Search code examples
androidandroid-notificationsandroid-notification-bar

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


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.


Solution

  • 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.