目录
文章目录
一 : 常用API
Service 服务对象
onCreate() 创建时调用(只会创建一次)
onDestroy() 销毁时调用(只会销毁一次)
onStart() 开启时调用(接受到开启的指令时调用)(可以多次调用)[过时]
onStartCommand() 开启时调用(接受到开启的指令时调用)(可以多次调用)
onBind() 绑定时调用,返回服务中的代理人
onUnbind() 解绑时调用
stopSelf() 自己关闭服务(停掉自己)
stopForeground(true); 关闭前台服务
startForeground() 开启前台服务
--------------------------------------------------
context.startService() 开启服务
context.stopService() 停止服务
context.bindService() 绑定服务(可以间接的调用到服务里面的方法,可以与服务进行通讯)
context.unbindService() 取消绑定
context.getSystemService() 获得系统服务的对象
二 : service 在另外的进程中
在清单文件中,加上这个两个属性
- android:enabled=“true”
- android:process=":remote"
例子:
<service android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote" >
</service>
三 : 让一个Service成为前置进程
- 在onStartCommand()里面调用startForeground(int id, Notification notification)方法
例子:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new NotificationCompat.Builder(this, "NotificationServiceChannel")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("开启服务")
.setOngoing(true)
.setAutoCancel(false)
.build();
startForeground(1, notification);
return super.onStartCommand(intent, flags, startId);
}
四 : 进程的优先级
- Foreground process
前台进程: 用户正在操作的应用程序所在的进程就是前台进程
- Visible process
可视进程: 用户已经不能操作这个应用程序了,但是界面用户仍然可以看到
- Service process
服务进程: 应用程序有一个服务代码正在运行
- Background process
后台进程: 应用程序有界面,但是界面被用户最小化(home)
- Empty process
空进程: 应用程序没有任何运行的Activity,service.
前台进程>可视进程>服务进程>后台进程>空进程
总结出服务的优点有
(1)服务在进程中的优先级别在中位(一般不容易被回收)
(2)服务的进程就算被回收当内存充足的时候又会重启启动
五 : 绑定远程服务调用服务的流程
和本地服务代码差不多,有几个小细节需要注意
1. 远程服务定义的接口文件不能是.java文件,需要改成.aidl文件,里面的修饰符都不需要
2. 原来的代理对象继承对象需要改变
//本地的写法 //远程的写法
private class MyBinder extends Binder implements IService --> private class MyBinder extends IService.Stub
3. 把远程服务的.aidl文件拷贝到本地工程,包名需要和远程服务的包名一致
4. 获取代理对象的方法需要改变
//本地的写法 //远程的写法
IService iService = (IService) service; --> IService iService = IService.Stub.asInterface(service);
5. 通过代理对象调用远程服务方法
六 : 无障碍辅助服务
https://blog.csdn.net/a343649190/article/details/54972291
七 : 系统服务对象
- 系统服务对象由 context.getSystemService() 获取
系统服务对象 | name | 说明 |
---|---|---|
NotificationManager | NOTIFICATION_SERVICE | 通知管理的服务 |
TelephonyManager | TELEPHONY_SERVICE | 电话管理器的服务 |
WindowManager | WINDOW_SERVICE | 界面管理的服务 |
SensorManager | SENSOR_SERVICE | 传感器 |
LocationManager | LOCATION_SERVICE | 位置管理器 |
DevicePolicyManager | DEVICE_POLICY_SERVICE | 设备策略管理器<超级管理器> |
ActivityManager | ACTIVITY_SERVICE | 进程管理器 |
LayoutInflater | ||
PowerManager | ||
AlarmManager | ||
KeyguardManager | ||
SearchManager | ||
Vibrator | ||
ConnectivityManager | ||
WifiManager | ||
AudioManager | ||
MediaRouter | ||
SubscriptionManager | ||
InputMethodManager | ||
UiModeManager | ||
DownloadManager | ||
BatteryManager | ||
JobScheduler | ||
NetworkStatsManager |