我对应用程序开发还很陌生,尝试创建一个漂亮的“简单”任务计划程序,但是具有重复任务的功能。就像到处都提到的那样,我使用“共享首选项”在重新启动后将数据保留在原位。只要不触发警报,此方法(至少在模拟器中)可以正常工作。
几乎不可能在模拟器中测试警报,因为我的PC不在凌晨3点运行(如果没有其他可能性,可能仍然必须这样做),所以我复制了输出.apk在我的S8(Android 9.0)上。我什至无法在那里启动我的应用两次,因为在设备上似乎无法使用“共享首选项”(至少我猜是这样)。我无法将设备连接到Android Studio进行调试,因为USB-C端口似乎已损坏。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> month = new ArrayList<>();
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String date = prefs.getString("CURRENTDATE",null);
if(date != null){
for(int i=0;i<Jobs.month_length;i++){
month.add(prefs.getString(Integer.toString(i),"#"));
}
Storage.jobs = new Jobs(month);
}
else{
Storage.jobs = new Jobs();
//Registration
timingCal = Calendar.getInstance();
timingCal.set(Calendar.HOUR, 3);
timingCal.set(Calendar.MINUTE, 0);
timingCal.set(Calendar.SECOND, 0);
long intendedTime = timingCal.getTimeInMillis();
registerMyAlarmBroadcast();
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, intendedTime,AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
private void registerMyAlarmBroadcast()
{
Log.i("ALARM", "Going to register");
myBroadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
MainActivity main = new MainActivity();
Log.d("ALARM","triggered");
ArrayList<String> month= new ArrayList<>();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(main);
SharedPreferences.Editor editPrefs = preferences.edit();
for(int i=1;i<Jobs.month_length;i++){
editPrefs.putString(Integer.toString(i-1),prefs.getString(Integer.toString(i),"#"));
Log.d("PUTTING",i+" to "+(i-1));
}
editPrefs.putString(Integer.toString(30),"");
editPrefs.apply();
}
};
registerReceiver(myBroadcastReceiver, new IntentFilter("com.alarm.example") );
pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("com.alarm.example"),0 );
alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}
我希望第二天将“ current_day” +1的内容作为当前/第一个,但我得到的唯一结果是无法启动的应用程序(甚至当我尝试时,甚至是同一天)在我的真实设备上)