Status bar notifications in a timer
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开发者_StackOverflow中文版 Service)
        manager.notify(NOTIFICATION_ID, notification);
    }
}
Question: How can I launch a notification from the timer? Do I create an external Service class to do so?
Thanks so much. As a solo Android programmer, I am grateful for this community.
Pass context to your class constructor when you create its instance:
class Download extends TimerTask{
   Context context;
   public Download(Context c){
     this.context=c;
   }
}
 //inside Activity or whatever
    Download download=new Download(getApplicationContext());
Then use this context variable to create Notification.
 加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论