我想在我的应用程序按主页按钮等进行最小化时开始通知(但不是使用BACK,当用户按下时,它会退出应用程序)。 我创建了onPause函数,但是当我按下按钮时也会启动通知:)也许当按下后面时,android启动onPause也是。
Public void onPause(){
try{
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.city, "Notification Test", System.currentTimeMillis());
Context context = getApplicationContext();
CharSequence contentTitle = "asdf TITLE asdf";
CharSequence contentText = "blah blah";
Intent notificationIntent = new Intent(HomeActivity.this, HomeActivity.class);
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
//auto cancel after select
notification.flags |= Notification.FLAG_AUTO_CANCEL;
PendingIntent contentIntent = PendingIntent.getActivity(HomeActivity.this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1, notification);
}catch(Exception e){}
}
super.onPause();
任何想法?谢谢你的回答
答案 0 :(得分:3)
是的,当你按下后面时你是对的,onPause()
会被调用,之后是onDestroy()
,这会破坏活动。
<强>溶液; 强>
您需要做的是,您可以覆盖onBackPressed()
并添加按下后退按钮的标记,并在onPause()
中检查该标记。
private flag = false; //global variable
@Override
public void onBackPressed() {
flag = true; //set to true when you pressd back button
super.onBackPressed();
}
public void onPause(){
if(!flag) //check if backbutton is not pressed
{
try{
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.city, "Notification Test", System.currentTimeMillis());
Context context = getApplicationContext();
CharSequence contentTitle = "asdf TITLE asdf";
CharSequence contentText = "blah blah";
Intent notificationIntent = new Intent(HomeActivity.this, HomeActivity.class);
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
//auto cancel after select
notification.flags |= Notification.FLAG_AUTO_CANCEL;
PendingIntent contentIntent = PendingIntent.getActivity(HomeActivity.this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1, notification);
flag = false; //reset you flag
}catch(Exception e){}
}
super.onPause();
}