我已经搜索了这个问题的解决方案,但一直找不到。
我遇到的问题是警报响起,但MainActivity
已关闭且未重新显示。
如何在以下代码中重新显示MainActivity
:
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
//this will update the UI with message
AlarmActivity inst = AlarmActivity.instance();
inst.setAlarmText("Alarm! Wake up! Wake up!");
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
代码是我作为示例下载的代码,可以使用JavaPapers
答案 0 :(得分:0)
答案 1 :(得分:0)
我确实试图使用广播,但它不起作用,所以我做的很可能是不完整的。
虽然以下代码确实有效(最后添加了3行),但在我看来它是错误的,因为我认为它创建了一个MainActivity的新实例。 MainActivity是原始版本中的AlarmActivity。
AlarmService.java中“工作”的代码如下:
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder alarmNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Alarm").setSmallIcon(R.mipmap.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alarmNotificationBuilder.setContentIntent(mPendingIntent);
alarmNotificationManager.notify(1, alarmNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
Intent mIntentMain = new Intent(this, MainActivity.class);
mIntentMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
this.startActivity(mIntentMain);
}
我添加的相关代码是最后3行。我把它放到AlarmService.java中,因为它扩展了IntentService。在第一个帖子(上面)中发布的原始代码来自AlarmReceiver.java,它扩展了WakefulBroadcastReceiver。我认为我应该做的是使现有的MainActivity显示而不是创建另一个。
编辑:2016年9月29日
由于可能已经显示了主要活动,我最终要做的就是如下:
if (fn_IsMainActivityDisplayed(this) == false) { System.out.println("Main activity is not running. Now recreating"); try { PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_ONE_SHOT); mPendingIntent.send(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); } catch (Exception jExc) {
System.out.println("AlarmService: PendingIntent failed: Error = " + jExc.getMessage());
}
}
确定是否显示主要活动的代码在SO上找到。我不确定这是否100%正确,但似乎工作正常。