服务的简单说明
一、 前台服务与IntentService:
前台服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收
service服务测试的准备代码
我们通过一个具体的案例来说明start与bind方式的service服务的生命周期的介绍。项目结果如下:
一、 在MainActivity.java中做一些初始化工作,如下代码:
privatefinalstaticString TAG ="MyIntentService";
privateMyIntentService.MyBinder binder;
privateServiceConnection connection =newServiceConnection() {
@Override
publicvoidonServiceConnected(ComponentName name, IBinder service) {
binder = (MyIntentService.MyBinder) service;
binder.sayHello(name.getClassName());
}
@Override
publicvoidonServiceDisconnected(ComponentName name) {
Log.i(TAG,"service disconnect: "+ name.getClassName());
}
};
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
二、 创建一个简单的IntentService服务类:MyIntentService
packagecom.example.linux.intentservicetest;
importandroid.app.IntentService;
importandroid.content.Intent;
importandroid.os.Binder;
importandroid.os.IBinder;
importandroid.util.Log;
publicclassMyIntentServiceextendsIntentService {
privatefinalstaticString TAG ="MyIntentService";
privateMyBinder myBinder =newMyBinder();
classMyBinderextendsBinder {
publicvoidsayHello(String name) {
Log.i(TAG,"say hello method: "+ name);
}
publicvoidsayWorld(String name) {
Log.i(TAG,"say world method: "+ name);
}
}
@Override
publicIBinder onBind(Intent intent) {
returnmyBinder;
}
publicMyIntentService() {
super("MyIntentService");
Log.i(TAG,"myintent service constructor.");
}
@Override
publicvoidonCreate() {
Log.i(TAG,"on create.");
super.onCreate();
}
@Override
protectedvoidonHandleIntent(Intent intent) {
Log.i(TAG,"handle intent: "+ intent.getStringExtra("username") +", thread: "+ Thread.currentThread());
}
@Override
publicvoidonDestroy() {
super.onDestroy();
Log.i(TAG,"on destroy.");
}
@Override
publicintonStartCommand(Intent intent,intflags,intstartId) {
Log.i(TAG,"on start command.");
returnsuper.onStartCommand(intent, flags, startId);
}
@Override
publicbooleanonUnbind(Intent intent) {
//默认返回false
String username = intent.getStringExtra("username");
Log.i(TAG,"on unbind: "+super.onUnbind(intent) +", username: "+ username);
returntrue;
}
@Override
publicvoidonRebind(Intent intent) {
Log.i(TAG,"on rebind");
super.onRebind(intent);
}
}
三、 创建一个简单的前台服务类:FrontService
packagecom.example.linux.intentservicetest;
importandroid.app.Notification;
importandroid.app.PendingIntent;
importandroid.app.Service;
importandroid.content.Intent;
importandroid.os.IBinder;
importandroid.util.Log;
publicclassFrontServiceextendsService {
privatefinalstaticString TAG ="MyIntentService";
publicFrontService() {
Log.i(TAG,"front service constructor");
}
@Override
publicIBinder onBind(Intent intent) {
returnnull;
}
@Override
publicvoidonCreate() {
super.onCreate();
Notification.Builder builder =newNotification.Builder(this);
Intent intent =newIntent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
builder.setSmallIcon(R.mipmap.ic_launcher).setTicker("ticker");
builder.setWhen(System.currentTimeMillis()).setAutoCancel(true);
builder.setContentTitle("content title").setContentText("content text");
builder.setContentIntent(pendingIntent);
Notification notify = builder.getNotification();
notify.defaults = Notification.DEFAULT_ALL;
startForeground(10, notify);
}
}
四、 在AndroidManifest.xml中注册服务与活动:
android:name=".MyIntentService"
android:exported="false">
android:name=".FrontService"
android:enabled="true"
android:exported="true">
Intent服务的使用
一、 在MainActivity中创建方法,启动停止服务:
// 开启服务
publicvoidstartService(View view) {
Intent intent =newIntent();
intent.putExtra("username","linux");
intent.setClass(MainActivity.this, MyIntentService.class);
startService(intent);
}
// 停止服务
publicvoidstopService(View view) {
Intent intent =newIntent();
intent.setClass(MainActivity.this, MyIntentService.class);
stopService(intent);
}
二、 在MainActivity中创建方法,绑定解绑服务:
// 绑定服务
publicvoidbindService(View view) {
Intent intent =newIntent();
intent.setClass(MainActivity.this, MyIntentService.class);
intent.putExtra("username","linux");
booleanisBind = bindService(intent, connection, Context.BIND_AUTO_CREATE);
Log.i(TAG,"bind service: "+ isBind);
}
// 解绑服务
publicvoidunbindService(View view) {
Intent intent =newIntent();
intent.setClass(MainActivity.this, MyIntentService.class);
unbindService(connection);
}
三、 运行结果:
点击start:
03-25 08:01:53.460 8389-8389/? I/MyIntentService: myintent service constructor.
03-25 08:01:53.460 8389-8389/? I/MyIntentService: on create.
03-25 08:01:53.475 8389-8389/? I/MyIntentService: on start command.
03-25 08:01:53.477 8389-8727/? I/MyIntentService: handle intent: linux, thread: Thread[IntentService[MyIntentService],5,main]
03-25 08:01:53.478 8389-8389/? I/MyIntentService: on destroy.
点击stop:无输出
点击bind:
03-25 08:02:25.421 8389-8389/? I/MyIntentService: bind service:true
03-25 08:02:25.422 8389-8389/? I/MyIntentService: myintent service constructor.
03-25 08:02:25.422 8389-8389/? I/MyIntentService: on create.
03-25 08:02:25.432 8389-8389/? I/MyIntentService: say hello method: com.example.linux.intentservicetest.MyIntentService
点击unbind:
03-25 08:02:28.486 8389-8389/? I/MyIntentService: on unbind:false, username: linux
03-25 08:02:28.490 8389-8389/? I/MyIntentService: on destroy.
前台服务的使用
一、 在MainActivity中创建方法,启动前台服务:
// 前台服务的使用
publicvoidfrontService(View view) {
Intent intent =newIntent();
intent.setClass(MainActivity.this, FrontService.class);
startService(intent);
}
二、 运行结果: 在手机的通知栏中
IntentService的原理分析
一、 intentService是继承Service的抽象方法:
publicabstractclassIntentServiceextendsService
二、 intentService包含的一些字段引用如下:
privatevolatileLooper mServiceLooper;
privatevolatileServiceHandler mServiceHandler;
privateString mName;
privatebooleanmRedelivery;
privatefinalclassServiceHandlerextendsHandler {
publicServiceHandler(Looper looper) {
super(looper);
}
@Override
publicvoidhandleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
二、 和service一样在启动的时候,首先是执行构造方法,接着是onCreate方法,然后是onStartCommand方法,在onStartCommand中执行了onStart方法(执行流程在android基础---->service的生命周期讲过):
onCreate方法,开启了一个线程,并且得到Looper与初始化了一个Handler
@Override
publicvoidonCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread =newHandlerThread("IntentService["+ mName +"]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler =newServiceHandler(mServiceLooper);
}
onStart方法,用上述的Handler发送信息
@Override
publicvoidonStart(Intent intent,intstartId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
onStartCommand方法,调用onStart方法,发送信息
@Override
publicintonStartCommand(Intent intent,intflags,intstartId) {
onStart(intent, startId);
returnmRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
***上述的Handler得到信息,调用handleMessage方法,其中有stopSelf(msg.arg1)方法,停止了服务:
三、 这里附上service类的两个方法,源代码是android6.0的
在Service中的onStart方法已经被废弃了:
/**
* @deprecated Implement {@link #onStartCommand(Intent, int, int)} instead.
*/
@Deprecated
publicvoidonStart(Intent intent,intstartId) {
}
在onStartCommand的方法中
publicintonStartCommand(Intent intent,intflags,intstartId) {
onStart(intent, startId);
returnmStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
}
【编辑推荐】
【责任编辑:齐琳 TEL:(010)68476606】
点赞 0