0
votes

i want to start notification when my app goes to minimize with home button etc. (but not with BACK, when user press back, it exits app). I create onPause functions but nottification started also when i push back button :) maybe when back is pressed android start onPause too.

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();

any idea ? thanks for answer

1

1 Answers

3
votes

Yes you are right when you pressed the back buton the onPause() will get called and after is onDestroy() which will destroy the activity.

solution;

What you need to do is that you can override your onBackPressed() and add a flag that you pressed the back button and in your onPause() you'll check that flag.

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();
}