知识要点:
- service是无界面的,可运行在后台,处理耗时(放在线程中),监听等任务;
- service有两种启动方式:start、bind
service生命周期:
两种启动方式区别:
start方式用法
- 定义MyStartService 类,继承service
public class MyStartService extends Service{
@Override
public void onCreate() {
System.out.println("onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
System.out.println("onDestroy");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
2、manifest文件中注册哦
<service android:name="com.bzx.androidlearning.MyStartService"></service>
3、activity中启动
Intent intent = new Intent(MainActivity.this,MyStartService.class);
startService(intent);
4、销毁service
stopService(intent);
注意start方式service,启动后,依次onCreate、onStartCommand,销毁时onDestroy,多次start,只会执行一次onCreate
bind方式用法
1、同样定义MyBindService ,继承Service。注意manifest中注册。启动顺序是onCreate、onBind。onBind会返回接口,这里自定义一个MyBinder 类继承Binder,内部方法返回MyBindService。并在onBind中返回MyBinder实例。passMessage为自定义方法,供activity中调用。
public class MyBindService extends Service{
public class MyBinder extends Binder{
public MyBindService getService(){
return MyBindService.this;
}
}
@Override
public void onCreate() {
System.out.println("onCreate");
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
System.out.println("onBind");
return new MyBinder();
}
@Override
public void unbindService(ServiceConnection conn) {
System.out.println("unbindService");
super.unbindService(conn);
}
@Override
public void onDestroy() {
System.out.println("onDestroy");
super.onDestroy();
}
public void passMessage(Context context){
Toast.makeText(context, "调用service中方法", Toast.LENGTH_SHORT).show();
}
}
2、activity中启动service。其中创建一个ServiceConnection实例,重新两个方法。onServiceConnected中,获取传过来的binder对象,进而获得Service对象myBindService 。myBindService.passMessage(Context)调用service中方法。
MyBindService myBindService;
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myBindService = ((MyBinder)service).getService();
}
};
intent = new Intent(MainActivity.this,MyBindService.class);
bindService(intent, connection, BIND_AUTO_CREATE);