2011-06-17 168 views
0
class Download extends TimerTask 
{ 
    public void run() { 

     // do some computations that alter static variables 
      String str = ; // something from the computations 
     displayNotification(str); 
    } 

    private static final int NOTIFICATION_ID = 1; 

    public void displayNotification(String msg) 
    { 
     NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     Notification notification = new Notification(R.drawable.icon, msg, System.currentTimeMillis()); 

     // The PendingIntent will launch activity if the user selects this notification 
     PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, new Intent(this, ExpandNotification.class), 0); 

     notification.setLatestEventInfo(this, "Title", "Details", contentIntent); 
     // this line causes the trouble because "this" is not a context (i.e., Activity or Service) 

     manager.notify(NOTIFICATION_ID, notification); 
    } 
} 

問題:如何從定時器啓動通知?我是否創建一個外部服務類來這樣做?定時器中的狀態欄通知

非常感謝。作爲一個獨立的Android程序員,我很感激這個社區。

回答

1

通行證上下文類構造函數當你創建它的實例:

class Download extends TimerTask{ 
    Context context; 

    public Download(Context c){ 
    this.context=c; 
    } 

} 


//inside Activity or whatever 
    Download download=new Download(getApplicationContext()); 

然後用這個上下文變量創建通知。

+0

謝謝。這看起來很明顯,但我無法制造它。謝謝。 – user802023

+0

不要忘記接受答案(在左側)。 –