I've been looking around for the last days and none of the answers to the questions made have helped me and I'm bumping my head with something that perhaps is simple to solve .... I want to work with the proximity sensor and what I'm doing is that if I put the finger on the sensor it turns off the screen and if I remove the finger away it turns back on the screen! I'm sucessfully turning off the screen and I'm getting the "Log.i("info", "trying to turn on!")" message when I remove the finger but somehow the screen doesn't turn on .... I've tried with wakelock (commented) and with flags with no sucess! If I remove the finger the lights on the keypad turn on but the screen won't .. If I press the power button two times it turns on the screen sucessfully! Can anyone give me an help with it? :(
#Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
ProximityReading.setText("\nProximity Sensor Reading:" + String.valueOf(event.values[0]));
}
if(event.values[0] == 0) {
WindowManager.LayoutParams params = getWindow().getAttributes();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
params.screenBrightness = 0f;
getWindow().setAttributes(params);
} else {
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1f;
getWindow().setAttributes(params);
/*powermanager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powermanager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wakeLock.acquire();
Log.i("info", "trying to turn on!");
}
}
if you want turn screen on,you can use the API such as "TurnScreenOn" in PowerManager,or use ACQUIRE_CAUSES_WAKEUP combined with FULL_WAKE_LOCK
I use the following method to unlock the phone,lighten it up and then reenable the keyguard lock.
public void unlockAndPowerup(){
KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km.newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
wakeLock.release();
kl.reenableKeyguard();
}
Your procedure is wrong. It may work on some devices by chance, but that's not the way to do it.
FLAG_TURN_SCREEN_ON is supposed to be applied on the onCreate method of an activity. You need to modify your app logic.
Your screen off technique is incorrect. You're modifying brightness, that's a hacky way, and may not turn off screen at all, and drain battery.
You need to achieve it via Device Admin permission. That's the official way to do it
Locking sample code
public static void lockNow(Context c) {
DevicePolicyManager dpm = (DevicePolicyManager)c.getSystemService(Context.DEVICE_POLICY_SERVICE);
if(dpm.isAdminActive(new ComponentName(c.getApplicationContext(),DeviceAdmin.class)))
dpm.lockNow();
}
DeviceAdmin.java
import android.app.admin.DeviceAdminReceiver;
public class DeviceAdmin extends DeviceAdminReceiver {
}
In the manifest
<receiver
android:name=".admin.DeviceAdmin"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
And asking for Device Admin permission
private void askAdminPerm(){
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
new ComponentName(root.getContext(), DeviceAdmin.class));
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, getString(R.string.lock_msg_big));
startActivity(intent);
}
Related
My service starts an Activity like this:
Intent intent = new Intent(context, CallMonitor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
this happens in CallMonitor.onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
On most devices, the activity (called up from service) wakes up the device, turns on the screen and is displayed.
But - for example - on Galaxy Tab 4, the activity is only called if the screen is already switched on.
If the screen is switched off and the service calls up the activity, it is displayed with a delay - It will be displayed immediatly after turning the screen on.
There is also a voice output in the activity. When the Galaxy S4 is switched off, it will not be played back - but immediatly after turning the screen on again.
Any suggestions?
I don't want to use WakeLock!
It looks like that's a device limitation and I don't know how you could work around that without using a WakeLock. We have a really old piece of code which you could modify to your needs which pretty much always worked for us:
public static void bringToFront() {
try {
PowerManager pm = (PowerManager) MainActivity.getAppContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "ALARM");
wl.acquire();
KeyguardManager keyguardManager = (KeyguardManager) MainActivity.getAppContext().getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
if (MainActivity.getAppActivity() != null) {
MainActivity.getAppActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
} catch(Exception e){
e.printStackTrace();
Log.w(TAG, "bringToFront Err: "+e.toString());
}
}
I am trying to wake the screen when the screen is off (dark).
I create a class like the following code:
public class ScreenWakeLock {
private static PowerManager.WakeLock WakeLock;
#SuppressLint("Wakelock")
static void acquireCpuWakeLock(Context context) {
Log.i("ScreenWakeLock", "acquireCpuWakeLock");
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
WakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,"okTag");
WakeLock.acquire();
}
static void releaseCpuLock() {
if (WakeLock != null) {
WakeLock.release();
WakeLock = null;
}
}
}
When the Screen is off , the App call ScreenWakeLock.acquireCpuWakeLock(getActivity());.
But the Screen didn't wake up. I have seen the acquireCpuWakeLock in the log , I am sure the function acquireCpuWakeLock has been called. I also add the <uses-permission android:name="android.permission.WAKE_LOCK" /> in Manifest.xml.
Why the Screen didn't wake up when I call acquire in Android ?
Did I missing something?
Thanks in advance.
Straight from the PowerManager documentation:
In addition, you can add two more flags, which affect behavior of the
screen only. These flags have no effect when combined with a
PARTIAL_WAKE_LOCK.
Use something else instead of PowerManager.PARTIAL_WAKE_LOCK. Try SCREEN_DIM_WAKE_LOCK and see if that's good enough for your use case; if not, try SCREEN_BRIGHT_WAKE_LOCK.
For my application, I need to know that the screen is locked. How to check this is problematically. I used following flag:
if(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON != 0){
// some code
}else if((WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)!= 0){
// some code
}
But this always executing both if and else part... which flag I have to use to check the screen is locked or not?
I'll try to answer this though the question is already old since it is unresolved and could help other googlers. ;)
First you must register a BroadcastReceiver for Intent.ACTION_SCREEN_OFF & Intent.ACTION_SCREEN_ON. Note that this receiver must be registered in codes and will not work when declared in the manifest.
In your broadcast receiver, when you receive Intent.ACTION_SCREEN_ON, you can check if the screen is locked by using the below codes:
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean locked = km.inKeyguardRestrictedInputMode();
KeyguardManager myKeyManager = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
if( myKeyManager.inKeyguardRestrictedInputMode()) {
//screen is locked
} else {
//screen is not locked
}
Register a broadcast receiver with action android.intent.action.ACTION_SCREEN_OFF and write your code in onReceive() method of receiver.
If you are using an activity, onPause() will be called when the screen locked and onResume() will be called when the screen unlocked.
In your code you are checking some flags, i don't know where you will do that checking ? is it continuous verification ? If you are using an activity in your app, the above procedure will happen, just check it in Android Developers website.
I guess you may have already found the answer, but if not (and for other developers), you can do it like this:
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn = powerManager.isScreenOn();
if (!isScreenOn) {
//Screen is in OFF State
//Code to power on and release lock
KeyguardManager km = (KeyguardManager) this
.getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km
.newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();
PowerManager pm = (PowerManager) this
.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
}
There are broadcasted intents for screen lock & unlock.
Check it like :
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){//LOGIC Here}
Let me know!
Here is what I did:
This handles if the user has unlocked the screen, but not yet entered the home screen or the user's screen is turned off say during a call.
if (Intent.ACTION_SCREEN_ON.equals(pIntent.getAction()) ||
Intent.ACTION_USER_PRESENT.equals(pIntent.getAction())) {
if(mListener!=null) {
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
boolean locked = km.inKeyguardRestrictedInputMode();
Log.v(TAG, ": Phone lock state from KEYGUARD_SERVICE: Current state:" + (locked ? "LOCKED":"UNLOCKED"));
mIsPhoneLocked = locked;
}
}
I can't turn off the screen using this code. I used PowerManager and wl.release() method, but it doesn't work. Can somebody show me an example?
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
This is part of my function:
stateString = "nextone";
if(stateString=="nextone"){
wl.release();
}
I also added permission in the manifest but no result.
I found the answer over here on stack overflow: Turn off screen on Android
Copied from there:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
I tried this out and it seems to work.
If you don't use a permission, the program will crash with a SecurityException when it tries to lock, so that isn't the problem. The correct method is: (obtains WakeLock on start, gives it up when the application loses focus (onPause)
//declared globally so both functions can access this
public PowerManager.WakeLock wl;
///////////onCreate
//stop phone from sleeping
PowerManager powman = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = powman.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "NameOfLock");
wl.acquire();
///////////onPause
wl.release();
//////////for completion's sake, onResume
if(!wl.isHeld()){
wl.acquire();
}
However, your problem is actually in this check
if(stateString=="nextone")
This should be if(stateString.equals("nextone"))
please check this link before proceeding with wake lock. if it does not solve your problem then you can proceed with wake lock.
Force Screen On
You can use
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
try
{
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000*15);
}
catch (NumberFormatException e)
{
Log.e("aa", "could not persist screen timeout setting", e);
}
How to detect switching between user and device
My goal is make same thing as power button do.
I try PARTIAL_WAKE_LOCK and this is my code..
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wl.acquire();
after that I open WAKE_LOCK permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WAKE_LOCK" />
But when I launch my application not thing happen.
Do I miss something ?
Thanks
From your question I'm not totally sure whether you:
Try to turn off the device by pressing a button
Want to make sure the device will not go to sleep (as this is what a WakeLock is supposed to help you with). It can't prevent user interaction though (just tested on HTC Desire).
For 1) You can't lock the device or turn it's power off without being signed as a system app, as written here: http://groups.google.com/group/android-developers/browse_thread/thread/36399f15724ac3ae/98d93e53616cf495?show_docid=98d93e53616cf495
For 2) You can prevent the device from sleeping using WakeLock, sample code can read like this:
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
}
// Call me from a button
public void doLock(View view) {
Log.d(TAG, "Lock");
if (!wl.isHeld()) {
Log.d(TAG, "acquire");
wl.acquire();
} else {
Log.d(TAG, "release");
wl.release();
}
}