android - IntentService 类未在主 ui 线程上运行 AsyncTask。方法execute必须从主线程调用,目前推断线程是worker

标签 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 是在此服务中定义的私有(private)类。现在我收到错误 方法execute必须从主线程调用,目前推断线程是worker.. 不明白这个execute方法怎么没有运行在主线程上?请帮忙。

最佳答案

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

onHandleIntent() 在后台线程上调用。

您不能从后台线程执行 AsyncTask

更重要的是,您不需要 AsyncTask。只需将您的 doInBackground() 代码放入 onHandleIntent() 即可。

关于android - IntentService 类未在主 ui 线程上运行 AsyncTask。方法execute必须从主线程调用,目前推断线程是worker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31750269/

相关文章:

Android AsyncTask 卡住 UI

java - AsyncTask 在 doinbackground() 上抛出错误 "Caused by java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Void[]"

php - android.os.NetworkOnMainThreadException : refactoring code to use AsyncTask?

java - InputStream - 处理网络变化

android - 是否可以通过 adb 安装应用程序但仍然获得 Google Market 更新?

c - OpenMP - 在并行 for 循环中调用外部函数

java - UDP - 多线程

android - viewHolder 类中的 notifyDataSetChanged

android - 处理音频插孔按钮

python - 如何同时运行 2 个列表的循环,以便循环中的每个项目都匹配? [Python]