1. 定义一个服务
创建一个MyService 类继承Service
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("MyService", "onCreate executed");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService", "onDestroy executed");
}
}
注意:服务需要在AndroidManifest文件中进行注册:
<service android:name=".MyService" ></service>
2. 启动和停止服务
在布局中添加两个按钮,用于启动和停止服务:
<Button
android:id="@+id/start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Service" />
<Button
android:id="@+id/stop_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop Service" />
在MainActivity中添加点击事件:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button)findViewById(R.id.start_service);
stopService = (Button)findViewById(R.id.stop_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.start_service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
break;
case R.id.stop_service:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
break;
}
其中,启动和停止一个服务的方法都很简单,与启动Activity的方法类似。先构造出一个Intent,再调用startService 或stopService 方法即可。
如果服务需要中途停止,可以在服务中调用stopSelf()f函数。
通过打印的日志可以发现,在第一次点击Start Service 按钮的时候,MyService 的onCreate 方法和onStartCommand 方法都会被调用,之后只有onStartCommand 方法会被调用。点击Stop Service 按钮,onDestroy 方法会被调用。