2013-05-17 119 views
0

我正在做一個應用程序來檢查現場比分。我不知道這是否是最好的方法,但我創建了一個Timertask,一個Service和Activity來通知。每x秒發送一次通知

Timertask每x秒檢查一次分數是否發生變化,如果發生變化,則通知服務。 如果通知服務,它會調用將通知用戶的活動。我的問題是我沒有打電話給該服務通知活動。

這裏是我的代碼(本例中,我沒拿分數,但一個變量i。

//import ... 

public class MyService extends Service{ 

    Notif notif = new Notif(); 

    private static final String TAG = "MyService"; 

    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onCreate"); 
    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onStart"); 
     Timer time = new Timer(); // Instantiate Timer Object 
     final ScheduleTask st = new ScheduleTask(); // Instantiate SheduledTask class 
     time.schedule(st, 0, 5000); // Create Repetitively task for every 1 secs 
    } 

    @Override 
    public void onDestroy() { 
     Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onDestroy"); 
    } 

    public void checkI(int i){ 
     if (i==3){ 
      notif.initializeUIElements(); 
     } 
    } 
} 

的TimerTask

import ... 

// Create a class extends with TimerTask 
public class ScheduleTask extends TimerTask { 
    MyService myService = new MyService(); 
    Notif notif = new Notif(); 
    int i = 0; 
    // Add your task here 
    public void run() { 
     i++; 
     System.out.println("affichage numero " + i); 
     myService.checkI(i); 
    } 

    public int getI() { 
     return i; 
    } 
} 

NOTIF

import ... 

public class Notif extends Activity { 

    private static final int NOTIFY_ME_ID = 1987; 
    private NotificationManager mgr = null; 
    ScheduleTask scheduleTask = new ScheduleTask(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    } 

    void initializeUIElements() { 
     Notification note = new Notification(R.drawable.ic_launcher, 
       "Welcome to MyDoople.com", System.currentTimeMillis()); 
     PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(
       this, MainActivity.class), Notification.FLAG_ONGOING_EVENT); 

     note.setLatestEventInfo(this, "MyDoople.com", "An Android Portal for Development", 
       i); 
     // note.number = ++count; 
     note.flags |= Notification.FLAG_ONGOING_EVENT; 

     mgr.notify(NOTIFY_ME_ID, note); 
    } 
} 

回答

2

服務可能如果需要資源,則由系統終止。根據您的要求,最好將AlarmManager用於periodi cally做點什麼。

這裏有更多的參考資料:[1][2]

+0

感謝的我要了解這個 – user1965878