android开发之Service的使用

来源:互联网 发布:msp430用什么软件编程 编辑:程序博客网 时间:2024/06/07 05:41

实现步骤:

1、定义Service子类

public class LocalService extends Service {

@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubLog.d("onBind", "onBind");return new LocalIBinder();}@Overridepublic void onCreate() {// TODO Auto-generated method stubLog.d("onCreate", "onCreate");super.onCreate();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog.d("onStartCommand", "onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {Log.d("onDestroy", "onDestroy");super.onDestroy();}<span style="white-space:pre"></span>//通信的关键class LocalIBinder extends Binder {public void test() {Log.d("LocalIBinder", "test");}}}
2、AndroidManifest.xml中注册

<service android:name="com.example.android_test_service.LocalService"             ></service>
3、具体使用如下所示(两种方式):

startService方式

a.多次执行startService,运行结果如下图所示

service = new Intent(MainActivity.this, LocalService.class);
startService(service);


b.执行stopService,运行结果如下图所示

stopService(service);

bindService方式

a.多次执行bindService,运行结果如下所示

//监听接口

<span style="font-family: Arial, Helvetica, sans-serif;">serviceConnection = new ServiceConnection() {</span>
<span style="white-space:pre"></span>//Called when a connection to the Service has been lost.  This typically happens when the process hosting the service has crashed <span style="white-space:pre"></span>//or been killed. This does <em>not</em> remove the ServiceConnection itself -- this binding to the service will remain active, and you wil<span style="white-space:pre"></span>//l receive a call to <code><a target=_blank href="eclipse-javadoc:%E2%98%82=android_test_service/F:%5C/mzhd%5C/software_develop%5C/android_sdk%5C/platforms%5C/android-23%5C/android.jar%3Candroid.content(ServiceConnection.class%E2%98%83ServiceConnection~onServiceDisconnected~Landroid.content.ComponentName;%E2%98%82%E2%98%82onServiceConnected">onServiceConnected</a></code> when the Service is next running.
@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stubLog.d("onServiceDisconnected", "onServiceDisconnected");}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubLog.d("onServiceConnected", "onServiceConnected");((LocalIBinder)service).test();}};
bindService(service, serviceConnection, BIND_AUTO_CREATE);

b.执行unBindService,运行结果如下

unbindService(serviceConnection);


c.再次执行unBindService,出现异常





0 0