当用户检查CheckBox
并将时间设置为TimePickerDialog
并且时间到了时,服务将通过BroadcastReceiver
开始并且音乐每6秒播放一次。由于这是Service
,即使我重新启动应用程序,音乐仍然每6秒播放一次。 同样我创建了另一个服务来保存CheckBox的状态,因为如果时间还没有到来,用户关闭然后打开应用程序,CheckBox仍然必须签入。我创建了一个全局变量来管理复选框的状态:服务问题
main.java:
Intent intentA = new Intent(main.this, AlarmReceiverA.class);
PendingIntent pendingIntentA = PendingIntent.getBroadcast(main.this, 0,
intentA, PendingIntent.FLAG_ONE_SHOT);
alarmManagerA = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar now = Calendar.getInstance();
alarmManager.set(AlarmManager.RTC_WAKEUP, now.getTimeInMillis(), pendingIntentA);
Toast.makeText(main.this, "Present time: " +
String.valueOf(now.getTime()), Toast.LENGTH_SHORT).show();
这是很容易AlarmReceiver
启动服务:
public final class AlarmReceiverA extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "AlarmA worked.", Toast.LENGTH_LONG).show();
context.startService(new Intent(context, MyServiceA.class));
}
}
这是MyServiceA.class:
@Override
public void onCreate() {
Toast.makeText(this, "My ServiceA Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
GlobalVars.setTimeWatch(1);
}
@Override
public void onDestroy() {
Toast.makeText(this, "My ServiceA Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My ServiceA Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
GlobalVars.setTimeWatch(1);
}
我得到“我的服务启动”吐司消息,所以这一直工作到目前为止。问题是即使我将变量设置为1 GlobalVars.setTimeWatch(1)
当我重新启动应用程序时,我没有收回它。
在main.java我检查这个变量的值:
public void onResume() {
super.onResume();
Toast.makeText(main.this, String.valueOf(GlobalVars.getTimeWatch()),
Toast.LENGTH_SHORT).show();
}
但是,所有我得到的是0问题一定与服务,因为当我打开了一个新的画面(例如,通过点击在一个按钮上),然后返回,我得到值为“1”的Toast消息。
- 这是保存CheckBox状态的方法吗?
- 代码有什么问题?
我也是这个尝试:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean("MyBoolean", cbstate);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myb = savedInstanceState.getBoolean("MyBoolean");
}
cbstate是布尔变量。在OnCreate方法,我检查cbstate的价值:
if (myb == true)
{
cb1.setChecked(true);
Toast.makeText(main.this, "checked", Toast.LENGTH_SHORT).show();
}
else
{
cb1.setChecked(false);
Toast.makeText(main.this, "Not checked", Toast.LENGTH_SHORT).show();
}
重新启动应用程序我总是得到“未检查”之后。