name=".Service.BackGroupService"/>
三、绑定服务和解除绑定服务
我们通过两个按钮分别演示绑定服务和解除绑定服务,通过bindService()开启服务,通过unbindService()停止服务
publicclassMainActivityextendsAppCompatActivity{
Buttonbt_open,bt_close;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_open=(Button)findViewById(R.id.open);
bt_close=(Button)findViewById(R.id.close);
finalIntentintent=newIntent(this,BackGroupService.class);
bt_open.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv){
bindService(intent,conn,BIND_AUTO_CREATE);
}
});
bt_close.setOnClickListener(newView.OnClickListener(){
@Orride
publicvoidonClick(Viewv){
unbindService(conn);
}
});
}
ServiceConnectionconn=newServiceConnection(){
@Override
publicvoidonServiceConnected(ComponentNamename,IBinderservice){
//拿到后台服务代理对象
BackGroupService.MyBindermyBinder=(BackGroupService.MyBinder)service;
//调用后台服务的方法
myBinder.showToast();
myBinder.showList();
}
@Override
publicvoidonServiceDisconnected(ComponentNamename){
}
};
}
这里和startService的区别在于多了一个ServiceConnection对象,该对象是用户绑定后台服务后,可获取后台服务代理对象的回调,我们可以通过该回调,拿到后台服务的代理对象,并调用后台服务定义的方法,也就实现了后台服务和前台的交互
四、运行代码
运行程序后,我们点击绑定服务,然后一段时间后解除绑定服务。
我们以Log信息来验证Service的生命周期:
onCreate->onBind->onUnBind->onDestroy,其中也可以看到我们调用后台服务的方法showToast和showList
11-2400:
55:
32.77515408-15408/com.handsome.boke2E/Service:
onCreate
11-2400:
55:
32.77515408-15408/com.handsome.boke2E/Service:
onBind
11-2400:
55:
32.79615408-15408/com.handsome.boke2E/Service:
showToast
11-2400:
55:
32.79615408-15408/com.handsome.boke2E/Service:
showList
11-2400:
55:
34.29015408-15408/com.handsome.boke2E/Service:
onUnbind
11-2400:
55:
34.29015408-15408/com.handsome.boke2E/Service:
onDestroy
混合性交互的后台服务
或许你会迷惑,startService和bindService之间有什么关系?
其实简单的说两者之间是没有关联的,类似于你亲妈生了个双胞胎一样,只有纯粹的血缘关系。
那么问题来了,这两个启动方式是否可以同时使用呢,答案是可以的
将上面两种启动方式结合起来就是混合性交互的后台服务了,即可以单独运行后台服务,也可以运行后台服务中提供的方法,其完整的生命周期是:
onCreate->onStartCommand->onBind->onUnBind->onDestroy
前台服务
由于后台服务优先级相对比较低,当系统出现内存不足的情况下,它就有可能会被回收掉,所以前台服务就是来弥补这个缺点的,它可以一直保持运行状态而不被系统回收。
例如:
墨迹天气在状态栏中的天气预报
一、创建服务类
前台服务创建很简单,其实就在Service的基础上创建一个Notification,然后使用Service的startForeground()方法即可启动为前台服务
publicclassForegroundServiceextendsService{
@Nullable
@Override
publicIBinderonBind(Intentintent){
returnnull;
}
@Override
publicvoidonCreate(){
super.onCreate();
showNotification();
}
/**
*启动前台通知
*/
privatevoidshowNotification(){
//创建通知详细信息
Notification.BuildermBuilder=newNotification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("2016年11月24日")
.setContentText("今天天气阴天,8到14度");
//创建点击跳转Intent
Intentintent=newIntent(this,MainActivity.class);
//创建任务栈Blder
TaskStackBuilderstackBuilder=TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(ent);
PendingIntentpendingIntent=stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
//设置跳转Intent到通知中
mBuilder.setContentIntent(pendingIntent);
//获取通知服务
NotificationManagernm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
//构建通知
Notificationnotification=mBuilder.build();
//显示通知
nm.notify(0,notification);
//启动为前台服务
startForeground(0,notification);
}
}
二、配置服务
name=".Service.ForegroundService"/>
三、启动前台服务
startService(newIntent(this,ForegroundService.class));
四、运行代码
我们可以看到状态栏确实增加了我们这条通知
当我们将该程序退出并杀掉的时候,通过设置->应用->选择正在运行中的应用,我们可以发现,我们的程序退出杀掉了,而服务还在进行着
IntentService
IntentService是专门用来解决Service中不能执行耗时操作这一问题的,创建一个IntentService也很简单,只要继承IntentService并覆写onHandlerIntent函数,在该函数中就可以执行耗时操作了
publicclassTheIntentServiceextendsIntentService{
publicTheIntentService(Stringname){
super(name);
}
@Override
protectedvoidonHandleIntent(Intentintent){
//在这里执行耗时操作
}
}
AIDL跨进程服务
关于AIDL跨进程服务的使用和原理分析,可以见我另一篇博客:
Android基础——初学者必知的AIDL在应用层上的Binder机制
AccessibilityService无障碍服务
关于AccessibilityService无障碍服务的使用和实例,可以见我另一篇博客:
Android进阶——学习AccessibilityService实现微信抢红包插件
系统服务
系统服务提供了很多便捷服务,可以查询Wifi、网络状态、查询电量、查询音量、查询包名、查询Application信息等等等相关多的服务,具体大家可以自信查询文档,这里举例几个常见的服务
1.判断Wifi是否开启
WifiManagerwm=(WifiManager)getSystemService(WIFI_SERVICE);
booleanenabled=wm.isWifiEnabled();
需要权限
name="android.permission.ACCESS_WIFI_STATE"/>
name="android.permission.CHANGE_WIFI_STATE"/>
2.获取系统最大音量
AudioManageram=(AudioManager)getSystemService(AUDIO_SERVICE);
intmax=am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
3.获取当前音量
AudioManageram=(AudioManager)getSystemService(AUDIO_SERVICE);
intcurrent=am.getStreamMaxVolume(AudioManager.STREAM_RING);
4.判断网络是否有连接
ConnectivityManagercm=(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfoinfo=cm.getActiveNetworkInfo();
booleanisAvailable=info.isAvailable();
需要权限
name="android.permission.ACCESS_NETWORK_STATE"/>