内容转自 Android之Service与Activity通信机制 - 夏日小草 - SegmentFault 思否
0x01.Service生命周期
看一张网上的关于Service的生命周期
Service主要包含本地类和远程类。
Service主要在后台运行,我们可以在这里做网络状态监测,地理位置监测,以及系统状态监测等,然后通过broadcast广播,发送给前台进行处理。
Service不是Thread,Service 是android的一种机制,当它运行的时候如果是Local Service,那么对应的 Service 是运行在主进程的 main 线程上的。如:onCreate,onStart 这些函数在被系统调用的时候都是在主进程的 main 线程上运行的。如果是Remote Service,那么对应的 Service 则是运行在独立进程的 main 线程上。
0x02.Service的基本用法
启动service的方法很简单,首先在AndroidManifest.xml中注册才行。
其次,要在Activity运行时候调用Intent对象生成Service。
Intent startIntent = new Intent(MainActivity.this, MainService.class); startService(startIntent);
下面是service的基本调用方式,重写onCreate()、onStartCommand()和onDestroy()方法。
onCreate()只启动一次,onStartCommand()会在每次启动activity时候运行,onDestroy()只在service关闭时候运行。
publicclassMainServiceextendsService{@OverridepublicvoidonCreate(){super.onCreate(); }@OverridepublicintonStartCommand(Intent intent,intflags,intstartId){returnsuper.onStartCommand(intent, flags, startId); }@OverridepublicvoidonDestroy(){super.onDestroy(); }@OverridepublicIBinderonBind(Intent intent){returnnull; }}
0x03.Service通过IBinder与Activity通信
下面是主要源码。
MainService.java
publicclassMainServiceextendsService{privateString TAG ="MainService";publicServiceBinder mBinder =newServiceBinder();/* 数据通信的桥梁 *//* 重写Binder的onBind函数,返回派生类 */@OverridepublicIBinderonBind(Intent arg0){returnmBinder; }@OverridepublicvoidonCreate(){ Toast.makeText( MainService.this,"Service Create...", Toast.LENGTH_SHORT).show();super.onCreate(); }@OverridepublicintonStartCommand(Intent intent,intflags,intstartId){ Toast.makeText(MainService.this,"Service StartCommand", Toast.LENGTH_SHORT).show();returnsuper.onStartCommand(intent, flags, startId); }@OverridepublicvoidonDestroy(){ Toast.makeText( MainService.this,"Service Destroy", Toast.LENGTH_SHORT).show(); }/* 第一种模式通信:Binder */publicclassServiceBinderextendsBinder{publicvoidstartDownload()throwsInterruptedException{/* 模拟下载,休眠2秒 */Toast.makeText( MainService.this,"模拟下载2秒钟,开始下载...", Toast.LENGTH_SHORT).show(); Thread.sleep(2); Toast.makeText( MainService.this,"下载结束...", Toast.LENGTH_SHORT).show(); } }}
MainActivity.java
publicclassMainActivityextendsActivity{/* 通过Binder,实现Activity与Service通信 */privateMainService.ServiceBinder mBinderService;privateServiceConnection connection =newServiceConnection() {@OverridepublicvoidonServiceDisconnected(ComponentName name){ }@OverridepublicvoidonServiceConnected(ComponentName name, IBinder service){ mBinderService = (MainService.ServiceBinder) service;try{ mBinderService.startDownload(); }catch(InterruptedException e) { e.printStackTrace(); } } };@OverridepublicvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent bindIntent =newIntent(MainActivity.this, MainService.class); bindService(bindIntent, connection, BIND_AUTO_CREATE); }}
0x04.Service通过BroadCast广播与Activity通信
关于广播的原理。
MainService.java
publicclassMainServiceextendsService{privateString TAG ="MainService";publicServiceBinder mBinder =newServiceBinder();/* 数据通信的桥梁 *//* 重写Binder的onBind函数,返回派生类 */@OverridepublicIBinderonBind(Intent arg0){returnnull; }@OverridepublicvoidonCreate(){ Toast.makeText( MainService.this,"Service Create, Send BroadCast...", Toast.LENGTH_SHORT).show(); SendServiceBroadCast();super.onCreate(); }@OverridepublicintonStartCommand(Intent intent,intflags,intstartId){ Toast.makeText(MainService.this,"Service StartCommand", Toast.LENGTH_SHORT).show();returnsuper.onStartCommand(intent, flags, startId); }@OverridepublicvoidonDestroy(){ Toast.makeText( MainService.this,"Service Destroy", Toast.LENGTH_SHORT).show(); }/* 第二种模式通信:Broadcast广播 */publicvoidSendServiceBroadCast()throwsInterruptedException{ Log.d(TAG,"ServiceThread===>>startDownload() executed===>>线程ID:"+Thread.currentThread().getId()); Toast.makeText( MainService.this,"Send BroadCast now...", Toast.LENGTH_SHORT).show(); Intent intent =newIntent(); intent.setAction("me.homeway.servicebinder.BroadcastTest"); intent.putExtra("value",1000); sendBroadcast(intent); Toast.makeText( MainService.this,"Sent! Did you receive?", Toast.LENGTH_SHORT).show(); }}
新建一个类,命名成 BroadcastTest.java 放在 me.homeway.servicebinder 包里面。
这里我们使用静态注册方式,所以要在AndroidManifest.xml中注册广播。
AndroidManifest.xml
...
BroadcastTest.java
publicclassBroadcastTestextendsBroadcastReceiver{privateNetworkInfonetInfo;privateConnectivityManagermConnectivityManager; public void onReceive(Contextcontext,Intentintent) {Bundleextras = intent.getExtras();if(extras !=null) {if(extras.containsKey("value")){/* 这里可以做下载,发包等事件 */Toast.makeText( context,"收到广播 => "+extras.get("value"),Toast.LENGTH_SHORT).show();System.out.println("Value is:"+extras.get("value")); } } }}
0x05.参考
0x01. http://www.vogella.com/tutorials/AndroidServices/article.html
0x02.http://blog.csdn.net/guolin_blog/article/details/11952435
0x03.http://www.tutorialspoint.com/android/android_services.htm
源码下载这里: ServiceBinder.zip
APK下载:ServiceBinder.apk
本文出自 夏日小草,转载请注明出处:http://homeway.me/2014/12/02/android-service-share-data-with-activity/
网友评论