How to connect Android Application to Internet when the screen is locked? - android

After some research on Google Search, I tried to find a solution to connect my Android Application to internet when the screen is locked and without the phone charging.
My first impression is that the phone block in background my application. Strange things because others applications on Google Play Store can communicate on the Internet and do things on background.
I have already tried to search solutions on the Internet. My search apparently turn to this link to keep the device awake:
https://developer.android.com/training/scheduling/wakelock
But this solution did not work properly for me and the android system block my application in background when the screen is locked. If the screen is unlocked, the application works properly.
Moreover, I do not understand the problem. Probably, the android energy saver block my application.
Have you any idea to fix this? And if not, how to use the wakeLock?
Thank you :)

there is two way to hold the CPU running (on) even after screen lock
1. Wake Lock
wake lock hold cpu on as long as you acquire it. for acquiring wakelock
first define this permission in manifest
<uses-permission android:name="android.permission.WAKE_LOCK" />
then you can have wakelock like this
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakelockTag");
wakeLock.acquire();
and after your task is done you can release wakelock like this
wakeLock.release();
UPDATE
WakefulBroadcastReceiver is deprecated now with android 8.0
2. WakefulBroadcastReceiver
it's a special broadcast receiver that takes care everything about wakelock
for using this first define in manifest
<receiver android:name=".WakefulReceiver"/>
and then same as we use our service you can do
public class WakefulReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
startWakefulService(context, your_service_intent);
}
}
here you can see all we have to do is start service using startWakefulService
this will take care everything

Related

Is it possible for my GPS application to continue running in the background while the tablet is on standby?

I have created an application that generates a tracklog of the Android devices location. A GPS coordinate is recorded at regular intervals and stored on the device for later download. Currently, when the phone goes on standby, the program stops recording points. Is there a method that would allow the application to continue documenting location while the unit is on standby? Thanks in advance.
According to android documentation, if your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself isn't in the foreground. Also for accessing location in the background you may need additional permissions
You can run a foreground service with showing an ongoing notification if you want to run a service which is always alive in the background. Or you can schedule tasks using WorkManager.
I found two solutions.
1.) Use Wakelock
public void wakeLock() {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyApp::MyWakelockTag");
wakeLock.acquire();
}
with the following added to the manifest XML file,
<uses-permission android:name="android.permission.WAKE_LOCK"/>
or, 2.) use WindowManager to keep the device awake,
public void noSleep() {
if (bNoSleep == true){
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else if (bNoSleep != true){
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
I've chosen the latter as a user selectable feature accessible via checkbox in the main workspace. I've also set this to engage automatically when a tracklog is initiated with the user having the option to disable this and allow standby/sleep to occur. I did implement a wakelock, but had some issues with it that may be related to a custom ROM on some of my Android devices. This is why I went ultimately went w/the windowmanager solution.

Loosing network android 6 and above if app run in backgroud

I am running service background to execute some tasks with some interval using AlaramManager (setExactAndAllowWhileIdle). If its connected the power charger its running. But if its unplugged device power after some i am loosing the network to my application.
Alaram is waking up the service even device is idle.But my app don't have network.
As per https://developer.android.com/training/monitoring-device-state/doze-standby.html# its restricting the network when phone is idle.I tested the same with applying phone idle ($ adb shell dumpsys battery unplug)
But is there any possible to get network access to my application even phone is idle mode.
Application is not of play store. Its really appropriated for suggestion.
I've used PowerManager.isDeviceIdleMode() in your running service to detect whether you're in Doze and if so just invoke setAlarmClock() method with 250 millis (for example) and random broadcast just to wake the device up, it'll completely wake up from doze and thus will get network access as usual. THe down side is that you lose the battery saving that comes with doze.. :D Please mark this as useful should it actually be usefull in your case.
Once your service (set up with setExactAndAllowWhileIdle()) you can go :
private boolean isDeviceInDozeMode() {
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
return pm.isDeviceIdleMode();
So now you know that you're in DOZE or not.
Then you can just set up AlarmClock and set it with setAlarmClock(AlarmClockInfo a, PendingIntent p)
And you're out of Doze with normal network access.
NOTE: Please remember that using setExactAndAllowWhileIdle doesn't mean that your alarm will go off at specified time, it will go off sooner than normal set() method, but not exact (as the method name would suggest). Generally my way isn't perfect in terms of scheduling, but it does exit DOZE programmatically once it's detected on device.
Let me know should you need more update.
I tried many options but none of them works, But finally this works to me.It might help for others.
we can always ask the user to let your app ignore battery optimization functionality using
PowerManager powerManager = (PowerManager)
getSystemService(Context.POWER_SERVICE);
Intent intent=new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
if (powerManager.isIgnoringBatteryOptimizations(getPackageName())) {
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
}
else {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
and in the manifest
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"></uses-permission>
But remember this might make your app not approved by Google Play
https://developer.android.com/training/monitoring-device-state/doze-standby.html#whitelisting-cases

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" />

How to keep Android awake in background when screen is off

I runs web server in my rooted Android Tablet. I setup it for web development. I created a home network by this Android server. but when the screen of the tab turns off, the server also stop working & again start working when i turn on the screen. but its not possible to turn on the screen for long time. I can be harmful for my tablet. Is there any way to keep awake my tablet when the screen is turn off so that my server can work properly in Background.
please help
You can run a service in the background and acquire lock like this :
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,
"MyWakelockTag");
wakeLock.acquire();
and return onStartCommand START_STICKY. To release the wake lock, call wakelock.release().
Do not forget to put the permission in the manifest file :
<uses-permission android:name="android.permission.WAKE_LOCK" />
Or you can use this app to prevent phone from sleeping :
https://play.google.com/store/apps/details?id=nl.syntaxa.caffeine

Keep My App alive - Android

I'm trying to make an App on Android 2.2 that has to run whether the screen is on or off.
I tried realizing it via a Service, but when my phone turns the screen off the service stopps working and I don't understand why.
In my Application I use
startService(new Intent(this, MyService.class));
when the User presses a button
and
Notification notification = new Notification();
startForeground(1, notification);
in the onCreate-Method of the Service class
(I tried it within the onStart() Method, too)
(I also could not find out what the id-field of startForeground() expects so I used the 1)
The service then should start an infinite vibration pattern of the phone so I know whether it is running or not.
But when I turn off the screen, the phone stops vibration immediately
Please help me. I don't know how I can fix that (and google was not a big help)
Sincerely
zed
Android devices go to a sleep mode when idle (e.g. when the screen is off), in order to conserve the battery.
To keep your service running you need to aquire a WakeLock. There are plenty of tutorials how to use it, like this one.
Note that having a service running all the time will drain your battery. Also make absolutely sure to release the wakelock when not needed, otherwise you're phone will always be awake.
Try returning 'START_STICKY' from 'onStartCommand() '. This will keep the service running, restarting it if necessary, without keeping the screen on.
Have a look at http://developer.android.com/reference/android/app/Service.html#START_STICKY
try this
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km .newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
and in manifest file
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
so when your notification or alarm manager service running, screen will light on and the keyguard will unlock.I wish it works for who has this problem too.

Categories

Resources