当前位置: 首页 > 科技观察

android基础IntentService的使用

时间:2023-03-23 11:35:52 科技观察

服务简述1.前台服务和IntentService:前台服务可以保持运行,不会因为系统内存不足而被回收。service服务测试的准备代码我们用一个具体的案例来说明start和bind方法service服务的生命周期介绍。工程结果如下:1.在MainActivity.java中做一些初始化工作,代码如下:privatefinalstaticStringTAG="MyIntentService";privateMyIntentService.MyBinderbinder;privateServiceConnectionconnection=newServiceConnection(){@OverridepublicvoidonServiceConnected(ComponentNamename,IBinderservice){binder=(MyIntentService.MyBinder)service;binder.sayHello(name.getClassName());}@OverridepublicvoidonServiceDisconnected(ComponentNamename){Log.i(TAG,"servicedisconnect:"+name.getClassName());}};@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}2.创建一个简单的IntentService服务类:MyIntentServicepackagecom.example.linux.intentservicetest;importandroid.app.IntentService;importandroid.content.Intent;importandroid.os.Binder;importandroid.os.IBinder;导入android.util.日志;publicclassMyIntentServiceextendsIntentService{privatefinalstaticStringTAG="MyIntentService";privateMyBindermyBinder=newMyBinder();classMyBinderextendsBinder{publicvoidsayHello(Stringname){Log.i(TAG,"sayhellomethod:"+name);}publicvoidsayWorld(Stringname){Log.i(TAG,"sayworldmethod:"+name);}}@OverridepublicIBinderonBind(Intentintent){returnmyBinder;}publicMyIntentService(){super("MyIntentService");Log.i(TAG,"myintentserviceconstructor");}@OverridepublicvoidonCreate(){Log.i(TAG,"oncreate.");超级.onCreate();}@OverrideprotectedvoidonHandleIntent(Intentintent){Log.i(TAG,"handleintent:"+intent.getStringExtra("username")+",thread:"+Thread.currentThread());}@OverridepublicvoidonDestroy(){super.onDestroy();Log.i(TAG,"ondestroy.");}@OverridepublicintonStartCommand(Intentintent,intflags,intstartId){Log.i(TAG,"onstartcommand.");returnsuper.onStartCommand(intent,flags,startId);}@OverridepublicbooleanonUnbind(Intentintent){//默认返回falseStringusername=intent.getStringExtra("username");Log.i(TAG,"onunbind:"+super.onUnbind(intent)+",username:"+username);returntrue;}@OverridepublicvoidonRebind(Intentintent){Log.i(TAG,"onrebind");super.onRebind(intent);}}三、创建一个简单的前台服务类:FrontServicepackagecom.example.linux.intentservicetest;importandroid.app.Notification;importandroid.app.PendingIntent;importandroid.app.Service;importandroid.content.Intent;importandroid.os.IBinder;importandroid.util.Log;publicclassFrontServiceextendsService{privatefinalstaticStringTAG="MyIntentService";publicFrontService(){Log.i(TAG,"frontserviceconstructor");}@OverridepublicIBinderonBind(Intentintent){returnnull;}@OverridepublicvoidonCreate(){super.onCreate();Notification.Builderbuilder=新通知ation.Builder(这个);Intentintent=newIntent(this,MainActivity.class);PendingIntentpendingIntent=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("contenttitle").setContentText("contenttext");builder.setContentIntent(pendingIntent);Notificationnotify=builder.getNotification();notify.defaults=Notification.DEFAULT_ALL;开始前景(10,通知);}}四、在AndroidManifest.xml中注册服务与活动:Intent服务的使用1.在MainActivity中创建一个方法来启动和停止服务://启动服务publicvoidstartService(Viewview){Intentintent=newIntent();intent.putExtra("用户名","linux");intent.setClass(MainActivity.this,MyIntentService.class);启动服务(意图);}//停止服务publicvoidstopService(Viewview){Intentintent=newIntent();intent.setClass(MainActivity.this,MyIntentService.class);停止服务(意图);}2.在MainActivity中创建一个方法,绑定和解绑服务://BindingservicepublicvoidbindService(Viewview){Intentintent=newIntent();intent.setClass(MainActivity.this,MyIntentService.class);intent.putExtra("用户名","linux");booleanisBind=bindService(意图,连接,上下文。BIND_AUTO_CREATE);Log.i(TAG,"绑定服务:"+isBind);}//解绑服务publicvoidunbindService(Viewview){Intentintent=newIntent();intent.setClass(MainActivity.this,MyIntentService.class);解除绑定服务(连接);}3、运行结果:点击开始:03-2508:01:53.4608389-8389/?I/MyIntentService:myintentserviceconstructor。03-2508:01:53.4608389-8389/?I/MyIntentService:oncreate.03-2508:01:53.4758389-8389/?I/MyIntentService:onstartcommand.03-2508:01:53.4778389-8727/?I/MyIntentService:handleintent:linux,thread:Thread[IntentService[MyIntentService],5,main]03-2508:01:53.4788389-8389/?I/MyIntentService:ondestroy。点击停止:无输出点击绑定:03-2508:02:25.4218389-8389/?I/MyIntentService:bindservice:true03-2508:02:25.4228389-8389/?I/MyIntentService:myintentserviceconstructor。03-2508:02:25.4228389-8389/?I/MyIntentService:oncreate.03-2508:02:25.4328389-8389/?I/MyIntentService:sayhellomethod:com.example.linux.intentservicetest.MyIntentService点击解绑:03-2508:02:28.4868389-8389/?I/MyIntentService:onunbind:false,用户名:linux03-2508:02:28.4908389-8389/?I/MyIntentService:ondestroy。使用1.在MainActivity中创建启动前台服务的方法://前台服务的使用publicvoidfrontS服务(视图视图){Intentintent=newIntent();intent.setClass(MainActivity.this,FrontService.class);启动服务(意图);}2.运行结果:手机通知栏IntentService原理分析1.IntentService是继承Service的抽样方法:publicabstractclassIntentServiceextendsService二、intentService包含的一段引用如下:privatevolatileLoopermServiceLooper;privatevolatileServiceHandlermServiceHandler;私人字符串名;privatebooleanm重新交付;privatefinalclassServiceHandlerextendsHandler{publicServiceHandler(Looperlooper){super(looper);}@OverridepublicvoidhandleMessage(Messagemsg){onHandleIntent((Intent)msg.obj);stopSelf(msg.arg1);其次,服务启动时,先执行构造方法,然后执行onCreate方法,再执行onStartCommand方法。onStart方法在onStartCommand中执行(执行过程在android基础---->服务生命周期):onCreate方法,开启一个线程,获取Looper并初始化一个Handler@OverridepublicvoidonCreate(){//TODO:最好有一个选项来保持部分唤醒锁//在处理过程中,并有一个静态启动服务(上下文,意图)//启动服务的方法&;handoffawakelock.super.onCreate();HandlerThreadthread=newHandlerThread("IntentService["+mName+"]");thread.start();mServiceLooper=thread.getLooper();mServiceHandler=newServiceHandler(mServiceLooper);}onStart方法,使用上面的Handler发送信息@OverridepublicvoidonStart(Intentintent,intstartId){Messagemsg=mServiceHandler.obtainMessage();msg.arg1=startId;msg.obj=意图;mServiceHandler.sendMessage(消息);}onStartCommand方法,调用onStart方法,发送信息@OverridepublicintonStartCommand(Intentintent,intflags,intstartId){onStart(intent,startId);returnm重新投递?START_REDELIVER_INTENT:START_NOT_STICKY;}***上面的Handler获取信息,调用handleMessage方法,其中有stopSelf(msg.arg1)方法,停止Service:3.这里是service类的两个方法。源码是android6.0。Service中的onStart方法已被废弃:/***@deprecatedImplement{@link#onStartCommand(Intent,int,int)}。*/@DeprecatedpublicvoidonStart(Intentintent,intstartId){}在onStartCommand方法中publicintonStartCommand(Intentintent,intflags,intstartId){onStart(intent,st艺术编号);returnmStartCompatibility?START_STICKY_COMPATIBILITY:START_STICKY;}

最新推荐
猜你喜欢