2011-06-17 119 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

不要忘记接受答案(在左侧)。 –