开发者

Status bar notifications in a timer

开发者 https://www.devze.com 2023-03-13 15:35 出处:网络
class Download extends TimerTask { public void run() { // do some computations that alter static variables
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消