Service
main Activity用来启动和关闭Service,Count是Service实现类,Manifest中加<service android:name=".Count" />
public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startService(new Intent(this, Count.class)); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); stopService(new Intent(this, Count.class)); } }
public class Count extends Service { private boolean threadDisable; private int count; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); Log.v("count", "onCreate"); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); this.threadDisable = true; Log.v("count", "onDestroy"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub Log.v("count", "onStartCommand"); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while (!threadDisable) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } count++; Log.v("count", "Count is " + count); } } }).start(); return START_STICKY; } }
START_STICKY确保Service一直保持启动状态,但不能保证Intent被处理执行;START_REDLIVER_INTENT可以确保Service在意外终止后将自动重新运行并保证Intent被处理;START_NOT_STICKY在Service被意外终止后将停止运行