ACTION_POWER_DISCONNECTED triggered when phone start - android

I have an app that play a sound when the phone charger is disconnected. Evrything works well but Android triggers the ACTION_POWER_DISCONNECTED when the phone boot, same when the charger is connected with ACTION_POWER_CONNECTED.
I understand why the OS would make such a thing but is it possible to know that this is due to reboot state, so my sound won't be played?
This happens on Nexus 4, haven't tested other devices.
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == Intent.ACTION_POWER_CONNECTED) {
} else if (intent.getAction() == Intent.ACTION_POWER_DISCONNECTED) {
//Don't want to get there if the phone is rebooting!
}
}
Thanks!

Figured a solution to my problem, this could be a general and easy way to make sure device is not booting when charger intent is called.
Just catch the ACTION_BOOT_COMPLETED (don't forget manifest permission and intent) and set the timestant in a shared preference.
if (intent.getAction() == Intent.ACTION_BOOT_COMPLETED) {
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(context)
.edit();
editor.putLong("uptime", System.currentTimeMillis());
editor.commit();
return;
}
Then to be sure we're not in a boot sequence surround your code with a simple condition comparing to the system uptime:
if (preferences.getLong("uptime", System.currentTimeMillis()) > System.currentTimeMillis() - SystemClock.uptimeMillis()) {
//Your code to be executed there!
}
Hope this will help anyone!

Related

How to prevent a user from disabling my device admin app, through the settings menu?

I'm working on an MDM (Mobile Device Management) app for android, but I have a huge problem and it's that the user can disable my app from within settings>security>device administrators. The only thing I can do about it, is display a warning message by overriding the onDisableRequested(...) method in my DeviceAdminReceiver sub-class, but I really want to prevent the user from disabling my admin app altogether.
I've tried to override the onReceive(...) method, so that nothing happens when the actions ACTION_DEVICE_ADMIN_DISABLE_REQUESTED and ACTION_DEVICE_ADMIN_DISABLED are broadcasted by the system, but so far it has not worked. Apparently some other component is processing those actions before they arrive to my onReceive(...) method and I dont know why. I would like to be able to show my own custom dialog indicating that the user canĀ“t disable the administrator app from this section, and maybe even ask the user to set an admin password to do it.
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_PASSWORD_CHANGED.equals(action)) {
onPasswordChanged(context, intent);
} else if (ACTION_PASSWORD_FAILED.equals(action)) {
onPasswordFailed(context, intent);
} else if (ACTION_PASSWORD_SUCCEEDED.equals(action)) {
onPasswordSucceeded(context, intent);
} else if (ACTION_DEVICE_ADMIN_ENABLED.equals(action)) {
onEnabled(context, intent);
} else if (ACTION_DEVICE_ADMIN_DISABLE_REQUESTED.equals(action)) {
} else if (ACTION_DEVICE_ADMIN_DISABLED.equals(action)) {
} else if (ACTION_PASSWORD_EXPIRING.equals(action)) {
onPasswordExpiring(context, intent);
}
}
I need help to solve this issue.
Thanks,
You can do this from Android 5 Lollipop with the new device-owner mode. Then the Device-Administrator option in greyed-out and the user cannot disable it, thus not uninstall the device-admin App.
However note that installing a device-owner App is not easy, it has to be done at provision-time with NFC, or from a computer with adb (handy for testing but not for deployment), or with a MDM what is your case...
There is no way to prevent user from disabling, and it's his right.
But to get sure that the user himself is actually removing the admin privilege, lock the device in onDisableRequested with his password and return something like "Someone tried to disable this app administrator feature. was it you and are you sure?".
Now if someone other than the real user try to disable it, he has to enter password before proceeding.
I agree with FoamyGuy, you are not allowed to prevent disabling admin. Otherwise, your application can't be uninstalled at all.
Generally speaking a user grants to some application device admin rights and can remove these rights at any moment.
Any broadcasts are just notifications, you can't handle it and prevent some actions from happening. The system just says to listening apps that something is going on.
Also, read this:
How to wipe Android device when device admin is deactivated?
There is a workaround to prevent disabling the device administrator.
When the user initiates deactivation and we recieve ACTION_DEVICE_ADMIN_DISABLE_REQUESTED callback, we re-launch the settings activity intent.
A message is allowed by the OS to be displayed asking for confirmation from the user. According to Android OS rules, for about 5 seconds, no app is allowed to launch on top of this confirmation dialog. So basically the settings activity we tried to open will only launch after 5 seconds.
To pass these 5 seconds without allowing the user to confirm deactivation, the phone is locked by the device administrator repeatedly in a background thread. After 5 seconds when the user unlocks the device, 'Settings' activity will have been restarted.
The following code for Device Admin Broadcast Receiver Class illustrates the above method.
DevAdminReceiver.java
public class DevAdminReceiver extends DeviceAdminReceiver {
DevicePolicyManager dpm;
long current_time;
Timer myThread;
#Override
public void onEnabled(#NonNull Context context, #NonNull Intent intent) {
super.onEnabled(context, intent);
Log.d("Root", "Device Owner Enabled");
}
#Nullable
#Override
public CharSequence onDisableRequested(#NonNull Context context, #NonNull Intent intent) {
Log.d("Device Admin","Disable Requested");
Intent startMain = new Intent(android.provider.Settings.ACTION_SETTINGS);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startMain);
dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
myThread = new Timer();
current_time = System.currentTimeMillis();
myThread.schedule(lock_task,0,1000);
return "Warning";
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_DEVICE_ADMIN_DISABLE_REQUESTED.equals(action)) {
CharSequence res = onDisableRequested(context, intent);
if (res != null) {
dpm.lockNow();
Bundle extras = getResultExtras(true);
extras.putCharSequence(EXTRA_DISABLE_WARNING, res);
}
}else if (ACTION_DEVICE_ADMIN_DISABLED.equals(action)) {
Log.d("Device Admin","Disabled");
}
}
// Repeatedly lock the phone every second for 5 seconds
TimerTask lock_task = new TimerTask() {
#Override
public void run() {
long diff = System.currentTimeMillis() - current_time;
if (diff<5000) {
Log.d("Timer","1 second");
dpm.lockNow();
}
else{
myThread.cancel();
}
}
};
}
Ensure force lock policy is set for the device admin in the resource file.
This is a purely a workaround and not an intended solution from the side of the developers. Apps which abuse device admin permissions are always promptly taken down from the Play Store when exposed.
Complete sample code is present in the following repo
https://github.com/abinpaul1/Android-Snippets/tree/master/PermanentDeviceAdministrator
Not a nice way to do this, but here an idea:
When you receive the callback ACTION_DEVICE_ADMIN_DISABLE_REQUESTED, kill the settings app.
(Search for task-killers to see how)
And make sure you don't kill the settings-app after the user entered the password.
If the settings app is gone, the user can't click the disable button.

Screen on/off validate from android shell

I'm stuck at some validation for screen off and on test. I am using input keyevent 26 to put screen off and the same to wakeup. How to validate this test whether it was passed or failed. Is there any file where android write the state of the screen? any other way from dumpsys power? Can any one please suggest the way to check the state.
Thanks in advance.
You could write a simple app that has a broadcast receiver for the SCREEN ON and SCREEN OFF events, and log the events to the LogCat, and easily see it via adb logcat.
Here is some sample code for that. Make sure your app has been run at least once on the device, or it will not be registered for receiving the broadcast.
public class MyReceiver extends BroadcastReceiver {
private boolean SCREEN_ON = false;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
SCREEN_ON = true;
Log.d(C.TAG, "Screen on");
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
SCREEN_ON = false;
Log.d(C.TAG, "Screen off");
}
}
}

BroadcastReceiver doesn't wake up the phone

I have an alarm application. I generally know the lifecycle of the receiver and how to use WakeLock.
Today however I was contacted by an user that have sent me a really strange log and complained that his alarm hasn't started until he have had unlocked the phone by himself. I used to have problems with phones going back to sleep after receiver completed its work and before activity was started, but creating WakeLock in the receiver seemed to fix the problem. At least until today - from log it seems that onReceive method wasn't called at all until user has unlocked phone by himself.
Facts:
it is the first case I have heard of
it has happened a few times to the user, but not every time
log is prepared by adding text to SQLite database. It doesn't seem to delay application in any significant way
infomation from onReceive was recorded over 100 seconds after expected alarm start time. It is the first method call in onReceive
alarm was started just after user has unlocked the phone
I use AlarmManager.RTC_WAKEUP flag
user says he doesn't have any custom rom. I wait for answer if he has any custom/special lockscreen
phone model is Sony Xperia U ST25A, Android 4.0.4
Any ideas what could be causing this problem? Is it possible that BroadcastReceiver's "inside" WakeLock doesn't work somehow?
EDIT:
I would like to emphasize the issue here - BroadcastReceiver should keep phone awake during its whole onReceive method. However in my case, it is either that
phone falls to sleep before onReceive methods end (even before finishing "logging call")
phone is not awaken by receiver at all
Also, I would like to point out the fact that user has stated clearly - alarm has started precisely when he has unlocked phone by himself. Couple of times.
Some code:
#Override
public void onReceive(Context context, Intent intent) {
Logger.initialize(context, "AlarmReceiver");
...
}
Logger methods:
public synchronized static void initialize(Context context, String text) {
try {
if (mInstance == null) { // this is the block that is runned
BugSenseHandler.initAndStartSession(context, BUGSENSE_ID);
mInstance = new Logger(context);
log("== Logger initialized == from "
+ (text != null ? text : "")); // it stores times as well. Said
// that alarm was started over 100
// seconds after it should
} else {
log("logger initialized again from "
+ (text != null ? text : ""));
}
} catch (Exception e) {
try {
BugSenseHandler.sendException(e);
mInstance = null;
} catch (Exception e2) {
}
}
}
Take a look at WakefulIntentService from Commonsware

Android: Creating a persistent event listener

I am trying to figure out how to implement an event listener (unsure if this is the proper term.) I want the service, once my app is launched, to listen for the phones power status. I am uncertain to as how android handles this situation so don't really know what to search for. I've been working with this code that uses a broadcast receiver:
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
unregisterReceiver(this);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
if (plugged == BatteryManager.BATTERY_PLUGGED_AC) {
// on AC power
Toast.makeText(getApplicationContext(), "AC POWER", Toast.LENGTH_LONG).show();
} else if (plugged == BatteryManager.BATTERY_PLUGGED_USB) {
// on USB power
Toast.makeText(getApplicationContext(), "USB POWER", Toast.LENGTH_LONG).show();
startActivity(alarmClockIntent);
} else if (plugged == 0) {
Toast.makeText(getApplicationContext(), "On Battery", Toast.LENGTH_LONG).show();
} else {
// intent didnt include extra info
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);
The code works fine. When I open my app it will toast what the current status of the phone power is.
Here is what I am trying to do:
When the user launches the app, it is effectively turning on the service
The user can go about using the phone, but once it is plugged in, my service will catch that and use the code above
How do I adapt this code to achieve the objectives above?
You could keep the listener on for the battery status by removing the line
unregisterReceiver(this);
This way, the app will continue to listen to power status change in the background even though that the app is not running in the foreground. Note that at some point, you might still want to unregister your receiver. You probably want to allow the user to control that via settings.
One other note, your code contains starting activity in the receiver in below code:
else if (plugged == BatteryManager.BATTERY_PLUGGED_USB) {
// on USB power
Toast.makeText(getApplicationContext(), "USB POWER", Toast.LENGTH_LONG).show();
startActivity(alarmClockIntent);
}
If your activity is in the background then it can't start another activity. See this SO Question - how to start activity when the main activity is running in background?, the accepted answer has suggestion on how to handle situation that requires starting activity from the background

Intent.ACTION_HEADSET_PLUG is received when activity starts

I am trying to pause music that is playing when the headset is unplugged.
I have created a BroadcastReceiver that listens for ACTION_HEADSET_PLUG intents and acts upon them when the state extra is 0 (for unplugged). My problem is that an ACTION_HEADSET_PLUG intent is received by my BroadcastReceiver whenever the activity is started. This is not the behavior that I would expect. I would expect the Intent to be fired only when the headset is plugged in or unplugged.
Is there a reason that the ACTION_HEADSET_PLUG Intent is caught immediately after registering a receiver with that IntentFilter? Is there a clear way that I can work with this issue?
I would assume that since the default music player implements similar functionality when the headset is unplugged that it would be possible.
What am I missing?
This is the registration code
registerReceiver(new HeadsetConnectionReceiver(),
new IntentFilter(Intent.ACTION_HEADSET_PLUG));
This is the definition of HeadsetConnectionReceiver
public class HeadsetConnectionReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.w(TAG, "ACTION_HEADSET_PLUG Intent received");
}
}
Thanks for the reply Jake. I should have updated the original post to indicate that I discovered the issue that I was having. After a bit of research, I discovered that the ACTION_HEADSET_PLUG Intent is broadcast using the sendStickyBroadcast method in Context.
Sticky Intents are held by the system after being broadcast. That Intent will be caught whenever a new BroadcastReceiver is registered to receive it. It is triggered immediately after registration containing the last updated value. In the case of the headset, this is useful to be able to determine that the headset is already plugged in when you first register your receiver.
This is the code that I used to receive the ACTION_HEADSET_PLUG Intent:
private boolean headsetConnected = false;
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra("state")){
if (headsetConnected && intent.getIntExtra("state", 0) == 0){
headsetConnected = false;
if (isPlaying()){
stopStreaming();
}
} else if (!headsetConnected && intent.getIntExtra("state", 0) == 1){
headsetConnected = true;
}
}
}
I use a different approach to stop playback when headset is unplug. I do not want you to use it since you are already fine, but some other people may find it useful. If you get control of audio focus, then Android will send you an event audio becoming noisy, so if you write a receiver for this event it will look like
public void onReceive(Context context, Intent intent) {
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
if (isPlaying()){
stopStreaming();
}
}
}
I ran into the same issue. I'm not sure what causes it, but at least in my testing it seems to be consistent, which means you can work around it. I did just that by adding a boolean member variable that starts as true, and is set to false on the first onReceive(Context, Intent) call. This flag then controls whether I actually process the unplug event or not.
For your reference, here is the code I use to do just that, which is available in context here.
private boolean isFirst;
public void onReceive(Context context, Intent intent)
{
if(!isFirst)
{
// Do stuff...
}
else
{
Log.d("Hearing Saver", "First run receieved.");
isFirst = false;
}
}

Categories

Resources