在API 3.1之前,我们可以有一个广播接收器,即使它所属的应用程序处于停止状态,它也可能被隐式意图调用。
但这构成了安全威胁。 因此,Google强制要求任何广播接收方都必须收到活动,并且应用程序不应处于停止状态。 这是进一步阅读的链接 。
当启动应用程序时,它处于停止状态,因此它要求用户激活具有广播接收器的应用程序。 如果应用程序被用户强行停止,则广播接收器再次无法接收到该意图。 因此,仅具有广播接收器并在3.1之前的版本上开发的apk将不再适用于更高版本。
但是,可以使用FLAG_INCLUDE_STOPPED_PACKAGES来激活已停止的应用程序中的组件。 为了使用广播接收器,这不需要创建另一个活动。
Intent intent = new Intent("com.custom.intent"); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
this.sendBroadcast(intent);
正如我之前提到的,另一种方式是编写一个活动,该活动可能是也可能不是启动程序活动。
PackageManager pm = getPackageManager();
Intent appStartIntent =
pm.getLaunchIntentForPackage("com.your.broadcast.receiver.package");
if (null != appStartIntent)
{
startActivity(appStartIntent);
}
如果它不是启动器应用程序,那么您需要在广播接收者清单文件的intent-filter中将类别提到为INFO 。
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" <
<activity
android:name=".InvokedActivity"
android:label="@string/app_name"<
<intent-filter<
<action android:name="android.intent.action.MAIN" /<
<category android:name="android.intent.category.INFO" / <
<-- If the activity is a launcher then mention this instead
<category android:name="android.intent.category.LAUNCHER" /
< --<
</intent-filter <
</activity <
<receiver android:name=".TestBroadCastReceiver" <
<intent-filter <
<action android:name="com.custom.intent" <
</action <
</intent-filter <
</receiver <
<application <
这是BroadCastReceiver的代码:
public class TestBroadCastReceiver extends BroadcastReceiver {
private static final String CUSTOM_INTENT = "com.custom.intent";
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(CUSTOM_INTENT)) {
//your code here
}
}
}
InvokedActivity的代码:
public class InvokedActivity extends Activity {
public void onCreate(Bundle b) {
super.onCreate(b);
/*Toast.makeText(this, "starting xyz receiver...blah blah :)", Toast.LENGTH_LONG) .show();*/
finish();
}
}
参考: 广播接收器–自我们的JCG合作伙伴 Ashimita Adusumilli在API 3.1以来,流量的变化,来自My My world of Android blog。
翻译自: https://www.javacodegeeks.com/2012/05/android-broadcast-receiver-change-in.html