0

I have a BroadCastReceiver that is listen for incoming short messages. In SmsReceiver I want to start an Activity to process the sms. In many situation the Activity is running while getting message and I don't want to start it again.

In fact I want to see that if that Activity is already running (visible or not killed yet) just take it to front and otherwise start it with new task.

Any idea?

Ali Behzadian Nejad
  • 8,804
  • 8
  • 56
  • 106
  • to bring activity to foreground use flag like intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); – Zaz Gmy May 07 '12 at 13:01
  • possible duplicate of [Android: how do I check if activity is running?](http://stackoverflow.com/questions/5446565/android-how-do-i-check-if-activity-is-running) – Ron May 07 '12 at 13:09
  • When I use this flag, I got "android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?" – Ali Behzadian Nejad May 07 '12 at 13:51

1 Answers1

0

I mixed some ideas from here and other places and finally solved the problem. I write the solution here for other people that may have similar situations:

In amy Activity:

static boolean isRunning = false;

@Override
public void onStart() {
    super.onStart();
    isRunning = true;
}

public void onStop() {
    isRunning = false;
    super.onStop();
}

public static boolean isRuuning() {
    return isRunning;
}

@Override
public void onCreate(Bundle savedInstanceState) {       
    smsReceiver = new SmsReceiver();
    smsReceiver.setActivity(this);
    // ...
}

Inside my SmsReceiver:

static MyActivity myActivity;

public void setActivity(MyActivity MyActivity) {
    SmsReceiver.myActivity = myActivity;
}   

if( MyActivity.isRuuning() ) {
    SmsReceiver.myActivity.receiveNewMessage(smsBody);
} else {
    // Create an intent and start it
}

This works fine for me.

Ali Behzadian Nejad
  • 8,804
  • 8
  • 56
  • 106