我正在尝试使用timepicker在选定的小时内关闭应用程序。我有这个代码,但它还没有工作。我按下按钮并选择了小时,但它没有断电。
public class ContadorproActivity extends ActionBarActivity {
TimePicker timePicker;
Button contadorpro;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contadorpro);
timePicker = (TimePicker) findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);
}
public void onClick(View view) {
Toast.makeText(getBaseContext(), "Hora seleccionada:" + timePicker.getCurrentHour() +
":" + timePicker.getCurrentMinute(), Toast.LENGTH_SHORT).show();
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss ");
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
Intent myIntent = new Intent(ContadorproActivity.this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ContadorproActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
还有java.class:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Run your stuff
Toast.makeText(context, "OnReceive!", Toast.LENGTH_SHORT).show();
android.os.Process.killProcess(android.os.Process.myPid());
}
}
答案 0 :(得分:0)
获得特定时间后,您可以使用AlarmManager服务触发确切的警报(使用setExact()方法),您可以在此处调用关闭。您可以在此处阅读有关AlarmManager的更多信息:AlarmManager - setExact()
请记住,如果您需要在系统重新启动后继续此倒计时,则可能需要额外处理。
答案 1 :(得分:0)
您可以使用AlarmManager
在所需日期安排闹钟:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
实施BroadcastReceiver
以执行您的操作:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Run your stuff
Toast.makeText(context, "OnReceive!", Toast.LENGTH_SHORT).show();
}
}
编辑:
请记住在Manifest中声明您的BroadcastReceiver
:
<receiver android:name="<com.package.app>.MyReceiver " />