handler.postDelayed is not working in onHandleIntent method of IntentService

前端 未结 5 1942
猫巷女王i
猫巷女王i 2021-01-17 22:50
final Handler handler = new Handler();
LOG.d(\"delay\");
handler.postDelayed(new Runnable() {
    @Override public void run() {
        LOG.d(\"notify!\");
        /         


        
相关标签:
5条回答
  • 2021-01-17 23:23

    IntentService is not designed for such scenario. You can use a regular Service instead. You can put the handler inside the onStartCommand(). Don't forget to call stopSelf() on the Service instance to shut it down after the handler.postDelayed(){}

    0 讨论(0)
  • 2021-01-17 23:29

    Convert

    final Handler handler = new Handler();
    

    to

    final Handler handler = new Handler(Looper.getMainLooper());
    

    This worked for me.

    0 讨论(0)
  • 2021-01-17 23:32

    this is how i use handler:

    import android.os.Handler;
    
    Handler handler;
    //initialize handler
    handler = new Handler();
    
    //to start handler
    handler.post(runnableName);
    
    private Runnable runnableName= new Runnable() {
            @Override
            public void run() {
                //call function, do something
                handler.postDelayed(runnableName, delay);//this is the line that makes a runnable repeat itself
            }
    };
    
    0 讨论(0)
  • 2021-01-17 23:35

    Handlers and Services will be predictable when the device screen is on. If the devices goes to sleep for example the Handler will not be a viable solution.

    A much more better and reliable solution will be to use: AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    0 讨论(0)
  • 2021-01-17 23:38

    You are using looper of the main thread. You must create a new looper and then give it to your handler.

    HandlerThread handlerThread = new HandlerThread("background-thread");
    handlerThread.start();
    final Handler handler = new Handler(handlerThread.getLooper());
    handler.postDelayed(new Runnable() {
        @Override public void run() {
            LOG.d("notify!");
            // call some methods here
    
            // make sure to finish the thread to avoid leaking memory
            handlerThread.quitSafely();
        }
    }, 2000);
    

    Or you can use Thread.sleep(long millis).

    try {
        Thread.sleep(2000);
        // call some methods here
    
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    

    If you want to stop a sleeping thread, use yourThread.interrupt();

    0 讨论(0)
提交回复
热议问题