0

trying to create a app that will autostart on boot, but with an option to turn this function off. Very new to programming.

this is in the manifest

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

this is the listener class

public class MyBootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean auto = prefs.getBoolean("as", true);

    if(auto == true) {
        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

this is the settings class

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    autostart= (Switch) findViewById(R.id.switch1);
    autostart.setOnClickListener(this);

    settings = getSharedPreferences("as", MODE_PRIVATE);
    editor = settings.edit();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean auto = prefs.getBoolean("as", false);

    if(auto == true){
        autostart.setChecked(true);
    }else{
        autostart.setChecked(false);
    }

    @Override
public void onClick(View view) {
    Switch auto = (Switch) view;
    if (auto.isChecked())
    {
        editor.putBoolean("as",true);
        Toast.makeText(SettingsActivity.this, "autostart on", Toast.LENGTH_SHORT).show();
        editor.commit();

    }else{
        editor.putBoolean("as",false);
        Toast.makeText(SettingsActivity.this, "autostart off", Toast.LENGTH_SHORT).show();
        editor.commit();

    }
}

As you can see I'm trying to use a button to toggle the autostart function, i get no errors, but as is the program always starts on boot. what am I doing wrong?

Paroli80
  • 31
  • 2

1 Answers1

0

You are setting the value to different preferences than you try to read it from. You are using getSharedPreferences("as") to store it and getDefaultSharedPreferences() to read it.

Also, prefer using package manager to enable or disable the broadcast receiver itself.

Community
  • 1
  • 1
StenSoft
  • 9,369
  • 25
  • 30