我的应用有一个活动,一个管理员接收器和一个报警管理器接收器。即使应用程序关闭,我也希望能够执行以下操作:
1-禁用警报并在禁用设备管理员时将布尔首选项设置为false 2-在收到警报后执行一些管理任务。
我尝试将代码放入接收器,但代码仅在应用程序运行时才有效。然后我尝试在onCreate()之前初始化与警报管理器和设备管理员相关的所有代码,但我无法在接收器中引用代码,因为其中一些代码是动态的。
那我怎么能实现这个目标呢?
代码
public class mainActivity extends ActionBarActivity {
static EditText numberOfHours;
static TextView hourText;
static Button setButton;
static Context context;
static DevicePolicyManager dpm;
static ComponentName admin;
static boolean adminCheck;
static Intent intent;
static SharedPreferences preferences;
static SharedPreferences.Editor editor;
static boolean appSet;
static AlarmManager alarmManager;
static PendingIntent alarmIntent;
static Intent mIntent;
static Calendar calendar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hourText = (TextView) findViewById(R.id.hourText);
numberOfHours = (EditText) findViewById(R.id.numberOfHours);
setButton = (Button) findViewById(R.id.setButton);
context = this;
dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
admin = new ComponentName(context, adminReceiver.class);
intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "The app needs to be a device administrator to be able to lock the screen");
preferences = getPreferences(Context.MODE_PRIVATE);
editor = preferences.edit();
editor.putBoolean("appSet", false);
appSet = preferences.getBoolean("appSet", false);
alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mIntent = new Intent(context, alarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 24, mIntent, 0);
calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 24);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
setButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (adminCheck) {
numberOfHours.setEnabled(false);
setButton.setEnabled(false);
setButton.setText("Done");
editor.putBoolean("appSet", true).commit();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),1000 * 60 * 60 * 24, alarmIntent);
}
else {
startActivityForResult(intent, 1);
}
}
});
}
static public class adminReceiver extends DeviceAdminReceiver {
@Override
public void onEnabled(Context context, Intent intent) {
super.onEnabled(context, intent);
}
@Override
public void onDisabled(Context context, Intent intent) {
super.onDisabled(context, intent);
}
@Override
public void onPasswordChanged(Context context, Intent intent) {
super.onPasswordChanged(context, intent);
}
}
static public class alarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm", Toast.LENGTH_SHORT).show();
}
}
}