Well some months ago I learned the basics of android and now I'm triying to practice to remember what I learned. So the problem is that I'm doing an app that when it catches a change in the status of the screen (screen on/screen off) it does something. I want that when the app is not running (becausethe user killed it by pressing the home button or something like that) it still does what I want. I have decided to use receiver but I don't know if it's the correct option.
If the app is minimized it works but the problem whenthe user presses the "recent apps" button and slides the app. Then the receiver doesn't catch anything.
In the manifest I've declared:
<receiver android:name=".MyReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.SCREEN_OFF"/>
</intent-filter>
</receiver>
My main activity (maybe I have something wrong there):
public class MainActivity extends Activity {
private MyReceiver myReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);
}
@Override
protected void onDestroy() {
if (myReceiver != null) {
unregisterReceiver(myReceiver);
myReceiver = null;
}
super.onDestroy();
}
}
and my receiver:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("android.intent.action.SCREEN_OFF")) {
Log.e("In on receive", "In Method: ACTION_SCREEN_OFF");
Toast.makeText(context, "DO SOMETHING",Toast.LENGTH_LONG).show();
}
else if (action.equals("android.intent.action.SCREEN_ON")) {
Log.e("In on receive", "In Method: ACTION_SCREEN_ON");
Toast.makeText(context, "DO SOMETHING2",Toast.LENGTH_LONG).show();
}
}
}
Really appreciate if you could take a look :D.
Thank you