Problem mit einem Timer

  • Antworten:1
Daniel online
  • Forum-Beiträge: 282

24.09.2011, 15:47:58 via Website

Hey,

ich will das der User alle paar Stunden eine Benachrichtigung von meiner App bekommt.
Ich löse das mit einem Service der bei App start und OnBoot gestartet wird.
In der App erstelle ich dann einen Timer wie folgt:

1public void onCreate()
2 {
3 timer = new Timer();
4 }
5
6 @Override
7 public int onStartCommand(Intent intent, int flags, int startId)
8 {
9 if(pref_abgehakt.getBoolean("notifyMe", true))
10 {
11 getDatas();
12
13 if(timer!=null)timer.cancel();
14 timer = new Timer();
15 timer.scheduleAtFixedRate(new TimerTask(){
16
17 @Override
18 public void run() {
19 notifyMe();
20
21 }
22
23
24
25 }, zeitVerzögerung, zeitIntervall);
26 }
27 return START_STICKY;
28 }

Der Hauptbestandteil der notifyMe() Methode:
1Notification notification = new Notification(icon, tickerText, when);
2 notification.flags |= Notification.FLAG_AUTO_CANCEL;
3 CharSequence contentTitle = tickerText;
4 Intent notificationIntent = new Intent(this, main.class);
5 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
6
7 notification.setLatestEventInfo(getApplicationContext(), contentTitle,contentString, contentIntent);
8 final int HELLO_ID = 1;
9 mNotificationManager.cancel(HELLO_ID);
10
11 mNotificationManager.notify(HELLO_ID, notification);

Das funktioniert auch meistens. Nur manchmal bekommt man Nachrichten über Nachrichten. Also direkt wieder eine neue obwohl ich gerade erst darauf geklickt habe.
Ich habe es jetzt damit versucht den Timer vor dem Neustarten (wenn die App geöffnet wird wird auch der Service aufgerufen) zu canceln,
das hat das ganze zwar verbessert, das Problem tritt jetzt zwar seltener auf, aber weg ist es immer noch nicht.

MFG,
Daniel

Antworten
Ansgar M
  • Forum-Beiträge: 1.544

24.09.2011, 16:33:51 via Website

Hey,
ich würde das nicht über einen Timer lösen, sondern den AlarmManager benutzen..
Lg Ansgar

Antworten