【发布时间】:2015-11-13 19:08:25
【问题描述】:
我的应用程序中发生了一个非常奇怪的错误。我正在构建一个警报应用程序,我正在使用 SQLite 来存储警报数据并使用广播接收器来管理警报管理器调用。
奇怪的是,onReceive 的代码在某些情况下的行为方式并不相同。当接收器收到广播时,我尝试启动一个 Activity,几乎 90% 的情况一切顺利,我设法启动了 Activity,但在某些情况下,接收器执行指令“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 中发布您的活动声明代码,以便更好地了解问题。
-
刚刚添加了清单。代码在 90% 的情况下都有效,因此意图启动了我的活动,但奇怪的是在某些情况下它并没有启动它。
-
您的代码看起来不错。我可以推荐的唯一更改是使用 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 而不是 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)。此外,当它失败的 10% 的时候,是当你通过按下主页按钮将 Activity 置于后台时。
-
我将尝试通过将标志添加到意图中来设置它,而不只是设置它。尽管很可能它会产生很大的不同,但我仍然会尝试它,希望能解决问题。发生错误的那 10% 不仅在您提到的情况下。即使奇怪的是,在相同的用例中,应用程序在 90% 的情况下表现良好,但有时在这 10% 的情况下,即使用例始终相同,我也会遇到该错误。
-
现在我将尝试 google 的方式来处理 wakefulBroadcasts :developer.android.com/reference/android/support/v4/content/….
标签: android android-intent broadcastreceiver