Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntentService class not running AsyncTask on main ui thread. Method execute must be called from the main thread, currently inferred thread is worker

I have a weird problem that occurred recently. I am calling a service named NotificationService which extends IntentService class. Now inside the onHandleIntent(Intent intent) method i making call to an async task. The code is given below:

@Override
protected void onHandleIntent(Intent intent) {
    defPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    //int fiveMinutes = 1000 * 60 * 5;
    //Setting an alarm to call AlarmScheduler service now. This alarm scheduler service will set next days alarm to show notifications
    //based on the weekly schedule as obtained from server.
    Intent i = new Intent(NotificationService.this, ScheduleAlarms.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getService(NotificationService.this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarmManager = (AlarmManager) NotificationService.this.getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis(), pendingIntent);//Use AlarmManager.INTERVAL_DAY instead of int number here.

    //Check if locally notifications are enabled by the user then only show notification depending on
    //if there are any latest notifications to be shown.
    if(defPrefs.getBoolean(getString(R.string.notifications),true)) {
        NotificationAsyncTask httpAsyncTask1 = new NotificationAsyncTask();
        httpAsyncTask1.mOnHttpResponseListener = new GetHomeResponse(intent);
        httpAsyncTask1.execute("http://" + HttpAsyncTask.IP_ADDRESS + "/v5/getResult");
    }else{
        Log.v("NotificationService","Disabled");
    }

}

Where NotificationAsyncTask is a private class defined inside this service. Now i am getting the error Method execute must be called from the main thread, currently inferred thread is worker.. I don't understand how this execute method is not running on the main thread? Please help.

like image 442
FingerSmith Avatar asked Jul 31 '15 15:07

FingerSmith


1 Answers

Now inside the onHandleIntent(Intent intent) method i making call to an async task

onHandleIntent() is called on a background thread.

You cannot execute an AsyncTask from a background thread.

More importantly, you do not need an AsyncTask. Just take your doInBackground() code and put it in onHandleIntent().

like image 195
CommonsWare Avatar answered Oct 30 '22 10:10

CommonsWare