什么時候使用startService?
答:APP在后台長時間運行並執行業務的時候,可以用服務,主要是看服務的特點(在后台長時間運行);
Service相關代碼:
package liudeli.service1.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class MyService4 extends Service { private final static String TAG = MyService4.class.getSimpleName(); private final static int RUN = 1; private final static int NOT_RUN = 0; private int runState; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { runState = RUN; new Thread(new BackgroundRun()).start(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); runState = NOT_RUN; } /** * startService 不能直接執行耗時操作,需要通過異步去執行耗時操作,Service只負責長時間到在后台服務運行 * Service是開啟主線程的,Service與Activity很類似,都是開啟運行主線程的 */ class BackgroundRun implements Runnable { @Override public void run() { while (runState == RUN) { Log.d(TAG, "Background Run ......"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
MainActivity4相關代碼:
public void startService(View view) { startService(new Intent(this, MyService4.class)); } public void stopService(View view) { stopService(new Intent(this, MyService4.class)); }
Log日志,Service去啟動線程一秒執行一次:
12-06 22:54:07.489 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:08.490 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:09.495 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:10.500 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:11.507 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:12.508 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:13.509 8204-8301/liudeli.service1 D/MyService4: Background Run ......