Ahd Radwan
Ahd Radwan

Reputation: 1100

Lock The Android device screen and prevent the user to unlock it

I am working in Android App that should prevent the user to use the mobile in some-cases . So I tried to lock the screen I used the PowerManger goToSleeo() Method but it needs DEVICE_POWER permission. which is allowed only for the System apps, but my app is not a system app what should I do ?

here is my code

 PowerManager  manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
                 manager.goToSleep(600000);

Upvotes: 2

Views: 628

Answers (3)

Wolfish
Wolfish

Reputation: 970

You don't want to lock the device, that's deliberately designed against. You can, however, disable touch input by overriding onTouchEvent.

You then need to create a view, like so:

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

             <your code here>

    <Disabletouch
        android:id="@+id/black_hole"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</FrameLayout>

And define it like so:

public class DisableTouch extends View {
    private boolean touch_disabled=true;
    @Override
    public boolean onTouchEvent(MotionEvent e) {
        return touch_disabled;
    }
    public disable_touch(boolean b) {
        touch_disabled=b;
    }
}

Call it in the activity:

(DisableTouch) black_hole = findViewById(R.id.black_hole);
black_hole.disable_touch(true);

And reverse:

 black_hole.disable_touch(false);

Upvotes: 0

Booger
Booger

Reputation: 18725

This sort of thing is difficult to do in Android for reason. You are trying to block access to the main OS, which is a bad thing. As other people have mentioned this could be used for malicious purposes (it is not a stretch to think someone could create a ransom-ware app that blocks your device, until you pay something to release it).

So bottom line - you CANNOT do what you are asking (and for good reasons). Especially on a non-rooted phone. One a device is rooted, you CAN do anything (including blocking access to the system buttons).

For more details about this, look into 'Kiosk' mode, or blocking system access (there are many SO questions about this).

Upvotes: 1

0101100101
0101100101

Reputation: 5911

Counterquestion: What purpose would it serve if normal apps could lock your screen? In my eyes, that's malware. You need the permission and nothing will ever change that. The only solution is to remove this "functionality".

Edit: Some more information by the way: Android What permissions required to call PowerManager.goToSleep(n) put device in sleep mode?

Upvotes: 2

Related Questions