参考:http://blog.csdn.net/very_caiing/article/details/42040997
实现
1、新建一个继承Service的类
public class Service3 extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
onBind方法用于和Activity进行交互的。
Service.onBind如果返回null,则调用 bindService 会启动 Service,但不会连接上 Service,因此 ServiceConnection.onServiceConnected 不会被调用,但你任然需要使用 unbindService 函数断开它,这样 Service 才会停止。
此处先返回null,具体下面再说。
下面的类是回调了Service一些基本方法。
public class ServiceEasy extends Service {
private static final String TAG = "hq";
public static final String ACTION = "com.example.servicedemoactivity.ServiceDemo";
@Override
public IBinder onBind(Intent arg0) {
Log.e(TAG, " onBind ");
return null;
}
@Override
public void onCreate() {
Log.e(TAG, " onCreate ");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Log.e(TAG, " onStart ");
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, " onStartCommand ");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, " onDestroy ");
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
Log.e(TAG, " onUnbind ");
return super.onUnbind(intent);
}
}
2、调用Service
2.1创建一个开启Service的意图–serviceIntent
方式1、(可能会有警告)
Intent start1 = new Intent(this, Service1.class);
方式2、(学习Service期间可先跳过)
Intent serviceIntent1 = new Intent();
serviceIntent1.setAction(ServiceEasy .ACTION);
Intent serviceIntent = new Intent(Util.getExplicitIntent(ServiceDemoActivity.this, serviceIntent1));
public static Intent getExplicitIntent(Context context,
Intent implicitIntent) {
// Retrieve all services that can match the given intent
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent,
0);
// Make sure only one match was found
if (resolveInfo == null || resolveInfo.size() != 1) {
return null;
}
// Get component info and create ComponentName
ResolveInfo serviceInfo = resolveInfo.get(0);
String packageName = serviceInfo.serviceInfo.packageName;
String className = serviceInfo.serviceInfo.name;
ComponentName component = new ComponentName(packageName, className);
// Create a new intent. Use the old one for extras and such reuse
Intent explicitIntent = new Intent(implicitIntent);
// Set the component to be explicit
explicitIntent.setComponent(component);
return explicitIntent;
}
备注:有些时候我们使用Service的时需要采用隐私启动的方式,但是Android5.0一出来后,其中有个特性就是Service Intent must be explitict,也就是说从Lollipop开始,service服务必须采用显示方式启动。源:http://www.mamicode.com/info-detail-590854.html
2.2开启Service
方式一:
startService 启动服务,不管Local 还是 Remote 我们需要做的工作都是一样简单。
开启:startService(serviceIntent);
关闭:stopService(serviceIntent);
当然要记得在 Androidmanifest.xml 中注册 service。
<service android:name="com.example.servicedemoactivity.ServiceDemo">
<intent-filter >
<action android:name="com.example.servicedemoactivity.ServiceDemo"/>
</intent-filter>
</service>
方式二:
bindService启动服务。
bindService(Intent service, ServiceConnection conn, int flags)方法有三个参数
第一个Intent已经定义好了
第二个参数ServiceConnection,实现了 ServiceConnection 接口的对象
第三个参数是标志位,,BIND_DEBUG_UNBIND 与 BIND_AUTO_CREATE,前者用于调试,后者默认使用
下面创建ServiceConnection:
ServiceConnection conn1 = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
//①Service中需要创建一个实现IBinder的内部类(这个内部类不一定在Service中实现,但必须在Service中创建它)。在OnBind()方法中需返回一个IBinder实例,不然onServiceConnected方法不会调用。
Log.e(TAG, " onServiceConnected");
}
//在连接正常关闭的情况下是不会被调用的, 该方法只在Service 被破坏了或者被杀死的时候调用.例如, 系统资源不足, 要关闭一些Services, 刚好连接绑定的 Service 是被关闭者之一, 这个时候onServiceDisconnected() 就会被调用
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG, " onServiceDisconnected");
}
};
绑定Service:
bindService(serviceIntent, conn, BIND_AUTO_CREATE);
解绑:
unbindService(conn);
应用:Service与Activity交互
实现Service的onBind
定义一个MyBinder类,里面实现了两个方法,提供给Activity调用
class MyBinder extends Binder{
public void doSomething(){
Log.d(TAG, "在Binder中作的操作和Acty通信");
}
public void changeUI(TextView view,String text){
view.setText(text);
}
}
更改onBind方法的返回值为更改设置的MyBinder
private MyBinder mBinder= new MyBinder();
@Override
public IBinder onBind(Intent arg0) {
Log.e(TAG, " onBind ");
return mBinder;
}
在Activity中,只要更改ServiceConnection就行了,添加需要调用的binder方法。
ServiceConnection conn = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e(TAG, " onServiceConnected");
myBinder = (ServiceDemo.MyBinder) service;
myBinder.doSomething();//打印一个日志
myBinder.changeUI(changeTV, "哈哈哈哈哈~~");//改变TextView的内容
}
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG, " onServiceDisconnected");
}
};
应用一:
在Service创建时直接调用打开Notification的方法
public class Service1 extends Service {
private NotificationManager nm;
@Override
public void onCreate() {
super.onCreate();
Log.i("hq", "Service1 onCreate");
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
private void showNotification() {
Notification notification = new Notification(R.drawable.ic_launcher,
"Service started", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AnotherActy.class), 0);
// must set this for content view, or will throw a exception
notification.setLatestEventInfo(this, "Test Service",
"Service started", contentIntent);
nm.notify("111",0, notification);
}
@Override
@Deprecated
public void onStart(Intent intent, int startId) {
Log.i("hq", "Service1 onStart");
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
Log.i("hq", "Service1 onDestroy");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
Log.i("hq", "Service1 onBind:实现与Activity交互");
return null;
}
@Override
public boolean onUnbind(Intent intent) {
Log.i("hq", "Service1 onUnbind");
return super.onUnbind(intent);
}
}
开启和关闭:
case R.id.start1Bn:
Intent start1 = new Intent(this, Service1.class);
startService(start1);
break;
case R.id.stop1Bn:
Intent stop1 = new Intent(this, Service1.class);
stopService(stop1);
break;