Lock Android Phone after user dials a phone number - android

I am developing a security application whereby, if a user dials a phone number that is not frequently called and he has never called before, the user will have to reauthenticate himself. For this purpose I want to lock the phone after checking the phone number.
public class outgoingCalls extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.v("onReceive", "In onReceive()");
if (confidence == 0) {
Log.v("onReceive","confidence zeroed");
Intent i = new Intent();
i.setClassName("abc.xyz.SECURITY","abc.xyz.SECURITY.lockActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
In this new Activity lockActivity, I need to lock the phone where I have commented // LOCK PHONE
public class lockActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("lock","lockActivity onCreate method called");
// setContentView(R.layout.main);
Log.v("lock","locking");
// LOCK PHONE
}
}
The phone is not getting locked with the methods I have tried. These include the following:
1. KeyguardManager mgr = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = mgr.newKeyguardLock("edu.Boston.SECURITY.lockActivity");
((KeyguardLock) lock).reenableKeyguard();
2. PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
manager.goToSleep(100);//int amountOfTime
3. PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Tag");
wl.acquire();
wl.release();
4. WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 0;
getWindow().setAttributes(params);
Android manifest file has below permissions
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
Why am I not able to lock the phone? Any pointers?
Thanks a lot in advance for your help. Appreciate it!

Try creating a DevicePolicyManager
http://developer.android.com/training/enterprise/device-management-policy.html
and then call:
DevicePolicyManager mDPM = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
mDPM.lockNow();

Related

How to keep sceen on in Android?

How to keep screen on in Android?
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + Uri.encode("+86 212312142")));
startActivityForResult(callIntent, 100);
I want the screen keep turn on, even in the phone dial activity. (No Dim)
I try this
PowerManager pm = (PowerManager) act.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "XXXX");
wakeLock.acquire();
I think you need to add extras permission to use wakelock
<uses-permission android:name="android.permission.WAKE_LOCK" />
but instead of wakelock I recommend you to use this :
#Override
protected void onCreate(Bundle savedBundle) {
super.onCreate(savedBundle);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
there is a good discussion about not using wakelock here -> Force Screen On

Unlock device, display a text, then lock again

For the need of my application, I need to display a message on the screen even if the lockscreen is enabled, then wait 3 seconds, than I have to lock again the phone as I don't want it to make unwanted phone calls in your pockets.
First part is easy:
if (PreferenceManager.getDefaultSharedPreferences(
getBaseContext()).getBoolean("wake", false)) {
KeyguardManager kgm = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean isKeyguardUp = kgm.inKeyguardRestrictedInputMode();
WakeLocker.acquire(ProtoBenService.this);
Intent myIntent = new Intent(ProtoBenService.this,LockActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (isKeyguardUp) {
ProtoBenService.this.startActivity(myIntent);
} else
Toast.makeText(ProtoBenService.this.getBaseContext(), intention, Toast.LENGTH_LONG).show();
WakeLocker.release();
}
With this class:
public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;
public static void acquire(Context ctx) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "CobeIm");
wakeLock.acquire();
}
public static void release() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}
And the Activity:
public class LockActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
TextView tv = new TextView(this);
tv.setText("This is working!");
tv.setTextSize(45);
setContentView(tv);
Runnable mRunnable;
Handler mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
LockActivity.this.finish();
}
};
mHandler.postDelayed(mRunnable, 3 * 1000);
}
}
So, this is nice, the phone can display my text!
The only problem comes when I want to lock again the phone, it seems that locking the phone is protected by the system...
Programmatically turning off the screen and locking the phone
how to lock the android programatically
I think that my users won't understand the Device Admin and won't be able to activate it. Is there any workaround to lock the screen without the Device Admin stuff?
I used the following method for locking and unlocking phone.
initializing
KeyguardLock keyguard;
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
keyguard = km.newKeyguardLock("MyApp");
to unlock phone
keyguard.disableKeyguard();
to lock phone again
keyguard.reenableKeyguard();
to turn screen on
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
and dont forget to use the following permission
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
I am pretty sure that you have to use the Device Admin Features to lock the screen.
protected static void initiateDeviceLock(Context context) {
ComponentName componentName = new ComponentName(context, MyDeviceAdminReceiver.class);
DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
boolean active = dpm.isAdminActive(componentName);
Log.i(context.getClass().getSimpleName(), "Active (in initiateDeviceLock) = " + String.valueOf(active));
if (active) {
dpm.lockNow();
}
}
To help the user's setup the Device Admin features you can take them to the settings page:
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
ComponentName componentName = new ComponentName(TestActivity.this, MyDeviceAdminReceiver.class);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
startActivityForResult(intent, CODE);

Android: Wake & unlock phone

I am trying to figure out how to wake and unlock the phone with a service. I have been referring to this post but, I can't figure out why it isn't working. This is the code that I have so far:
public class WakephoneActivity extends Activity {
BroadcastReceiver mReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Log.v(TAG, "Screen OFF onReceive()");
screenOFFHandler.sendEmptyMessageDelayed(0, 2000);
}
};
}
private Handler screenOFFHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// do something
// wake up phone
// Log.i(TAG, "ake up the phone and disable keyguard");
PowerManager powerManager = (PowerManager) WakephoneActivity.this
.getSystemService(Context.POWER_SERVICE);
long l = SystemClock.uptimeMillis();
powerManager.userActivity(l, false);// false will bring the screen
// back as bright as it was, true - will dim it
}
};
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(mReceiver, filter);
// Log.i(TAG, "broadcast receiver registered!");
}
}
I have added the code in the manifest as well. Any ideas?
Use this code below in your service.
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock((PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "YourServie");
mWakeLock.acquire();
[...]
mWakeLock.release();
If you want to unlock the screen as well, register a receiver in your service that monitors if the screen is turned on/off and if it is turned off and you want to unlock the phone, start an activity with this code in onCreate:
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
this.finish();
return;
I know, this is a rather dirty, but as far as I know, there is no other way of unlocking the lockscreen (and this will only work if there are no passwords etc set, so it must be the normal "slide to unlock" screen).
And don't forget to add android.permission.WAKE_LOCK ;-)
/edit: I just saw you are already using an Activity. If you have one and don't need the service at all, just put this code into the activity.
For the service to be allways active you need to have this permission on manifest:
<uses-permission android:name="android.permission.WAKE_LOCK" />
Another thing you need to do is to adquire a WakeLock. Without it the service will end passed some time. You can do it like this:
getApplicationContext();
PowerManager pm = (PowerManager)getApplicationContext().getSystemService(Context.POWER_SERVICE);
WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wl.acquire();
You might need to change PowerManager.PARTIAL_WAKE_LOCK to the one that you need. You can see info about that here.
There is WakefulBroadcastReceiver which does this for you. Example use:
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, SimpleWakefulService.class);
// Start the service, keeping the device awake while it is launching.
Log.i("SimpleWakefulReceiver", "Starting service # " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}
After completing the action in the service, call SimpleWakefulReceiver.completeWakefulIntent(intent) to release the wake lock.
(as #Force already gave you the details about the wakeLock, they need not be repeated here ;-)
Mind that the class is deprecated from api level 26.1.0, reference here

Android PhoneStateListener: onCellLocationChanged in standby mode

I'm writing an app that runs in the background as a foreground service. This service instantiates a subclass of PhoneStateListener. The PhoneStateListener creates a TelephonyService with a context object of the foreground service and then listens to cell location changes. This works perfectly while the display in on. But as soon as the display goes off, the logging of the cells doesn't work anymore.
public class gps_service extends Service
{
public static TelephonyManager p_TelephonyManager = null;
public static myPhoneStateListener p_myPhoneStateListener = null;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
p_myPhoneStateListener = new myPhoneStateListener();
p_TelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
p_TelephonyManager.listen(p_myPhoneStateListener, PhoneStateListener.LISTEN_CELL_LOCATION);
...
}
public class myPhoneStateListener extends PhoneStateListener
{
public static int CurrentCellID;
/*
public static int current_cell_id;
#Override
public void onCellLocationChanged(CellLocation p_CellLocation)
{
//write to log
}
}
<uses-sdk android:minSdkVersion="3" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
When phone screen is on, all working fine, but when turn screen of onCellLocationChanged event never call.
Also I try
GsmCellLocation currentCellLocation = (GsmCellLocation) p_TelephonyManager .getCellLocation();
by this code always return last cell id before off screen, not actual cell id.
Also I try partial_wake_lock in my service, but the same results:
private PowerManager pPowerManager = null;
private PowerManager.WakeLock pWakeLock = null;
..
#Override
public void onCreate()
{
super.onCreate();
pPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
pWakeLock = pPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "No sleep");
pWakeLock.acquire();
...
}
#Override
public void onDestroy()
{
if (pWakeLock != null)
{
pWakeLock.release();
pWakeLock = null;
}
...
}
Any idea what I do wrong? Testing on HTC Desire Z Android 2.2
This situation is screen off thus, phone goes into sleep mode.
Take a look into PowerManager.
The following flags are defined, with varying effects on system power. These flags are mutually exclusive - you may only specify one of them.
Flag Value CPU Screen Keyboard
PARTIAL_WAKE_LOCK On* Off Off
SCREEN_DIM_WAKE_LOCK On Dim Off
SCREEN_BRIGHT_WAKE_LOCK On Bright Off
FULL_WAKE_LOCK On Bright Bright
*If you hold a partial wakelock, the CPU will continue to run, irrespective of any timers and even after the user presses the power button. In all other wakelocks, the CPU will run, but the user can still put the device to sleep using the power button.
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
..screen will stay on during this section..
wl.release();

What should I do as power button do (turn off screen, lock keyboard)?

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

Categories

Resources