Класс IntentService не запускает AsyncTask в главной теме. Вызов метода должен быть вызван из основного потока, текущий вывод - рабочий
У меня есть странная проблема, которая произошла недавно. Я вызываю службу с именем NotificationService, которая расширяет класс IntentService. Теперь внутри метода onHandleIntent (намерение намерения) я делаю вызов асинхронной задачи. Код приведен ниже:
@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 - частный класс, определенный внутри этой службы. Теперь я получаю ошибку
Вызов метода должен быть вызван из основного потока, в настоящее время выведенный поток является рабочим.
Я не понимаю, как этот метод выполнения не работает в основном потоке? Пожалуйста, помогите.
Ответы
Ответ 1
Теперь внутри метода onHandleIntent (намерение намерения) я делаю вызов асинхронной задачи
onHandleIntent()
вызывается в фоновом потоке.
Вы не можете выполнить AsyncTask
из фонового потока.
Что еще более важно, вам не нужен AsyncTask
. Просто возьмите код doInBackground()
и поместите его в onHandleIntent()
.