unlocking a screen via code in android - android

How do I unlock phone screen when some event happens?I tried the following code but it does not unlock the screeen . By unlock I mean bypass PIN or pattern
Am using following code and its get triggered when a sms is received.
private void unlockScreen(Context context){
Log.d("dialog", "unlocking screen now");
PowerManager powermanager = ((PowerManager)context.getSystemService(Context.POWER_SERVICE));
WakeLock wakeLock = powermanager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
wakeLock.acquire();
Window wind = DialogActivity.this.getWindow();
wind.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
wind.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
wind.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
}
Screen is powered on but the user has to enter PIN/pattern.How do I get over it?

Straight from the android API Site for disableKeyguard():
Disable the keyguard from showing. If the keyguard is currently
showing, hide it. The keyguard will be prevented from showing again
until reenableKeyguard() is called. A good place to call this is from
onResume() Note: This call has no effect while any DevicePolicyManager
is enabled that requires a password.
Based off that bolded statement I would probably say that you cannot do that without a password. The only way passed that is if you had yourself(app) added to the phone as a device admin, then you could control that from your device admin application of removing the password, wiping it etc.
Source : KeyguardManager.KeyguardLock & DevicePolicyManager
EDIT
I found the source code of the LockPatternUtils (I know it is from older version, but I doubt it has changed much) that is in part pattern locks and it has DevicePolicyManager all over it. I believe it has an internal service running as root in the system that does all the work. So without being a device admin, you do not even have authority to unlock the phone when it has a security setting for it.

Related

Android Wear - Wake lock not waking up watch

I am trying to make the watch vibrate at specific moments that are not at regular intervals.
I have no problem doing it when the watch's screen is on but it is not working when the watch screen dims out.
I have read a few questions on here and android developer's pages on WakeLocks and I think it's what I need... However it does not work for me. Below is my code, am I doing something wrong?
First, in my Manifest file, I have:
<uses-permission android:name="android.permission.WAKE_LOCK" />
Here is parts of my code:
PowerManager.WakeLock wakeLock;
#Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, TAG);
}
private void vibrate(int duration) {
wakeLock.acquire();
Vibrator v = (Vibrator) getBaseContext().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(duration);
wakeLock.release();
}
The screen doesn't turn on and the watch doesn't vibrate... What am I doing wrong?
Thank you!
If your watch doesn't vibrate when you get a notification or you're not seeing notifications at all, check your watch after each step to see if notifications start working. try the troubleshooting steps below:
Make sure that your watch isn't in Cinema mode.
Make sure that you're getting notifications on your phone.
Make sure that you haven't turned off (block) notifications for specific apps.
Make sure that app notifications and system notifications on your phone are turned on.
Check that your phone is connected to the Internet.
Make sure that your watch is paired with your phone or tablet.
Try restating your phone and your watch.
Check that these apps are up to date: Google Play Services, Google, Android Wear.
Try to awake device by using the flag FLAG_KEEP_SCREEN_ON.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
The advantage of this approach is that unlike wake locks, it doesn't require special permission, and the platform correctly manages the user moving between applications, without your app needing to worry about releasing unused resources.
Another way to implement this is in your application's layout XML file, by using the android:keepScreenOn attribute:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true">
...
</RelativeLayout>
Using android:keepScreenOn="true" is equivalent to using FLAG_KEEP_SCREEN_ON. You can use whichever approach is best for your app.
You need to keep the wake lock acquired for as long as you want the watch to stay interactive (and vibration to continue -- you must be in interactive to vibrate), but you seem to be releasing the wake lock immediately after acquiring it.
Acquiring wake locks can be risky, so if you're running that code from a watch face service (not clear from your snippet), start a transparent activity when acquiring your wake lock and release it when the activity dies -- this way, you are using the activity lifecycle as a means to stop the vibration and release a wake lock. This is something I implemented in the ustwo Timer Watch Faces (the watch face starts flashing and vibrating in interactive mode when the timer expires), and it's worked well.
Also, remember that to make vibration work, you need to declare the vibrate permission in the manifest:
<uses-permission android:name="android.permission.VIBRATE" />

Disable Keyguard upon receiving SMS

I am developing an SMS android application. One of the feature, I want to add is upon receiving an SMS the screen lock will be automatically disabled so that user need not unlock to read the message.
Is this possible? I tried few examples but those are the working. E.g How to Disable Keyguard and display an activity to the user when receiver of SCREEN_ON is triggered?
Any idea how to implement this?
You should use something like this :
KeyguardManager myKGuard = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
myLock = myKGuard.newKeyguardLock("com.example.myapp.Main");
myLock.disableKeyguard();
Also please note you will need to add DISABLE_KEYGUARD Permission to the manifest as well.
Hope this helps!
This is deprecated as of API 13 as well.
Use FLAG_DISMISS_KEYGUARD and/or FLAG_SHOW_WHEN_LOCKED instead; this allows you to seamlessly hide the keyguard as your application moves in and out of the foreground and does not require that any special permissions be requested. Handle returned by newKeyguardLock(String) that allows you to disable / reenable the keyguard.
That is what Google says as of now !

How to turn screen off or send device to sleep

I want to send device to sleep or turn the screen off. I have investigated and found this topic: Turn off screen on Android
Basically, the are three ways to do it, but I have found problems for the three:
a) Choice 1:
PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
manager.goToSleep(int amountOfTime);
Problem: It causes FC. I have read I need DEVICE_POWER permissions, but it can't be granted for normal apps.
b) Choice 2:
PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag");
wl.acquire();
wl.release();
Problem: This does not work for me. I don't know why. It does not give me a FC, but it is innocuous.
c) Choice 3:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
Problem: I can get it to work but when try to turn on device it does strange things, like don't like to return, or if my apps is in front, automatically goes to sleep just after pressing on button. This looks more like a tip or workaround than normal solution.
Can anyone tell me any good method to send device to sleep or turn screen off that can run without problems? It sound rare to me that a simple functionality like this has not a good way to use it (or at lest well documented)
I answer myself. It is possible to turn off the device, but the application has to implement the device administrator feature via API: Device Administration
In this API there is a locknow() function that do what I want.
Anyway, this is for extending the android hardware and security features and it is very unlikely that anyone wants to control the device in that way.
What I wanted is the ability to lock the device from a simple gesture. As I dont want to make my own device manager class I check if the free application "lockScreen" is installed and launch it. It is a shortcut and an easy way to do what I want. This app must be register as device manager so it has implemented this class. It is possible to get it free from the market.
My application already does this fine, I found this in my PowerManager.class
/**
* Force the device to go to sleep. Overrides all the wake locks that are
* held.
*
* #param time is used to order this correctly with the wake lock calls.
* The time should be in the {#link SystemClock#uptimeMillis
* SystemClock.uptimeMillis()} time base.
*/
public void goToSleep(long time)
{
try {
mService.goToSleep(time);
} catch (RemoteException e) {
}
}

Android Keyguard and DevicePolicyManager

I'm trying to lock/unlock the screen using Keyguard and everything works as expected when using the KeyguardManager.KeyguardLock disableKeyguard() and reenableKeyguard() functions.
I've tried it with "regular" slider lock, pattern, PIN and password lock and
they are all disabled and enabled when the appropriate functions are called.
The only thing that worries me is that the documentation of these functions has the following statement:
This call has no effect while any DevicePolicyManager is enabled that requires a password
I'm not sure I understand exactly in which cases this might not work and wouldn't like to find out after I release my application...
I tried reading a bit more on DevicePolicyManager but couldn't find any way to find out if there is an active DevicePolicyManager that will prevent the enable/disable screen lock functions to work.
Can you please describe a scenario that this will not work, and how I can identify these cases ?
The most common form of this "in the wild" is the user having a corporate Exchange device admin that requires they have a password. I believe the DeviceAdmin in the APIDemos is sufficient to test against this.

How to tell if device is sleeping

Here's my scenario. I have an app that is playing backgound sounds. Using the BroadcastReceiver I can tell when the display turns off, and then kill the sounds. I can also tell if the screen turns back on. However, if the device is in the lock state I don't want the audio to start. Therefore I wait for the ACTION_USER_PRESENT intent to signal. That all works, except that if the user turns the screen back on quickly after it was turned off, you don't get the lock screen or the ACTION_USER_PRESENT message. So, is there a way to tell, when the screen turns back on, if the device is locked or not, which I guess also means sleeping or not?
((PowerManager) getSystemService(Context.POWER_SERVICE)).isScreenOn()
You can try the KeyguardManager to check if the device is locked. Here is some code (I haven't tried this myself):
KeyguardManager kgMgr = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean showing = kgMgr.inKeyguardRestrictedInputMode();
Good luck!
Satur9nine's solution was right at the time, but since then isKeyguardRestricatedInputMode() was deprecated. Some powerManager related functionalities are now deprecated as well.
There's a newer, more accurate solution: isKeyguardLocked() for whether the device is locked, and a different approach to obtain whether the screen is interactive; You're looking for a combination of both.
KeyguardManager appKeyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
PowerManager appPowerManager = (PowerManager) getSystemService(Context,POWER_SERVICE);
boolean showing = !appKeyguard.isKeyguardLocked() && appPowerManager.isInteractive();
((PowerManager) getSystemService(Context.POWER_SERVICE)).isScreenOn()
tells if the screen is on. So, it gets true if the screen is on but the device is locked.
Instead,
inKeyguardRestrictedInputMode()
gets true just if the device is locked.

Categories

Resources