开发Service需要两个步骤
(1)定义一个继承Service的子类
public class MyService extends Service {
@Override
//当该Service被第一次创建后将立即回调该方法
public void onCreate() {
super.onCreate();
Log.d("11111111onCreate","onCreate");
}
@Override
//每次客户端调用startService(Intent)方法启动该Service时,都会回调该方法
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("11111111onStartCommand","onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
//Service被关闭之前回调
public void onDestroy() {
super.onDestroy();
Log.d("1onDestroy", "111111111");
}
@Nullable
@Override
//Service子类必须实现的方法,该方法返回一个IBinder对象,应用程序可以通过该对象与Service组件通信
public IBinder onBind(Intent intent) {
Log.d("onBind", "11111111");
return null;
}
}
(2)在AndroidManifest.xml文件中配置该Service
<service android:name=".MyService">
<intent-filter>
<!--用于说明该Service可被那些Intent启动-->
<action android:name="com.sercice"></action>
</intent-filter>
</service>
在程序中运行该Service
运行有两种方式
(1)startService():访问者与Service没有关联,访问者退出,服务仍然运行
(2)bindService( ) :访问者与Service绑定在一起,访问者一旦退出,Service终止!
运行如下
public void onClick(View v) {
switch (v.getId()){
case R.id.button_start:
// Intent intent=new Intent(getApplicationContext(),MyService.class);
Intent intent=new Intent("com.sercice");
startService(intent);
break;
case R.id.button_stop:
// Intent intent1=new Intent(getApplicationContext(),MyService.class);
Intent intent1=new Intent("com.sercice");
stopService(intent1);
break;
}
}
启动服务调用
09-08 14:28:05.678 18783-18783/? D/onCreate﹕ onCreate
09-08 14:28:05.678 18783-18783/? D/onStartCommand﹕ onStartCommand
关闭服务
09-08 14:28:53.286 18783-18783/? D/1onDestroy﹕
当关闭界面时,Service扔运行