Android部分-4:Service

1.什么是Service?

Service 是一种可在后台执行长时间运行操作而不提供界面的应用组件。服务可由其他应用组件启动,而且即使用户切换到其他应用,服务仍将在后台继续运行。此外,组件可通过绑定到服务与之进行交互,甚至是执行进程间通信(IPC)。例如,服务可在后台处理网络事务、播放音乐,执行文件I/O或与内容提供程序进行交互。

2.说说Service的生命周期

startService():由 startService 方法启动的服务,在服务内任务执行完成,需要通过 stopService 或者 stopSelf 方法停止这个服务。

首次创建 onCreate() 、onStartComand() 、onDestory()

bindService():与Activity的生命周期所绑定。

onCreate()、onBind()、onUnBind()、onDestory()

3.Service和Thread的区别?

如果可以Activity onPause之前处理耗时操作,无需创建线程。

Service 无法直接处理耗时操作,需要开启子线程来处理。(例外,如IntentService)

Thread 的处理场景是用户与应用直接交互的场景,直接开启线程来执行异步任务。

4.Android 5.0以上的隐式启动问题及其解决方案。

1
2
3
4
5
6
7
8
9
10
11
12
private void validateServiceIntent(Intent service) {  
if (service.getComponent() == null && service.getPackage() == null) {
if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
IllegalArgumentException ex = new IllegalArgumentException(
"Service Intent must be explicit: " + service);
throw ex;
} else {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
}
}
}

Android 5.0 中源码判断Service是否显示启动。若要绕过这些判断,可以设置intent的component或者package属性,例如:

1
2
3
4
Intent intent = new Intent();  
ComponentName componentName = new ComponentName(pkgName,serviceName);
intent.setComponent(componentName);
context.startService(intent);
1
2
3
4
Intent mIntent = new Intent();  
mIntent.setAction("XXX.XXX.XXX");//你定义的service的action
mIntent.setPackage(getPackageName());//这里你需要设置你应用的包名
context.startService(mIntent);

5.给我说说Service保活方案。

onStartComand 返回值设置START_STICKTY、START_NOT_STICKTY、START_REDELIVER_INTENT

Service的onDestory方法中设置广播唤醒

Service的优先级设置和前台Service

6.IntentService是什么 & 原理 & 使用场景。

IntentService 内部使用HandlerThread处理异步任务,handlerIntent所在线程为子线程。处理耗时操作

7.创建一个独立进程的Service应该怎样做?

android:process = ""

8.Service和Activity之间如何通信?

文件存储、Messager、AIDL、Socket、ContentProvider

9.说说你了解的系统Service。

ActivityManagerService、WindowManagerService、PowerManagerService…

10.谈谈你对ActivityManagerService的理解。

系统是通过ActivityManagerService 管理Activity相关组件的启动执行。

11.在Activtiy中创建一个Thread和在一个Service中创建一个Thread的区别?

Activity 和 Service 中创建的Thread一般来说必须在组件的生命周期中执行,Service的生命周期相对比较长。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×