Cannot receive broadcast in ICS

2019-02-22 11:24发布

I writing 1 app for Android 4.0, and it's started via broadcastreceiver. My code is below:

In AndroidManifest.xml:

 <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <receiver android:name="com.Android.Exercise.StartUpReceiver"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <!--<action android:name="StartInstrument" /> 
                <action android:name="PrintControlName" />      -->     
            </intent-filter>
        </receiver>         
        <service android:enabled="true" android:name="StartAUT_Service">
            <intent-filter>
                <action android:name="com.Android.Exercise.StartAUT_Service" />
            </intent-filter>
        </service>  
    </application>

In StartUpReceiver class:

public class StartUpReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {

        Log.i("Broadcast", "onReceive");

        Intent i = null;

        if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
             i = new Intent(context, StartAUT_Service.class);          
             i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        context.startService(i);            
    }       
}

After I rebooted my device, I can not receive broardcast. Please help me, thank so much

3条回答
\"骚年 ilove
2楼-- · 2019-02-22 12:00

Try

 <uses-permission android:name="android.intent.action.BOOT_COMPLETED" />

below Internet's uses permission

查看更多
贪生不怕死
3楼-- · 2019-02-22 12:05

Starting from Android 3.0, application state was introduced. All applications are now installed with a state set to inactive, making all it's BroadcastReceivers inactive.

To make the state as active, the user must launch the application at least once and the OS will automatically activate the app and all its BroadcastReceivers.

In your case, you need to add an activity, be it a license agreement or a help page. This will create an icon for your app for the user to click and activate the app.

Note that the application's state will be set to back inactive if the user force-closes the application.

I faced a similar problem: Android ICS not receiving data sms

I hope that solves your problem or at least put you on the right track.

regards, Ahmad

查看更多
混吃等死
4楼-- · 2019-02-22 12:09

You need to do the following to overcome this security feature.

If your API level is below 12, then set the following to your intent before broadcasting it:

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 32);

Otherwise, add the following flag to include packages which are marked as Stopped too:

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent. FLAG_INCLUDE_STOPPED_PACKAGES);
查看更多
登录 后发表回答