I am facing one strange problem, when i run my android application on the device so either it will be running on foreground or background , it should not loose the WiFi connection, for that I have get the WiFiManager and acquired the lock in Service's onCreate() method and release it on onDestroy method. But facing problem to keep WiFi turned on when device goes to sleep mode, so is there any way to make WiFi turned on even if device goes to sleep mode.
I can't acquire the lock to wake up the device because scenario is our application will run always so whenever user will not use, device should go to sleep mode but wifi connection should always be turned on.
Please do help me resolve this issue, please share some sample code also.
Regards,
Piks
Try to use Services. Just insert you wifi connection code in a service, and this will run forever in background.
Maybe this will help..
private void setNeverSleepPolicy() {
try {
ContentResolver cr = getContentResolver();
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
int set = android.provider.Settings.System.WIFI_SLEEP_POLICY_NEVER;
android.provider.Settings.System.putInt(cr, android.provider.Settings.System.WIFI_SLEEP_POLICY, set);
} else {
int set = android.provider.Settings.Global.WIFI_SLEEP_POLICY_NEVER;
android.provider.Settings.System.putInt(cr, android.provider.Settings.Global.WIFI_SLEEP_POLICY, set);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Related
Let's say I have async tasks that when finished, lock the vibrator and send it a pattern. In a nutshell, that's the kind of code I'm dealing with:
lock(vib);
vib.vibrate(pattern);
release(vib);
return;
The problem is, the vibration starts and just immediately stops due to the task's returning and I could use some help in changing that.
I have tried
lock(vib);
long duration = getDuration(pattern);
vib.vibrate(pattern);
synchronized(this){
try {
wait(duration);
} catch (InterruptedException e) {
...
}
}
release(vib);
return;
but that doesn't seem to actually do anything.
Since I have not found a way to determine whether or not the phone is currently vibrating, any suggestions on how I should best resolve the issue?
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 3 years ago.
Improve this question
I'm Developing an Android Application where it requireds 3 things:-
To keep the App up an running for specific time and then phone will be off (Working Fine)
When phone get charging from outlet, I want phone to power up automatically without hitting any power button. (Not Working with wall Socket, but working when connected to USB cable via Laptop).
After boot my app should start working Automatically (Working Fine)
You Must know :-
My phone is Moto E (rooted) and want 2nd step to be done. Tried some codes but that does not work on moto E.
When Connected with USB it gives 2 as response and when connected with Wall socket charger it says 1
Any help will be Appreciated
P.S :- Auto Boot working with USB cable connected with Laptop but not with Socket Charger
Update-1: 1- Found fastboot oem off-mode-charge 0 working with Nexus 7 but not on Moto e.
2- Moto e boots when connected to Router (USB Dongle Port)
At last I got the solution, you can achieve this by deleting system/bin/charge_only_mode file. Please do that at your own risk and before deleting have backup of that file. I got the desired result that was boot when its connected to wall charger and now its working fine.
All the best!
Moto e4 and Pixel 2 XL:
Get your device into the bootloader (fastboot) and run the following command from a computer connected over USB with Android Tools:
fastboot oem off-mode-charge 0
I was able to get it to work by updating the init.rc file
I found the on charger trigger and added the following lines below it:
setprop ro.bootmode "normal"
setprop sys.powerctl "reboot"
The entire trigger block ends up looking like this
on charger
class_start charger
setprop ro.bootmode "normal"
setprop sys.powerctl "reboot"
You then need to repack and flash the boot image created after the updates.
Connect the device over USB
Power on device and get to bootloader mode
adb reboot bootloader
To flash boot image execute the following command while in fastboot
fastboot flash boot new-boot.img
Note: This fix will cause the device to reboot when its plugged in even when shutting it off using the power button or software shutdown.
Source: https://forum.xda-developers.com/showthread.php?p=77766638#post77766638
You can see the commit that contains these changes for my project here:
https://github.com/darran-kelinske-fivestars/mkbootimg_tools/commit/c8633a2ec2e1924272fd16a8ed7fa7414bb65544#diff-d0007d763b44198f7c22e2c19609d5bbR606
I also tried replacing charge_only_mode with a sh script that rebooted the phone but only got a red circle with the M (on a Motorola Bionic). Changing the script to the below got it working...Now I get the red circle with the M for a few seconds, then a blank screen, the another red circle with the M, and it boots on up.
#!/system/bin/sh
su -c "/system/bin/reboot -n outofcharge"
On my device Lenovo K7000-Plus, the file need to be modified is kpoc_charger located at /system/bin.
Ipod file not working on my phone which using Android 6.0 ROM, but kpoc_charger works pefectly.
Regards
Hadi
For Lenovo A2010 phone,following worked:
Use file manager phone app from playstore like Total commander(on rooted phone) to goto folder /system/bin/
Copy file kpoc_charger and paste it there as kpoc_charger.bak
Now edit the original file kpoc_charger using total-commander, replace all lines with following code:
#!/system/bin/sh
/system/bin/reboot
Save it, goto properties and change UID:0 root, GID:2000 shell and permission as 755 (same as properties of other files in /system/bin folder).
Now shutdown phone and plug to charger.
Bazinga!!!! battery icon shows for a sec but phone sucessfully boots into os.
When phone get charging from outlet, I want phone to power up
automatically without hitting any power button. (Not Working with wall
Socket, but working when connected to USB cable via Laptop).
You can only achieve this by modifying your phone's OS files. Basically there is boot script/binary at /system/bin/chargemon which you can replace with a script that does nothing. Do it at your own risk because this may result in the device being damaged permanently. Also, Manufacturer warranty will become void.
I found another way for this (thanks to DavidThompson256 http://forum.xda-developers.com/showthread.php?t=1187631)
First make sure your phone is rooted (which I found iRoot very good for this), then install RootExplorer.apk (or similar) on your phone.
Try to edit "/system/bin/playlpm" and replace its content with following commands: (do not forget to make a backup first).
#!/system/bin/sh
/system/bin/reboot
(I know the content is in binary, simply remove them and write those two lines and save the file)
NOTE: When you modify that file, no changes will be applied on its permissions but if you are making another file remember to set permissions exactly as it was.
Finally, please do it on your own risk. It worked for me. (Samsung Discovery S730M)
i think there should be power sensor if you can add that in this code i belive it will work
public class Main extends Activity {
private SensorManager mSensorManager;
private PowerManager mPowerManager;
private WindowManager mWindowManager;
private WakeLock mWakeLock;
private Button button;
private TextView textView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
// Get an instance of the SensorManager
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Get an instance of the PowerManager
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
// Get an instance of the WindowManager
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.getDefaultDisplay();
// Create a bright wake lock
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass()
.getName());
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(mButtonStopListener);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("onCreate", e.getMessage());
}
} // END onCreate
View.OnClickListener mButtonStopListener = new OnClickListener() {
public void onClick(View v) {
try {
mWakeLock.release();
textView.setText("mWakeLock.release()");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("onPause",e.getMessage());
}
}
};
#Override
protected void onResume() {
super.onResume();
/*
* when the activity is resumed, we acquire a wake-lock so that the
* screen stays on, since the user will likely not be fiddling with the
* screen or buttons.
*/
try {
mWakeLock.acquire();
textView.setText("mWakeLock.acquire()");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("onResume", e.getMessage());
}
}
#Override
protected void onPause() {
super.onPause();
// and release our wake-lock
try {
mWakeLock.release();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("onPause",e.getMessage());
}
}
}
So I was trying to achieve this with a 3rd gen Moto G. It has a charge_only_mode file as per Rohit's answer, but simply moving/renaming it did not make the phone reboot on charge. Instead it just sat there with a Motorola logo. I got the same result when replacing charge_only_mode with either of the scripts referenced here.
I did get it to work, however. I copied /system/bin/reboot into /system/bin/charge_only_mode, and that did the trick.
All,
I am having a very strange issue.
I have the following code that enables and disables the PIN based on certain conditions
DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;
mDPM = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
mDeviceAdminSample = new ComponentName(context, DeviceAdminSampleReceiver.class);
public void disablePINLock(DBHelper myDBHelper, Context context) {
mDPM.setPasswordQuality(mDeviceAdminSample,
DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
mDPM.setPasswordMinimumLength(mDeviceAdminSample, 0);
boolean result = false;
result = mDPM.resetPassword("", DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
if (result) {
// Toast: "Successfully Disabled PIN lock"
}
else {
// Toast: "Could not disable PIN lock"
}
}
public void enablePINLock(DBHelper myDBHelper, Context context) {
mDPM.setPasswordQuality(mDeviceAdminSample,
DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
mDPM.setPasswordMinimumLength(mDeviceAdminSample, 4);
Cursor c = myDBHelper.getSetting("'random'");
if (c != null) {
boolean result = mDPM.resetPassword("1234",
DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
if (result) {
// Toast: "Successfully Enabled PIN lock"
}
else {
// Toast: "Could not enable PIN lock"
}
}
else {
// Toast: "Could not enable PIN lock"
c.close();
}
}
The code was working fine until a few days ago. I restarted the phone to finish updating and since then the disablePINLock function is not working correctly. When the function executes all I get is
"result" is false and toast message "Could not disable PIN". The enablePINLock method is working just fine and has always worked fine.
Since the restart result = mDPM.resetPassword("", DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY); has failed to execute. I tried to catch an exception but it didn't help.
At this point I am clueless as to why the method stopped working after the restart. I checked the device administrators, enabled/disabled the app few times without any success.
Also I am not sure if this is related, but let me say this. The device administrator screen has my app always checked, even after I uncheck the app and deactivate it, the app name has the box checked.
Thank you in advance for any response.
You say you've "checked the device administrators" but you don't say what you saw there. Are there any other active device administrators on the device? DevicePolicyManager.resetPassword() will return false if the password you provide is not compliant with the aggregate of password policies set by all device admins. It sounds like perhaps another device admin is still active.
Also, with regard to your last point:
The device administrator screen has my app always checked, even after I uncheck the app and deactivate it, the app name has the box checked.
That's a common bug with the Device Administrators screen: the checkbox often stays on even when you've successfully disabled an admin. Try backing out of the Device Administrators screen then going back in. It should be unchecked now.
My app allows the user to access their corporate voice mail. Normally, durring a phone call when the user holds the device up to their ear, the screen shuts off so they wont accidentally push buttons with their face. I would like to make my app do the same thing when the user is listening to their voice mail.
anyone know how to do this?
If you are allowed to look at open source code without causing yourself problems, check the source of the Android Phone Application. Specifically src/com/android/phone/PhoneApp.java and src/com/android/phone/InCallScreen.java.
From src/com/android/phone/PhoneApp.java:
//Around line 519
// Wake lock used to control proximity sensor behavior.
if ((pm.getSupportedWakeLockFlags()
& PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) {
mProximityWakeLock = pm.newWakeLock(
PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK,
LOG_TAG);
}
....
// Around line 1334
if (((state == Phone.State.OFFHOOK) || mBeginningCall)&& !screenOnImmediately) {
// Phone is in use! Arrange for the screen to turn off
// automatically when the sensor detects a close object.
if (!mProximityWakeLock.isHeld()) {
if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: acquiring...");
mProximityWakeLock.acquire();
} else {
if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: lock already held.");
}
} else {
// Phone is either idle, or ringing. We don't want any
// special proximity sensor behavior in either case.
if (mProximityWakeLock.isHeld()) {
if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: releasing...");
// Wait until user has moved the phone away from his head if we are
// releasing due to the phone call ending.
// Qtherwise, turn screen on immediately
int flags =
(screenOnImmediately ? 0 : PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE);
mProximityWakeLock.release(flags);
}
}
Additionally, if you look at the code for the PowerManager class, PROXIMITY_SCREEN_OFF_WAKE_LOCK is documented (but hidden) and should do what you want ( I am not sure which API level this works for, however ) -- but not in the table for some reason.
/**
* Wake lock that turns the screen off when the proximity sensor activates.
* Since not all devices have proximity sensors, use
* {#link #getSupportedWakeLockFlags() getSupportedWakeLockFlags()} to determine if
* this wake lock mode is supported.
*
* {#hide}
*/
public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = WAKE_BIT_PROXIMITY_SCREEN_OFF;
If you aren't afraid of using a potential undocumented feature, it should do exactly what you need.
as of API level 21 (Lollipop) you can get proximity wake lock this just like that:
if(powerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) {
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
wakeLock.setReferenceCounted(false);
return wakeLock;
} else {
return null;
}
}
then it is up to you to acquire and release the lock.
PS: PowerManager#getSupportedWakeLockFlags was hidden, but now exists nomore. They have invented isWakeLockLevelSupported instead.
Probably you don't need it anymore but for the ones that are interested in code you could have a look at my SpeakerProximity project at http://code.google.com/p/speakerproximity/
What you are seeing is the use of a proximity sensor. For devices that have one, you access it through SensorManager.
I have am having some issues with getting consistent results when checking if the network is available or not.
I use this code snippet inside a class AppPreferences to check the availability of a network.
/**
* #return the networkAvailable
*/
public boolean isNetworkAvailable() {
connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
networkAvailable = connectionManager.getActiveNetworkInfo() != null && connectionManager.getActiveNetworkInfo().isConnected();
return networkAvailable;
}
Before each run I set the context as below:
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
appPreferences.setContext(getBaseContext());
if (appPreferences.isNetworkAvailable()){
// perform task
}
}
},
0,
UPDATE_INTERVAL);
I do know it is not tied to the background thread as I have a onReceive call doing the same logic and still this check fails.
It seems to predominantly happen when it moves between a cellular data connection and to wifi, or vice versa. The Context in which it was started seems to stay even though I update it.
Does anyone have any idea what could be the issue here?
It seems as if the active network info will stay on the state of when the Context of the Service/Activity/Receiver is started. Hence if you start it on a network, and then later disconnect from that (i.e. moves from 3G to Wifi and disconnect the 3G connection) it will stay on the first active connection making the app believe the phone is offline even though it is not.
It seems to me that the best solution is to user getApplicationContext instead as that will not be tied to when you started the particular "task".
Update: Related is that if you run applications on Androids (in particular Nexus One) for a long period of time when connected to Wifi do check that you make sure you do not let the Wifi sleep when the screen sleeps. You will be able to set that at the Advanced option under Wireless Networks.