How to run service not on main thread?

前端 未结 2 1896
春和景丽
春和景丽 2021-02-19 23:17

I\'m trying to launch service and then open socket to have connection with server.

On button click I create new Thread and then st

2条回答
  •  醉话见心
    2021-02-19 23:52

    You can use IntentService for this. Just launch it normally with an Intent from the main thread. onHandleIntent() method gets executed in background thread. Put your socket-code in there. Here is an example code.

    public class MyIntentService extends IntentService {
    
        public MyIntentService() {
            super("MyIntentService");
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            // this method is called in background thread
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }    
    }
    

    In your activity you start the service as following.

    startService(new Intent(this, MyIntentService.class));
    

    If you need a long-lasting service, you can create a normal service and start a thread there. Here is an example. Make sure you launch it as "foreground" service. This will allow service to run longer without been killed by Android.

    public class MyAsyncService extends Service {
    
        private AtomicBoolean working = new AtomicBoolean(true)
    
        private Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while(working.get()) {
                    // put your socket-code here
                    ...
                }
            }
        }
    
        @Override
        public void onCreate() {
    
            // start new thread and you your work there
            new Thread(runnable).start();
    
            // prepare a notification for user and start service foreground
            Notification notification = ...
            // this will ensure your service won't be killed by Android
            startForeground(R.id.notification, notification);
        }
    
        @Override
        public onDestroy() {
            working.set(false)
        }
    }
    

提交回复
热议问题