1

I am a beginner. I want Toast from jobintentservice (onHandleWork) but crash my app. logcat error is : " can't toast on a thread that has not called looper.prepare()" i want learn work with handler in jobintentservice please help me.

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();

          }
      });

1 Answers1

0

you probebly figured it out by now, but for future readers, the error "can't toast on a thread that has not called looper.prepare()" simply means you must call ui related from ui thread.

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

you can find similiar questions here and here

itzik pichhadze
  • 101
  • 1
  • 3