Thread 主要用来执行异步操作
service 是android的一种机制, 比如在后台执行播放音乐之类的
生命周期: onCreate onStartCommand onUnbind onDestroy
Intent intent = new Intent(ServiceTestActivity.this,
MyService.class);startService(intent);
// 会调用 onCreate onStartCommand 如果已启动servce 只会调用onStartCommand
public class CountService extends Service { private boolean threadDisable; private int count; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); new Thread(new Runnable() { @Override public void run() { while (!threadDisable) { try { Thread.sleep(1000); } catch (InterruptedException e) { } count++; Log.v("CountService", "Count is " + count); } } }).start(); } @Override public void onDestroy() { super.onDestroy(); this.threadDisable = true; Log.v("CountService", "on destroy"); } public int getCount() { return count; } }
public class LocalServiceDemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.startService(new Intent(this, CountService.class)); } @Override protected void onDestroy() { super.onDestroy(); this.stopService(new Intent(this, CountService.class)); } }