I am currently trying to figure out, how to get the screen on/off event in android. Currently, it works as long as my MainActivity is runnig. But as soon as I close the activity, somehow Sevice and the Receiver stop working aswell (I don't get any Log messages anymore). I guess the problem, is somehow related to the dynamicaly registration of the receiver. As soon as the application gets closed, the receiver gets unregisted (?). How can I keep the receiver alive? (It is not possible to declare the receiver in the Manifest file).
I got the following code:
Main activity:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(getApplicationContext(), ScreenOnOffService.class));
}
}
ScreenReceiver:
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
Log.e("test","onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.d("test","Screen Off ");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.d("test","Screen On ");}
}
}
ScreenOnOffService:
public class ScreenOnOffService extends Service {
//Some unimportant code
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="ch.ethz.inf.thesis.screenonoffproject.app.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ScreenOnOffService">
</service>
</application>
</manifest>
Am I missing something to keep my service alive? I hope somebody can help me out.