android-How to run Service in different thread than main thread?

前端 未结 5 1856
旧时难觅i
旧时难觅i 2021-02-18 14:12

I am trying to develop a application in android that consists a service to read the sensor value for multiple hours. When i start the service my device get hang and all the othe

5条回答
  •  梦谈多话
    2021-02-18 14:58

    All you are doing there is launching the new activity, so if your logic for running the monitor is in SensorService, then it's still going to be on the main thread. You need to put the monitoring logic into the new thread, not just launch the activity with it.

    If you are trying to run a service on a background thread you need to use the static performOnBackgrounThread method like this code which can be found in the Android documentation (android-8\SampleSyncAdapter\src\com\example\android\samplesync\client\NetworkUtilities.java):

    public static Thread performOnBackgroundThread(final Runnable runnable) {
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {
    
                }
            }
        };
        t.start();
        return t;
    }
    

    It is also important to remember that you never want to perform network operations on the Main UI thread. Not that you have here, just a FYI...

提交回复
热议问题