BroadcastReceiver issues in Android 3.1+

2019-02-19 19:10发布

问题:

I'm trying to update location data to a web database using BroadcastReceiver and Service.

However I am having difficulties making it to work with Android 3.2 on a Galaxy Tab 7.0 Plus.

The same application is working very well on a Android 2.3.6 Galaxy Note, but it doesn't run on the tablet. In fact, I add the RECEIVE_BOOT intent action to my receiver, but it never gets instantiated, that is, onReceive() never gets called after boot completes. I wonder if there are any updates to the system that cause this action.

Here is my xml and receiver classes:

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tests.bootreceiver"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="15" />

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <receiver
        android:name=".BootUpReceiver"
        android:enabled="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

    <service android:name=".MyService" >
    </service>
</application>

BootUpReceiver.java

public class BootUpReceiver extends BroadcastReceiver {

private static int INTERVAL = 1000*15;

@Override
public void onReceive(Context context, Intent intent) {     
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), INTERVAL, pi);
}

}

Is there a reason for the same piece of code work in one system and don't work on another?

Thank you!

回答1:

since android 3, all components in an app are prevented from running (receiving broadcasts) until the app is explicitly started by the user.

to test if this is your problem, add a dummy activity to your app and start it. now your app should be able to receive intents from then on (even after a reboot).

here's the AOSP issue describing the problem,

http://code.google.com/p/android/issues/detail?id=18225

note that it's closed as "works as intended". this is technically a security fix. apps could exploit certain well-known broadcast intents like TIMER_TICK to start themselves without the user ever running the app or knowing that the app was running.



回答2:

Check this out: Boot Complete problems