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程序员,我很感激这个社区。 p>
答案 0 :(得分:1)
在创建实例时将上下文传递给类构造函数:
class Download extends TimerTask{
Context context;
public Download(Context c){
this.context=c;
}
}
//inside Activity or whatever
Download download=new Download(getApplicationContext());
然后使用此上下文变量创建通知。