Android:由于外部操作而显示通知

时间:2012-11-02 12:28:11

标签: java android android-activity notifications lifecycle

当我的MainActivity是onPause()时我必须显示通知,所以我在MainActivity上写下面的代码,所以通过onPAuse()我的意思是Activity因外部动作(未接来电,屏幕锁定)而中断但是我有一个问题,即使我移动到另一个活动显示通知,也可以帮助我。

private void createNotify(){
    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);        
    Notification notification = new Notification(R.drawable.ic_launcher, "Radio Jawhara en cours...", System.currentTimeMillis());  
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, FragmentsSliderActivity.class), 0);
    String titreNotification = "Radio Jawhara en cours...";
    String texteNotification = "Retour à la radio...";   
    notification.setLatestEventInfo(this, titreNotification, texteNotification, pendingIntent);
    notification.vibrate = new long[] {0,200,100,200,100,200};
    notificationManager.notify(ID_NOTIFICATION, notification);
}

private void cancelNotify(){
    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(ID_NOTIFICATION);
}

@Override
protected void onResume() {
    super.onResume();
    cancelNotify();
}
@Override
protected void onPause() {
    super.onPause();
    createNotify();
}

2 个答案:

答案 0 :(得分:0)

在代码中创建FLAG并修改onPause(),如下所示:

@Override
protected void onPause() {
    super.onPause();
    if(FLAG) {
        createNotify();
    }
}

将此标记的默认值设置为false并将其设置为true 仅当想要离开此Activity时。 (例如当您从activity)开始另一个startActivity()时;

答案 1 :(得分:0)

我认为这里的问题是你在几个活动中管理这个问题,你应该在更高层次上管理它。

如果我要解决这个问题,我会创建一个单例类来管理通知。我的所有活动(在他们的onPause()方法中)告诉单例他们已经暂停,并且我的所有活动也会告诉单身人士(在他们的onResume()方法中)他们已经恢复了。

我的单身人士的暂停方法不会立即创建通知;相反,它会设置一个计时器一段合理的时间来进入我的下一个活动(可能是1秒)。我的单身人士的简历方法只会取消该计时器。如果计时器到期(由于某些外部目的暂停后会发生一秒钟),它将创建通知。

为了使这更容易,我可能会使用具有静态详细信息而不是使用单例的类来扩展Activity,而我的其他活动将从此扩展而不是扩展Activity。这将使创建和维护适当协调的活动变得更加容易。