How to send notification from AsyncTask while main

2019-06-13 23:18发布

问题:

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.