I have a dialog to show settings which toggle App autostart on boot.
User click Enable
or Disable
, then click OK
to save.
The code:
public void showShareDialog(final int itId, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
String positiveText = getString(android.R.string.ok);
String negativeText = getString(android.R.string.cancel);
String[] items;
int default_i = 0;
final SharedPreferences sharedPref = getSharedPreferences("quickSettings", MODE_PRIVATE);
if (itId == AUTOSTART_LI) {
items = getResources().getStringArray(R.array.toggle);
final boolean autostart = sharedPref.getBoolean("autostart", false);
Log.d("hole", "#autostart get:" + autostart);
if (!autostart) default_i = 1;
} else return;
builder.setSingleChoiceItems(items, default_i, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("hole", "single clicked" + which);
}
})
.setPositiveButton(positiveText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("hole", "positive clicked:" + which);
if (itId == AUTOSTART_LI) {
int flag;
boolean autostart;
if (which == 0) {
flag = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
autostart = true;
} else {
flag = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
autostart = false;
}
ComponentName component = new ComponentName("com.blogspot.diannaoxiaobai.skyshot"
, "com.blogspot.diannaoxiaobai.skyshot.MyReceiver");
getPackageManager().setComponentEnabledSetting(component, flag, PackageManager.DONT_KILL_APP);
//save only if above no crash
SharedPreferences.Editor editor = sharedPref.edit();
Log.d("hole", "#autostart saved:" + autostart);
editor.putBoolean("autostart", autostart);
editor.commit();
}
}
})
.setNegativeButton(negativeText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("hole", "negative clicked:" + which);
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
But only setSingleChoiceItems
able get the index, while setPositiveButton
's which
variable always print -1
, logcat e.g.:
05-12 03:14:41.983 5014 5014 D hole : single clicked0
05-12 03:14:43.066 5014 5014 D hole : single clicked1
05-12 03:14:43.615 5014 5014 D hole : positive clicked:-1