user3650191
user3650191

Reputation: 369

Calling asynctask from GCMBaseIntentService?

Hello I have this code in my GCMIntenBaseIntenService

 @Override
    protected void onMessage(Context context, Intent intent) {

        AsyncTask taskDoStuff= new AsyncTask (context);
        taskDoStuff.execute();

    }

my AsyncTask is looking like:

public class AsyncTask extends AsyncTask<String,String,String> {


Context mContext;



    public AsyncTask(Context mContext) {
    this.mContext = mContext;

}

when I call my asynctask from my main ACTIVITY directly it works - AsyncTask runs and does its job... But when I try to call asynctask from GCMBaseIntentService it does not does it job - surely because of wrong context...

How can I solve that?

used: http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ as basic

EDIT:

I did some change, now it works in the background , but app crashes:

In my MainActivity i set

public static Context getAppContext() {
        return MainActivity.mContext;
    }

in onCreate:

MainActivity.mContext = MainActivity.this;

in gcm onMessag()

AsyncTask taskDoStuff = new AsyncTask(MainActivity.getAppContext());
        taskDoStuff.execute();

Upvotes: 2

Views: 162

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 199795

GCMBaseIntentService extends IntentService which per the documentation:

the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

Which means that as soon as onMessage completes, the service is killed.

As onMessage() is already on a worker thread, you can do your background work directly in onMessage() rather than needing an AsyncTask at all.

If you really, really need to reuse an AsyncTask, you can use taskDoStuff.get() instead of taskDoStuff.execute() to retrieve the results using the current thread.

Upvotes: 1

Related Questions