How to send notification from AsyncTask while main Activity is not started?

 ̄綄美尐妖づ 提交于 2019-12-08 11:03:09

问题


I have an AsyncTask which starts on boot (called by a service). In some cases I would like to send a notification to start the main Activity. My problem comes when I try to call:

NotificationManager notManager = (NotificationManager) getSystemService(ns);

where eclipse shows me an error because AsyncTask hasn't got getSystemService method. Any idea?

Thank you.


回答1:


Because getSystemService is a method of Context class. Check it out here.

Before you call the function, create a Context variable in your AsyncTask. Then initialize it in your constructor, i.e.

Context context;

public MyAsyncTask(Context contextin)
{ context = contextin;}

Then use this context variable to call your function:

NotificationManager notManager = (NotificationManager) context.getSystemService(ns);

Do not forget to input your context when you are executing AsyncTask:

MyAsyncTask mytask = new MyAsyncTask(getApplicationContext());
mytask.execute();

I also have a feeling that an IntentService would be more suitable for your needs.




回答2:


You could start a service that launches your application at the end of the background thread in your asynctask.



来源:https://stackoverflow.com/questions/11443787/how-to-send-notification-from-asynctask-while-main-activity-is-not-started

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!