Making an android Python service to run in suspend state

Here's my Python script written using android-scripting:

import android, time

droid = android.Android()
interval = 1 # every 1 minute

while True:
    # define your own vibrate pattern here


It basically vibrates every minute (like a motivator). However, when the phone is locked with screen blanked out, I don't sense any vibration. Perhaps Android is freezing the script (and hence the while loop)? Note that I am indeed running this script as a service (long-tap and click 'Start as service').

Is there a way to make this script work all the time regardless of the phone suspend state?

Update 1: I do hear the vibration occasionally, not every minute .. but rather like every 5-10 minutes randomly.

Update 2: This problems occurs if I run the script normally (not as a service). Seems like "time.sleep" is not sleeping for the specified time.

Asked by: Stella342 | Posted: 24-01-2022

Answer 1

The scripting environment is definitely a second-class citizen. What you want is called the AlarmManager, using ELAPSED_REALTIME. If that's not available for the scripting environment, you're stuck.

The scripting environment is not, at least currently, intended to be a full replacement for the development kit environment, where you can create full applications. It's meant to allow you to do some simple scripting tasks, at the cost of not being able to do more complicated things. Sorry.

Answered by: Miller635 | Posted: 25-02-2022

Answer 2

I am facing the same kind of problem.

time.sleep() is not reliable when your android device is in "locked" mode:

Here are a few things I've tried on SL4A release4 + pythonForAndroid_r5 + android 2.3.3 on samsung galaxy S

  • wrap a time.sleep(interval) loop inside droid.wakeLockAcquirePartial() and droid.wakeLockRelease(). This will prevent the CPU from slowing down.
  • use an eventWaitFor(eventName, timeOutInMilliSeconds) call:

droid.eventWaitFor("ThisEventCannotHappen", interval*60000)

  • threading.Timer() object seems also to work as expected, after a few tests on my device (confirmation needed...)

I'm not sure, but you'd better keep in mind that these tricks might drain more power than expected in true "locked/sleeping" mode and therefore reduce the runtime of your device.

Update: eventWaitFor() is not reliable either for long intervals. Here is a snippet showing how Timer() works:

import android
import threading
import logging

def doStuff():" Stuff DONE")
    droid.notify('',"doStuff() has been called")

def createLog(path):
                        format='%(asctime)s %(message)s')


timer=threading.Timer(DELAY,doStuff)"timer starting now")
timer.start()"doStuff() will be called by timer...Delay=%d" % DELAY)

Answered by: Ned402 | Posted: 25-02-2022

Answer 3

It's unlikely that this will work in ASE without support for the AlertManager. Your best bet is to file a feature request and wait for that. Or, if you're feeling ambitious, extend ASE yourself and submit a patch!

Answered by: Elise570 | Posted: 25-02-2022

Answer 4

I don't know much about Python binding, so I am going to answer as general Android issue. See Power Management.

PARTIAL_WAKE_LOCK sounds interesting: "Wake lock that ensures that the CPU is running. The screen might not be on."

Exploring a Wake Lock Example

All power management calls follow the same basic format:

  1. Acquire handle to the PowerManager service.
  2. Create a wake lock and specify the power management flags for screen, timeout, etc.
  3. Acquire wake lock.
  4. Perform operation (play MP3, open HTML page, etc.).
  5. Release wake lock. The snippet below illustrates this process.
PowerManager pm = (PowerManager)mContext.getSystemService(
PowerManager.WakeLock wl = pm.newWakeLock(
                                      | PowerManager.ON_AFTER_RELEASE,
 // ...

Answered by: Tara580 | Posted: 25-02-2022

Answer 5

Possible solution: use some scheduler software and start your script regularly. This way you'll not need to call time.sleep().

Maybe scripting is not a best solution for such periodic tasks. You will not face this problem if you write a simple Java app.

Answered by: Arnold831 | Posted: 25-02-2022

Similar questions

java - Not able to check Android Service Issue

All I want to do is simply control background music in my app through a service so I am able to start it and stop it from any activity. I have everything set up perfectly when I tell the service to Toast when it is started and destroyed but as soon as I put the media play-in in there instead It starts fine and starts playing the music but as soon as a click a button to stop the service I get an error and a force cl...

Android - Can I send an intent on Wifi state change to a service?

I want to send an intent to my service everytime the state of Wifi connectivity changes. So when I currently use a broadcast receiver to listen for the state changes in Wifi, so when this recieves an intent I want to be able to send this info on to my service. Is this possible and if so the correct way to do it?

android - Can't bind to Service

I have an aidl file defined as follows: package com.erbedo.callalert; interface RemoteCallAlert { void notifyCallEnded(); } The service is: package com.erbedo.callalert; public class CallAlert extends Service { Filter callListener; private final RemoteCallAlert.Stub mBinder = new RemoteCallAlert.Stub() { @Override public void notifyCallEnded(...

android - using IPC under Service

Please can anyone tell me what is, and when would it be good to use "IPC" ? thanks, ray.

android - Delete service from the phone

Closed. This question does not meet Stack Overflow guid...

android - how to use Remote Service?

im trying to use Remote Service btween two simple application, But its not easy to me. So any advice you have will help me. here`s my case. I made one app which is playing Music in service, There are two components. one is Activity controlling service by using three buttons, play,pause, stop. and it is working fine. and another one is just simple Activity which also has four bu...

android - How do I start a service which is defined in a different package?

I have two apps, one runs in namespace com.gtosoft.voyager and the other is com.gtosoft.dash. From com.gtosoft.dash I would like to start up the service which is defined in com.gtosoft.voyager... I think I need an intent, but what arg(s) would I pass to the intent before kicking it off with startService()? If they were in the same package I could just use Intent svc=new Intent (SettingsAct...

android - Reg: Remote Service

Can any one provide sample Remote service example. I want it like two different application. One application should contain service. Another application should use that service. Thanks in adv....

url - Android - When to use Service

This question is related to my previous question: Android Service - Ping URL So I have an Android app that on the click of a button, opens up a web page. Now, in the background I want to call another http url for gathering stats. My question is does this have to be a service? I know a service is for background tasks that run...

Android remote service doesn't call service methods

I'm developing a GPS tracking software on android. I need IPC to control the service from different activities. So I decide to develop a remote service with AIDL. This wasn't a big problem but now it's always running into the methods of the interface and not into those of my service class. Maybe someone could help me? Here my AIDL file: package interface ITrackingServiceRemot...

android - digital compass problem

I am creating an augmented reality application and I noticed that the stored locations don't appear appear on the correct direction if I try to use the camera view (using layar or wikitude API). The problem is that the digital compass doesn't show north correctly when you try to look at the known objects through the camera view. If align the phone with the ground (look at my shoes) the locations appear at the screen accord...

android - How to remove labels from a MapView?

I am trying to make a satellite view (via a MapView) without labels. How can I do this?

android - Custom title with image

i'm creating custom title for activity by disabling standard one and managing everything myself. I wonder if it's possible to replace/theme standart title to my needs. I can customize size, background image, and text via themes by changing windowXYZStyle items. The only thing i couldn't find - how i can add image instead of text. I've tried requestWindowFeature(Window.FEATURE_CUSTOM_TITLE) and ...

canvas - Android draw with blur

I need do draw on Android's Canvas using Blur effect, it is a very simple feature, I need to draw a circular area, which is blurred (the foreground) and the background transparent, I can do everything with manipulating the colour alpha to do it with custom transparency but I need it to be blurred instead of transparent.. any ideas?

layout - How to resize a android webview after adding data in it

In a layout (linear, vertical) hierarchy I've got several views and one of them is a WebView. They all have same parameters: android:layout_width="fill_parent" android:layout_height="wrap_content" For all views, the spacing between elements is correctly handled but for the Webview there is a lot of spaces after the displayed text inside. I set the (HTML) text of the webview in the ...

How to find easily the source of an android class

I know I can access android source code from, but it's hard to select the right git repo if I only know the package and the name of an android class. Isn't there a way to locate a file in

camera - Android Intent Save Path

At the moment I am using two intents. One for voice-recording, another for the camera: Intent photoIntent = new Intent(""); startActivityForResult(photoIntent, ACTIVITY_TAKE_PHOTO); Intent voiceIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION); startActivityForResult(voiceIntent, ACTIVITY_RECORD_SOUND); My aim is to put an Extra to each of t...

Android "hover" event in custom layout

I have a custom layout that I have written that basically just displays a bunch of ImageViews. I am handing onTouch events for all the ImageViews in my layout. However, if a user touches one imageView and then drags over another ImageView, I would like to be able to handle that as well. How would I go about capturing this behaviour?

android - What is the ideal place to cache images?

I am fetching a lot of thumbnails in my application from a remote server and lazy-loading these in a list view. The image fetches run in a background AsynTask and when completed the fetched images are stored in a HashMap using SoftReferences. This works just fine but when the images in the cache gets GC’d, the fetches have to be rerun. I could have stored them on the SD card so there would be no...

How to create a tree view in Android?

There are no controls in Android that provide Tree-like View. There is an ExpandableList View which I suspect could be used to creating one. Have you tried imlpementing such a control? How would one implement such a control in Android?

Still can't find your answer? Check out these communities...

Android Google Support | Android Community | Android Community (Facebook) | Android