I am coding an application which will trigger some action (like toast message) every 5 minute after the Screen is ON. I have made a 'Service' for this purpose. My Service is running successfully and triggering the specified action every 5 minutes.
My 'Service' keeps on running even when the Screen is OFF. I don't want to perform any action when the Screen is OFF. Should I stop the service on every screen OFF and re-run it on the next screen ON? or should I keep it running even when the Screen is OFF?
I just want to decrease the load on CPU performance because of the background running 'Service'.
Let the service keep running, and display the Toast only if the screen is off using following code,
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
Now,
if ( isScreenOn )
{
// Display Toast
}
else
{
// Do nothing
}
Related
What I want:
I am developing one app where I want to display dialog / popup on incoming call.
I have observed in log that there is slight delay between my activity start on incoming call and phone screen getting on. First activity gets fired and then phone screen gets on.
So I want to display this dialog after the phone screen gets on. In short I want to wait till phone gets on.
What I Tried:
I have used Asynctask in BroadcastReceiver
protected Boolean doInBackground(Void... params) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
isScreenOn = powerManager.isInteractive();
return isScreenOn;
}
and followed this answer. But it is giving me compile time exception
unhandled exception java.util.concurrent.executionexception even after searching a lot on google I was not able to solve it. So I used another approach.
I have created another* broadcast receiver for phone screen status as per this link
(*Note I already have incoming call broadcast receiver)
But I am not able to figure out how incoming call broadcast receiver will communicate to phone screen broadcast receiver and wait till phone screen gets on.
I have even tried to add intent action in existing broadcast receiver but again dont know how to wait till phone screen gets on.
Any pointers/suggestions?
After Struggling a lot on this issue, finally able to solve it. Posting the answer if anybody else struggling for similar issue.
case TelephonyManager.CALL_STATE_RINGING: //Incoming Call Ringing
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//Calling activity to show dialog / popup window.
}
}, 1000);
It was that simple. Phew!!
I have Created a methods to send SMS and call under function callfunction();
I want to call that function when the user have pressed four time power button, It should not required that app should be in launched state.
Try using the Power Manager
PARTIAL_WAKE_LOCK
added in API level 1
int PARTIAL_WAKE_LOCK
Wake lock level: Ensures that the CPU is running; the screen and keyboard backlight will be allowed to go off.
If the user presses the power button, then the screen will be turned off but the CPU will be kept on until all partial wake locks have been released.
Constant Value: 1 (0x00000001)
Example:
//Initialize the Power Manager
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//Create a PARTIAL_WAKE_LOCK
//This will keep the cpu running in the Background, so that the function will be called on the desired Time
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
//Check if the WackLock is held (may throw erro if you try to acquire twice)
//TRUE --> Do nothing, all good
//FALSE --> Acquire the WakeLock
if(!wl.isHeld()){
wl.acquire();
}
//*****
//You code to handel the Powerbutton comes here
//*****
//If the Repeating task is not active, release the Lock
//Check if the WackLock is held (may throw error if you try to release a none acquired Lock)
//TRUE --> Release Lock
//FALSE --> Do nothing, all good
if(wl.isHeld()){
wl.release();
}
To handle the Power Button, check this Post:
How to hook into the Power button in Android?
This is just an assumption, if it still doesnt work, could you post some Logs or more code snippets of your project :)
I think this is not possible to keep track of power button press for 4 times and to start your expected functionality. Since i don't find any app on play store which has this kind of functionality so as to start there respected jobs.
But you will get trigger for power button press for 1 time.
I'm creating this incredibly simple app, since I'm just starting with Android and I have no experience with Java what so ever. Anyhow, all I have is a timer and a button. Obviously the button starts the timer which counts down from 60 ( 1 minute ) and then vibrates when it's done. All worked fine up until the point I decided to press the lock screen button to put the phone to sleep. I found out that the timer in my app stops going until I unlock the phone. This also happens if I set the auto sleep time to less than 60 seconds and the phone falls asleep on it's own. My question is - how can I have that chronometer running even when the screen is not active?
You need to make this using BroadCastRecievers for system-calls. (Related Helpful question)
You can also play off the life-cyles of the Activity using the PowerManager.
Example using PowerManager:
#Override
protected void onPause()
{
super.onPause();
// If the screen is off then the device has been locked
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn = powerManager.isScreenOn();
if (!isScreenOn) {
// The screen has been locked
// Continue your timer
}
}
I use wakelock to keep the display on.
However, when the app is ended, the display also be turned off.
I want to keep it on after the app is ended.
What should I do?
What you want to do is use the .On_AFTER_RELEASE flag see below.
PowerManager pm;
PowerManager.WakeLock wakeLock;
// Put the next 5 lines in a method that is called when you want to acquire a wakelock //or in the OnREceive() of a broadcast receiver.`
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(
pm.ON_AFTER_RELEASE|pm.SCREEN_DIM_WAKE_LOCK, "My wakelook");
wakeLock.acquire();
...Do Stuff here
//Override the onDestroy of your activity to release the wakelock when it is destroyed.
#Override
protected void onDestroy() {
super.onDestroy();
wakelock.release;
}
This will keep the screen lit up as if someone interacted with the device (pushed the power button, touched the screen, etc.) right when you release the wakelock. At that point a normal power down will occur if there is no further interaction with the device (screen goes dim, and then it goes dark).
I
Let me know if that helped.
Thx
******************Added*************
If you want to wake up the phone from after the screen goes dark you can create your wakelock with the following flags. This is good if you have a broadcast receiver and want to turn on the screen when an event happens so the user can immediately see a UI (Notification, Toast, Layout,etc.)
PowerManager.WakeLock wakeLock = pm.newWakeLock(
pm.ACQUIRE_CAUSES_WAKEUP|pm.ON_AFTER_RELEASE|pm.SCREEN_DIM_WAKE_LOCK, "My wakelook");
And for how long do you need the display to stay on? Just for some time, or until certain event happen?
Don't release the wakelock when application is ended. You may schedule an event for a period of time you need to keep the screen on. But generally it's a bad practice as holding full wakelock may prevent not only screen but other hardware from going to sleep.
I have a CPU intensive long-running operation (a few hours) that I am using AsyncTask to perform. As it continues, it updates a progressbar on the screen to show what percentage of the task is done.
I discovered that when my screen goes to sleep (time-out) the task seems to stop. Not sure whether this is happing because the AsyncTask stops or it gets stuck at trying to update the screen (latter I am thinking).
Other than never letting the screen sleep, how else can I prevent my AsyncTask to stop executing? And if that is the only way, then how do I make sure that the screen doesn't sleep?
EDIT: I must add that I know this sounds like a non-user-friendly app as commented by someone below. This does a very specialized task (processes thousands of image files to compare processing on different systems) and is to be used by a few users internally, not for public release.
That's expected behavior. The idea is that the phone's battery is not supposed to drain because of bad apps. If the screen is off, the user generally expects the phone to sleep.
If you need your app to run, you can use a WakeLock to keep the phone running (with the screen off): Documentation here and here.
Note that a wake lock requires the WAKE_LOCK permission, and again, you need to make it clear to the user that your app will drink the phone's milkshake while it's off.
Not sure if anyone will read this as the OP is several years old but I am in the same boat in that I need to use a wakelock for an app for internal use, and leaving the screen on was not ok (I just needed the cpu on so I could run some metrics queries) I simply used a partial wakelock; ie:
public class my_frag extends Fragment {
WakeLock wl;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
PowerManager pm = (PowerManager) this.getActivity().getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
//I happen to have it in a button click event based on an async task
//Side note: I should probably be using a Loader for my Async task but this works fine
connectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (metrics_task != null)
{
Status s = metrics_task.getStatus();
if (s.name().equals("RUNNING")){
if (metrics_task.running){
metrics_task.cancel(true);
connectButton.setText("Start");
metrics_task.running = false;
wl.release(); <--releases it on async stop
}
else{
metrics_task = new start_metrics(ae);
metrics_task.execute();
wl.acquire(); <--starts it on async start
}
}
else{
metrics_task = new start_metrics(ae);
metrics_task.execute();
}
}
else{
metrics_task = new start_metrics(ae);
metrics_task.execute();
}
}
});
This worked great with no issues
My 2 cents on this old post, in case it might help someone. If all you want is to prevent your screen from going to sleep, there's a simple solution that does not require a permission from the user - and it's just 2 lines of code:
// prevent the screen from sleeping
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// do your stuff
// don't forget to re-enable the screen time-out so it won't stay awake from now on
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
An important note: it can only be called within an Activity - not from other app components. more details can be found here.