0

I am trying to build an app which can be also opened by pressing device power button twice. I have followed this question's answer to build my app. But the background service is not working when the application is closed. Though it seems to work fine when the application is running. Here is the code for service LockService.java

public class LockService extends Service {
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
}

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

public class LocalBinder extends Binder {
    LockService getService() {
        return LockService.this;
    }
}}

BroadcastReceiver class for application ScreenReceiver.java

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

    startService(new Intent(getApplicationContext(), LockService.class));
}}

Finally AndroidManifest.xml file is here. What should i do to work the app properly?

Community
  • 1
  • 1
Pial Kanti
  • 1,550
  • 2
  • 13
  • 26

1 Answers1

0

When your application is closed, LockService gets destroyed. That is why it doesn't work. What you can do is in your Main Activity's onDestroy method, stop the service. Further, in onDestroy method of LockService, send an intent to a broadcast receiver which will start your service again. In this way, whenever your app is closed, broadcast receiver will start your service again and the code inside the service will then be executed.

Vaibhav Agarwal
  • 975
  • 1
  • 7
  • 22