每次开启服务须在清单文件中注册
<service android:name="com.huaxin.test.TestService" >
service>
开启服务有两种方法
1、start方式开启服务
startService(service);
package com.huaxin.test;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class TestService extends Service {
@Override
public IBinder onBind(Intent intent) {
System.out.println("++++++++++++onBind++++++++++++");
return new MyService();
}
class MyService extends Binder {
public TestService getService() {
return TestService.this;
}
}
@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();
}
}
将会执行:
当程序退出时,不会执行destory的方法,说明服务没有被销毁,还在后台运行,退出时后台也不会报异常
当执行stopService(service);方法时服务才会被销毁
bindService(service, conn, BIND_AUTO_CREATE);
service = new Intent(getApplicationContext(), TestService.class);
// 创建ServiceConnection
conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated stub
System.out.println("++++++++++onServiceConnected++++++++++");
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
System.out.println("++++++++++onServiceDisconnected++++++++++");
System.out.println();
}
};
**使用Bind开启服务会执行,但是退出程序后,后台会报错,但是用户不会感知到,执行 unbindService(conn);时就会销毁服务,但是没有执行onServiceConnected和onServiceDisconnected方法,说明Activity与Service还没有交互
**
要使Activity与Service之间可以传递信息需要在Service与Activity中做如下操作
Service中的操作
@Override
public IBinder onBind(Intent intent) {
System.out.println("++++++++++++onBind++++++++++++");
return new MyService();
}
class MyService extends Binder {
public TestService getService() {
return TestService.this;
Activity中的操作
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
// MyService myService = myService.getService();
MyService binder = (MyService) service;
testService = binder.getService();
System.out.println("++++++++++onServiceConnected++++++++++"
}
这时候就会执行Connection方法
**Service中的onBind方法中返回值是一个IBinder类型的接口,而Activity的onServiceConnection方法则需要一个IBinder类型的参数,接口不能实例化,因此需要创建一个内部类,创建自己的Binder使它继承Binder’,Binder是IBinder的一个子类,因此就会返回IBinder类型的参数给onServiceConnection方法,再在Activity里调用getService方
法就会得到Service的对象,这样,Activity就能和Service通信了**