IntentService类没有在主ui线程上运行AsyncTask。必须从主线程调用方法execute,当前推断的线程是worker

时间:2015-07-31 15:49:31

标签: android multithreading android-asynctask

我最近发生了一个奇怪的问题。我正在调用名为NotificationService的服务,该服务扩展了IntentService类。现在在onHandleIntent(Intent intent)方法中,我调用异步任务。代码如下:

@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");
    }

}

NotificationAsyncTask是此服务中定义的私有类。现在我收到了错误 必须从主线程调用方法execute,当前推断的线程是worker。 我不明白这个执行方法是如何在主线程上运行的?请帮忙。

1 个答案:

答案 0 :(得分:23)

  

现在在onHandleIntent(Intent intent)方法中调用异步任务

在后台线程上调用

AsyncTask

您无法从后台线程执行AsyncTask

更重要的是,您不需要doInBackground()。只需使用onHandleIntent()代码并将其放入 output$condo=renderUI({ ConPages<-as.list(rep(0,condVar()+1)) for (i in 0:length(ConPages)){ ConPages[i]=lapply(paste("input.level==",i,sep=""),conditionalPanel,numericInput('clusters', 'Cluster count', 9, min = 1, max = 9)) } do.call(mainPanel,list(ConPages)) })