Search code examples
androidstartup

Startup receiver doesn't work on Android 10


My startup receiver is not working on Android 10. Why?

50 points reward for a solution.

AndroidManifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>


    <receiver android:name="ServiceStarter"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <acenter code heretion android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
            <action android:name="android.intent.action.REBOOT" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
            <action android:name="android.intent.action.ACTION_SHUTDOWN" />
        </intent-filter>
    </receiver>

ServiceStarter.Java

public class ServiceStarter extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences mSharedPref = context.getSharedPreferences("general", MODE_PRIVATE);
    mSharedPref.edit().putInt("Boot", 1).apply();
}
}

MainActivity.java

int boot = mSharedPref.getInt("Boot", 0);
Toast.makeText(this, "Boot: " + String.valueOf(boot), Toast.LENGTH_LONG).show();

When I open my app, "Boot" always 0. onReceive() doesn't get called.


Solution

  • Finally I found the solution. Since Android 24 you need to add directBootAware attribute to the receiver to receive the BOOT_COMPLETED intent, in case the phone is locked by a PIN, Pattern etc.

    android:directBootAware="true"
    

    And onReceive would be

    @Override
    public void onReceive(Context context, Intent intent) {
        //Toast.makeText(context, "onReceive Boot", Toast.LENGTH_LONG).show();
    
        SharedPreferences mSharedPref = context.getSharedPreferences("general", MODE_PRIVATE);
    
    
        if(intent != null && intent.getAction() != null){
            if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) || 
              Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(intent.getAction())) {
            }
        }
    }