我想开始通知,当我的应用程序去最小化与home按钮等(但不与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();
你知道吗?谢谢你的回答
是的,你是对的,当你按下后退按钮时,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();
}