1

我是初学者。我想要来自 jobintentservice (onHandleWork) 的 Toast,但我的应用程序崩溃了。logcat 错误是:“不能在未调用 looper.prepare() 的线程上敬酒”我想学习在 jobintentservice 中使用处理程序,请帮助我。

public class NotificationService extends JobIntentService {
    public static final String TAG = NotificationService.class.getSimpleName();
    Handler handler;

    public static void enqueuWork(Context context,Intent intent){
        enqueueWork(context,NotificationService.class,20,intent);
    }
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Start background Service", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        handler = new Handler();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        handler.post(new Runnable() {
          @Override
          public void run()
              Toast.makeText(NotificationService.this, "onhandlework", Toast.LENGTH_SHORT).show();

          }
      });
4

1 回答 1

0

您现在已经想通了,但是对于未来的读者来说,错误“无法在未调用 looper.prepare() 的线程上敬酒”仅仅意味着您必须从 ui 线程调用相关的 ui。

activity.runOnUiThread(new Runnable() {
@Override
public void run() {
    showToast(activity);
}});

你可以在这里这里找到类似的问题

于 2019-10-11T07:48:48.017 回答