3

I have two classes which are MainActivity and MyBroadcastReceiver. BroadcastReceiver detects whether phone screen is on or off. My desire is to launch my application whenever screen lock is released. I mean that I want to bring my application to the front when phone lock releases.

Here is my activity class:

 public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        registerReceiver();
    }

    private void registerReceiver(){
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new MyPhoneReceiver();
        registerReceiver(mReceiver, filter);
    }
}

And here is my broadcast receiver:

public class MyPhoneReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        if(pm.isScreenOn()){
            //Bring application front

        }
    }
}

What am I supposed to do in order to perform this operation in my broadcast receiver?

Cœur
  • 37,241
  • 25
  • 195
  • 267
gokhanakkurt
  • 4,935
  • 4
  • 28
  • 39

3 Answers3

2

Try to use FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_SINGLE_TOP

Basbous
  • 3,927
  • 4
  • 34
  • 62
2

Do the following in your onReceive method of the BroadcastReceiver

@Override
public void onReceive(Context context, Intent intent) {
    Intent newIntent = new Intent();
    newIntent.setClassName("com.your.package", "com.your.package.MainActivity");
    newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    context.startActivity(newIntent);
}

You need the flag "FLAG_ACTIVITY_NEW_TASK" for your intent otherwise there will be a fatal exception being thrown.

The flag "FLAG_ACTIVITY_SINGLE_TOP" is to bring your MainActivity to the front and you can proceed to do whatever you want from there by overriding the onNewIntent method in MainActivity.

@Override
protected void onNewIntent(Intent intent) {
    // continue with your work here
}
jcwx
  • 156
  • 1
  • 2
  • Hi I'm new android and xamarin, I have same issue in my app, I want to open app while receive call. I dont know exactly what I need to give in "com.your.package", "com.your.package.MainActivity" can you please help me? I need to set anything in manifest? – Rajesh Jul 13 '15 at 11:30
  • Look in your manifest.xml file and look for – Keith Loughnane Feb 07 '17 at 13:58
0

Do this inside your onReceive method:

Intent activityIntent = new Intent(this, MainActivity.class);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activityIntent);

You might need to tweak the addFlags call for your specific needs!

thiagolr
  • 6,909
  • 6
  • 44
  • 64