lundi 2 septembre 2019

Android How to use checkbox for enable/disable start app on device boot?

i want 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 Befor 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();
                }
            }
        } );




Aucun commentaire:

Enregistrer un commentaire