我有一個非常奇怪的錯誤發生在我的應用程序。我正在構建一個鬧鐘應用程序,我正在使用SQLite存儲鬧鐘數據和廣播接收器來管理鬧鐘管理器調用。WakefulBroadcastReceiver意圖不只在某些情況下啓動(奇怪)
在某些情況下,onReceive的代碼奇怪地不以相同的方式表現。我嘗試在接收器收到廣播時開始一個活動,將近90%的情況一切順利,我設法啓動活動,但在某些情況下,奇怪的是接收器執行指令「startActivity(i)」,但沒有任何反應。
這是真的很難重現的BUG,並在我的調試過程中,我已經學會了我所提到的,但對於大多數情況下,我更難以理解如何調用startActivity(),在某些情況下不起作用。我已經通過Stack社區進行了搜索,但是沒有人會遇到這種問題,每個人都在開始活動時遇到問題,因爲他們沒有設置標誌或者因爲他們沒有在清單中註冊接收者。下面我發佈代碼。
public class AlarmReceiver extends WakefulBroadcastReceiver {
// The app's AlarmManager, which provides access to the system alarm services.
private AlarmManager alarmMgr;
// The pending intent that is triggered when the alarm fires.
private PendingIntent alarmIntent;
@Override
public void onReceive(Context context, Intent intent) {
Utils.logToFile("Received Alarm ,I am in onReceive(), ALARM ID: "+intent.getExtras().getInt(Constants.ALARM_ID));
Intent intent = new Intent(context, StopAlarm.class);
Bundle b = new Bundle();
b.putInt(Constants.ALARM_ID, intent.getExtras().getInt(Constants.ALARM_ID));
if(intent.getExtras().containsKey(Constants.SNOOZE_ALARM)){
b.putString(Constants.SNOOZE_ALARM, intent.getExtras().getString(Constants.SNOOZE_ALARM));
}
i.putExtras(b);
//this flag is needed to start an Activity from a BroadcastReceiver
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
//this method reads from the DB and sets the next alarm
//I tried commenting this method so that no DB action is
//performed and still the bug happened
setAlarm(context.getApplicationContext());
//this method just logs data into a file that I have created to keep track of events
//since not always the device is connected with LogCat
Utils.logToFile("Received Alarm, Intent(context, StopAlarm.class);");
}
是否需要設置任何其他標誌,以及在某些情況下startActivity(intent)的行爲有可能不正確?
編輯
<activity
android:label="@string/app_name"
android:name="package.activity.StopAlarm"
android:windowSoftInputMode="stateAlwaysHidden"
android:screenOrientation="sensorPortrait">
</activity>
<receiver android:name="package.receivers.AlarmReceiver" />
請從您的Manifest發佈您的活動聲明代碼,以更好地瞭解問題。 – 2014-12-05 15:12:51
剛剛添加了清單。該代碼在90%的案例中起作用,所以意圖開始我的活動,但奇怪的是在某些情況下它不會啓動它。 – Rubin 2014-12-05 16:25:11
你的代碼看起來很好。我可以推薦的唯一更改是使用intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),而不是intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)。此外,當它失敗的時間達到10%時,是否通過按主頁按鈕將活動置於後臺。 – 2014-12-05 19:13:28