-1

i want to add checkbox to start my app on device boot

This is what i tried :

Step 1: Set the permission in AndroidManifest.xml

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

Step 2: Add this intent filter in receiver

<receiver android:name=".BootReceiver">
    <intent-filter >
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

Step 3: in BootReceiver.java

package com.example.myapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import static com.example.myapp.MainActivity.Global.*;

public class BootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (preferences.getBoolean( "boot", false )) {
            Intent myIntent = new Intent( context, SplashScreen.class );
            myIntent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
            context.startActivity( myIntent );
        }
    }
}
  1. In MainActivity.java Before onCreat:
public static class Global {
public static SharedPreferences preferences;
}
CheckBox AutoBoot;
  1. In MainActivity.java in onCreat:
preferences = PreferenceManager.getDefaultSharedPreferences( this );
        final SharedPreferences.Editor editor = preferences.edit();

if (preferences.getBoolean( "boot", false )) {
AutoBoot.setChecked( true );
} else {
AutoBoot.setChecked( false );
}

AutoBoot.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    editor.putBoolean( "boot", true );
                    editor.apply();
                } else {
                    editor.putBoolean( "boot", false );
                    editor.apply();
                }
            }
        } );
Le Tux
  • 15
  • 6
  • [MJ Studio's answer below](https://stackoverflow.com/a/57762941) is spot on. There is not going to be a `MainActivity` instance at boot, so `preferences` is going to be null. You really don't want to use `static` members like that, anyway. All you need to access `SharedPreferences` is a `Context`, and one is passed into `onReceive()` in your `BroadcastReceiver`. Also, a more efficient method to toggle your app's boot response would be to enable/disable that Receiver altogether, as appropriate. You can see examples of how to do that in this post: https://stackoverflow.com/q/6529276. – Mike M. Sep 03 '19 at 13:43
  • 1
    Thanks, i did as in your link and all works fine ! – Le Tux Sep 04 '19 at 02:31

1 Answers1

0

is there NPE in preferences? Your initialization code of preferences static variable is in MainActivity instance. So if you use it in BroadcastReceiver, It may cause NpE

MJ Studio
  • 3,947
  • 1
  • 26
  • 37