Android PhoneStateListener: onCellLocationChanged in standby mode - android

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

Related

Why the Screen didn't wake up when I call acquire in Android?

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.

Lock Android Phone after user dials a phone number

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

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

Turn off screen on Android

I am trying to turn on and off the display after a certain action happens (Lets just worry about turning the screen off for now). From what I understand from wake lock, this is what I have:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
When I read other posts on stackoverflow and else where, they seem to tell me that PARTIAL_WAKE_LOCK will turn the screen off. But if I read the SDK it says that it will only allow the screen to be turned off. I think this isn't right.
There are two choices for turning the screen off:
PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
// Choice 1
manager.goToSleep(int amountOfTime);
// Choice 2
PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag");
wl.acquire();
wl.release();
You will probably need this permission too:
<uses-permission android:name="android.permission.WAKE_LOCK" />
UPDATE:
Try this method; android turns off the screen once the light level is low enough.
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
The following is copied from SDK document.
If you want to keep screen on, I think SCREEN_BRIGHT_WAKE_LOCK is enough.
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
For me those methods didn't work. So I used other scenario (not trivial) to make my screen off.
Android has 2 flags that responsible to be awake:
Display --> Screen TimeOut
Application --> Development --> Stay awake while charging check box.
I used followed flow:
1st of all save your previous configuration, for example screen timeout was 1 min and Stay awake while charging checked.
After, I uncheck Stay awake while charging and set screen timeout to minimal time.
I register to broadcast receiver service to get event from android that screen turned off.
When I got event on screen off, I set previous configuration to default: screen timeout was 1 min and Stay awake while charging checked.
Unregister receiver
After 15 sec. device sleeps
Here is snippets of code:
BroadcastReceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Catch Screen On/Off
* */
public class BroadcastReceiverScreenListener extends BroadcastReceiver{
private BroadCastListenerCallBackItf mBroadCastListenerCallBack = null;
public BroadcastReceiverScreenListener(
BroadCastListenerCallBackItf broadCastListenerCallBack) {
this.mBroadCastListenerCallBack = broadCastListenerCallBack;
}
#Override
public void onReceive(Context arg0, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mBroadCastListenerCallBack.broadCastListenerCallBack__ScreenOff_onResponse();
}
}
}
Interface used as callback
public interface BroadCastListenerCallBackItf {
public void broadCastListenerCallBack__ScreenOff_onResponse();
}
2 methods from main class:
....
AndroidSynchronize mSync = new AndroidSynchronize();
....
public void turnScreenOff(int wait){
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadCastListenerCallBackItf broadCastListenerCallBack = this;
BroadcastReceiver mReceiver = new BroadcastReceiverScreenListener(broadCastListenerCallBack);
m_context.registerReceiver(mReceiver, filter);
//set Development --> disable STAY_ON_WHILE_PLUGGED_IN
Settings.System.putInt(
m_context.getContentResolver(),
Settings.System.STAY_ON_WHILE_PLUGGED_IN,
0 );
// take current screen off time
int defTimeOut = Settings.System.getInt(m_context.getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT, 3000);
// set 15 sec
Settings.System.putInt(m_context.getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT, 15000);
// wait 200 sec till get response from BroadcastReceiver on Screen Off
mSync.doWait(wait*1000);
// set previous settings
Settings.System.putInt(m_context.getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut);
// switch back previous state
Settings.System.putInt(
m_context.getContentResolver(),
Settings.System.STAY_ON_WHILE_PLUGGED_IN,
BatteryManager.BATTERY_PLUGGED_USB);
m_context.unregisterReceiver(mReceiver);
}
public void broadCastListenerCallBack__ScreenOff_onResponse() {
mSync.doNotify();
}
....
AndroidSynchronize class
public class AndroidSynchronize {
public void doWait(long l){
synchronized(this){
try {
this.wait(l);
} catch(InterruptedException e) {
}
}
}
public void doNotify() {
synchronized(this) {
this.notify();
}
}
public void doWait() {
synchronized(this){
try {
this.wait();
} catch(InterruptedException e) {
}
}
}
}
[EDIT]
You need to register permission:
android.permission.WRITE_SETTINGS
Per this link, You can also turn the screen off like this:
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000);
1000 is in milliseconds which means 1 second, you can replace it with any value as desired.
Needed permission:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
try -
wakeLock.acquire(1000); // specify the time , it dims out and eventually turns off.

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