Java 方向变更和通知

Java 方向变更和通知,java,android,Java,Android,我想实现以下场景: 当用户按下Home键时,状态栏中会显示一条通知,应用程序通常处于隐藏状态。当用户点击时,通知应用程序通常会恢复 以下是我的代码: private int NOTIFICATION = R.string.local_service_started; private NotificationManager mNM; private void showNotification() { CharSequence text = getText(R.string.local_s

我想实现以下场景:

当用户按下Home键时,状态栏中会显示一条通知,应用程序通常处于隐藏状态。当用户点击时,通知应用程序通常会恢复

以下是我的代码:

private int NOTIFICATION = R.string.local_service_started;
private NotificationManager mNM;

private void showNotification() {
    CharSequence text = getText(R.string.local_service_started);
    Notification notification = new Notification(R.drawable.icon, text, System.currentTimeMillis());
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, JingleCartoucheActivity.class), 0);
    notification.setLatestEventInfo(this, getText(R.string.local_service_label), text, contentIntent);
    mNM.notify(NOTIFICATION, notification);
}

@Override
public void onPause() {
    super.onPause();
    if (!isFinishing()) {
        showNotification();
    }
}

@Override
public void onResume() {
    super.onResume();
    mNM.cancel(NOTIFICATION);
}
除一件事外,所有这些都很有效:


当应用程序运行且用户旋转手机时,会创建并立即销毁通知。是否有办法在onPause()中检测手机方向的更改,而不显示此通知

您可以使用
getResources().getConfiguration().orientation
获取当前方向。在
onCreate
中,存储方向值,然后可以稍后进行比较。请确保将值存储到静态变量中,因为当您旋转手机时,活动会被破坏,其值也会被破坏。

当用户旋转屏幕时,活动会被破坏并重新创建,如果要在方向更改后显示通知,请在onDestroy方法中设置一个静态标志,并在onCreate方法中选中它以显示通知,如

public void onDestroy() {
Flag = 1;
}

public static int Flag = 0;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(Flag == 1) {
    showNotification();
    }
    else {
    .......//
    }
}