Android Broadcast Receiver –自API 3.1以来流量的变化

在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值