处理程序在我的后台服务中没有在延迟时间工作

时间:2016-10-05 05:43:45

标签: android service handler

我必须在 MyService.java 类中不断执行某项任务。为此,我使用Handler mHandler.postDelayed(此为40000); 在给定时间后没有被触发。它每秒都会被解雇。请帮帮我

public class SendMessageService extends Service {

    private Handler mHandler = new Handler();
    private Runnable task;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        registerReceiver(stopReceiver, new IntentFilter("com.android.STOP_HANDLER"));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        task = new Runnable() {
            @Override
            public void run() {

                dosomething();
                mHandler.postDelayed(this, 40000);
            }
        };

        try {

            mHandler.postDelayed(task, 40000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(stopReceiver);
    }

    private void dosomething() {
       //perform my task
    }

    private BroadcastReceiver stopReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("receive","STOP");
            mHandler.removeCallbacks(task);
        }
    };
}

1 个答案:

答案 0 :(得分:0)

我将代码更改为此代码并且正在运行

 public class SendMessageService extends Service {

        private Handler mHandler = new Handler();


        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onCreate() {
            super.onCreate();

            registerReceiver(stopReceiver, new IntentFilter("com.android.STOP_HANDLER"));
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {



            try {

                mHandler.postDelayed(task, 40000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return START_STICKY;
        }


        @Override
        public void onDestroy() {
            super.onDestroy();
            unregisterReceiver(stopReceiver);
        }

        private void dosomething() {
           //perform my task
        }

        private BroadcastReceiver stopReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("receive","STOP");
                mHandler.removeCallbacks(task);
            }
        };


 private Runnable task = new Runnable() {
                @Override
                public void run() {

                    dosomething();
                    mHandler.postDelayed(this, 40000);
                }
            };
    }