android 中service的简单事例

android 中service的简单事例


源码


public class ServiceDemoActivity extends Activity {
	private static final String TAG = "ServiceDemoActivity";
	
	Button bindBtn;
	Button startBtn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        bindBtn = (Button)findViewById(R.id.bindBtn);
        startBtn = (Button)findViewById(R.id.startBtn);
        
        bindBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
			Log.e(TAG, "bindBtn");
				bindService(new Intent(ServiceDemo.ACTION), conn, BIND_AUTO_CREATE);
			}
		});
        
        startBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
			Log.e(TAG, "startBtn");
				startService(new Intent(ServiceDemo.ACTION));
			}
		});
    }
    
    ServiceConnection conn = new ServiceConnection() {
    	public void onServiceConnected(ComponentName name, IBinder service) {
			Log.e(TAG, "onServiceConnected");
		}
		public void onServiceDisconnected(ComponentName name) {
			Log.e(TAG, "onServiceDisconnected");
		}
	};
	@Override
	protected void onDestroy() {
		Log.e(TAG, "onDestroy unbindService");
		unbindService(conn);
		super.onDestroy();
	};
}



public class ServiceDemo extends Service {
	private static final String TAG = "ServiceDemo";
	public static final String ACTION = "com.example.servicedemoactivity.ServiceDemo";
	

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		Log.e(TAG, " onBind ");
		return null;
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		Log.e(TAG, " onCreate ");
		super.onCreate();
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		Log.e(TAG, " 1onStart ");
		super.onStart(intent, startId);
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.e(TAG, " onStartCommand ");
		return super.onStartCommand(intent, flags, startId);
	}

}






参考  http://aswang.iteye.com/blog/1424309