【问题标题】:IntentService class not running AsyncTask on main ui thread. Method execute must be called from the main thread, currently inferred thread is workerIntentService 类未在主 ui 线程上运行 AsyncTask。方法execute必须从主线程调用,目前推断线程为worker
【发布时间】:2015-07-31 15:49:31
【问题描述】:

我最近遇到了一个奇怪的问题。我正在调用一个名为 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.. 我不明白这个执行方法怎么不在主线程上运行?请帮忙。

【问题讨论】:

    标签: android multithreading android-asynctask


    【解决方案1】:

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

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

    您不能从后台线程执行AsyncTask

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

    【讨论】:

    • 是的,对,我不需要 AsyncTask..之前没有考虑过。谢谢你的提示。在我的通知中还有一件事我只想显示大图标,那么如何禁用小图标,因为必须设置小图标(在 NotificationCompat.Builder 实例上使用 .setSmallIcon())?
    • 虽然执行语句带有红色下划线,但异步任务正在执行中......
    • @FingerSmith:“在我的通知中还有一件事我只想显示大图标”——您必须构建自己的移动操作系统。小图标显示在状态栏中,它的存在是不可协商的。
    • 实际上,当我同时使用小图标和大图标时,在通知抽屉中查看的小图标无法正确呈现,只看到一个小的空白灰色方块,尽管我在状态中清楚地看到它bar..你能建议问题可能是什么吗?
    • @Dpedrinha:“在这种情况下,我应该复制代码吗?” - 不。您将代码放在AsyncTaskIntentService 都可以访问的公共位置(例如Java 类)。
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多