nasty
nasty

Reputation: 7087

Android - Kill an app when screen turned off or screen times out

I want to kill / fully close an app so it doesn’t run even in the background when I press the screen turn on/off button or if the screen times out. I couldn’t find a solution anywhere on the internet. Can you guys help me out with a code snippet? Thanks

Upvotes: 0

Views: 2608

Answers (3)

Aleksandr
Aleksandr

Reputation: 787

To make activity like a toast (appear-and-go) add following code into manifest:

<activity   android:name=".YourActivity"
            android:label="YourActivityLabel"
            android:taskAffinity=""
            android:clearTaskOnLaunch="true"
            android:excludeFromRecents="true"
            android:finishOnTaskLaunch="true"
            android:noHistory="true"
            android:launchMode="singleTask">
</activity>

Upvotes: 0

Hashir Sheikh
Hashir Sheikh

Reputation: 1821

you can refer this link to detect screen turn off Screen off Broadcast receiver and for killing the app you can use below code

int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);

Upvotes: 3

Ahmad Al-Sanie
Ahmad Al-Sanie

Reputation: 3785

first check if the screen is locked inside a service that runs in the background:

KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if( myKM.inKeyguardRestrictedInputMode()) {
 //it is locked
  getActivity().finish();
  System.exit(0);
} else {
 //it is not locked
}

then you simply kill the app if the screen is locked. hope this will help.

Upvotes: 0

Related Questions