Service显示启动和隐式启动
16lz
2021-01-26
1,显示启动
- 直接上代码一目了然,不解释了。
- 需要设置一个Action,我们可以把Action的名字设置成Service的全路径名字,在这种情况下android:exported默认为true。
- 如果在同一个应用中,两者都可以用。在不同应用时,只能用隐式启动。
- Android 5.0之后google出于安全的角度禁止了隐式声明Intent来启动Service。如果使用隐式启动Service,会出没有指明Intent的错误,如下:
- 设置Action和packageName
final Intent serviceIntent=new Intent(); serviceIntent.setAction("com.android.ForegroundService");serviceIntent.setPackage(getPackageName());//设置应用的包名startService(serviceIntent);
- 将隐式启动转换为显示启动
public static Intent getExplicitIntent(Context context, Intent implicitIntent) { // Retrieve all services that can match the given intent PackageManager pm = context.getPackageManager(); List 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; }
- 调用方式如下:
Intent mIntent=new Intent();//辅助IntentmIntent.setAction("com.android.ForegroundService");final Intent serviceIntent=new Intent(getExplicitIntent(this,mIntent));startService(serviceIntent);
关于更多Service内容: https://blog.csdn.net/cricket_7/category_9580061.html
更多相关文章
- 说说 Android(安卓)中的通知(Notification)
- android图形图像函数汇集
- Android(安卓)自定义dialog(封装好的)
- Android(安卓)Service的两种启动方式,你知道吗?
- 【读书笔记-《Android游戏编程之从零开始》】4.Android(安卓)游
- Android(安卓)的第三方报表组件,AChartEngine 案列demo
- Android游戏引擎《Rokon》:主要类和方法的介绍文档
- cocos2d-x在android真机上设置帧率无效的问题
- 【Android(安卓)Developers Training】 27. 序言:和其它应用交互