所以我尝试了几种方法,并遵循了多种指南来尝试更新SharedReferences,但它似乎根本无法正常工作,我也不知道为什么。
我试图在代码中注册一个广播接收器,此刻我正在Manifest.xml中尝试它。
OnCreate()归纳为(我认为)相关部分。
MainActivity.java
public static final String alarm = "com.example.aufgaben_planer.alarm";
public static final String sharedPrefs = "com.example.aufgaben_planer.MONTH";
SharedPreferences prefs;
protected void onCreate(Bundle savedInstanceState) {
prefs = getApplication().getSharedPreferences(sharedPrefs,Context.MODE_PRIVATE);
timingCal = Calendar.getInstance();
timingCal.set(Calendar.HOUR, 17); // At the hour you want to fire the alarm
timingCal.set(Calendar.MINUTE, 55); // alarm minute
timingCal.set(Calendar.SECOND, 0); // and alarm second
long intendedTime = timingCal.getTimeInMillis();
alarmManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, MonthManager.class);
alarmIntent.setAction(alarm);
pendingIntent = PendingIntent.getBroadcast( this, 0, alarmIntent,PendingIntent.FLAG_UPDATE_CURRENT );
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, intendedTime,AlarmManager.INTERVAL_DAY, pendingIntent);
TextView tv = findViewById(R.id.temp_tasks);
tv.setText(prefs.getString("REC","NOT CALLED"));
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.aufgaben_planer">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
>
<activity android:name=".Add_job" android:parentActivityName=".MainActivity"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MonthManager" android:process=":remote">
<intent-filter>
<action android:name="com.example.aufgaben_planer.alarm"></action>
</intent-filter>
</receiver>
</application>
</manifest>`
MonthManager.java
public class MonthManager extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
Log.d("BISASAM","triggered");
SharedPreferences preferences = context.getSharedPreferences(MainActivity.sharedPrefs,Context.MODE_PRIVATE);
SharedPreferences.Editor editPrefs = preferences.edit();
editPrefs.putString("REC","Receiver called");
editPrefs.commit();
for(int i=1;i<Jobs.month_length;i++){
editPrefs.putString(Integer.toString((i-1)),preferences.getString(Integer.toString(i),"#"));
Log.d("BISASAM",i+" to "+(i-1));
}
editPrefs.putString(Integer.toString(30),"");
editPrefs.commit();
}
}
正如代码中所添加的,我希望在MainActivity中的TextView中看到一个“ Receiver named”,但我只是得到了“ NOT CALLED”。 似乎警报设置正确,因为在adb shell dumpsys警报中列出了该警报。
编辑:无论出于何种原因,它现在都可以在模拟器中运行,但是它始终在等待调试器附加。
编辑:最后一个问题:重新打开应用程序时,如何确定OnReceive()已完成。因为现在我可以打开它,然后必须将其关闭,然后在重新打开它之后,一切都很好。