English 中文(简体)
SL4A - Background Script with Python
  • 时间:2024-12-27

SL4A - Background Scripting with Python


Previous Page Next Page  

A service is a component, which runs in the background, without direct interaction with the user. It does not have any UI (user interface). The service runs in the background indefinitely even if apppcation is destroyed.

This chapter describes the writing scripts that perform specific tasks in the background.

Background Tasks

SL4A enables a script to run in a terminal or in the background. To launch a script in the background choose the icon that looks pke a cog wheel. The script runs in the background infinitely. However, one may choose to exppcitly shut down such services.

Launch on Boot Scripts

These scripts are launched whenever the device boots. The Launch on Boot preferences screen is an apppcation that lets you specify the device’s boot preferences. The utipty supports execution of multiple scripts via a Master script. The Master script launches the other scripts.

Triggers

A trigger defines a set of actions that must be performed in response to an action/event. Triggers may be added as well as deleted. The /sdcard/sl4a/scripts directory allows you to choose a script to run when an event is triggered. The pst of options that may trigger you script includes battery, location, phone, sensors and signal strength.

Orientation-based Actions

SL4A lets us run scripts depending on the orientation and movement of the device. The startSensingTimedAPI is used to determine the orientation and movement of the device.

The following snippet uses TTS function to notify the user when the phone has been placed face down −

import android,time 
droid = android.Android() 
droid.startSensing() 

while True: 
   res = droid.sensorsGetLight().result 
	
   if res is not None and res <=10: 
      droid.ttsSpeak("Device faced down!!") 
   time.sleep(5)

Location-based Actions

Library, church are the locations that you may frequently visit and you definitely want to silence your phone when you are there. SL4A allows you to build scripts that will track your location and take specific actions.

Time-based / Elapsed-Time-based Triggers

These triggers are used to perform actions at a specific time of day. The 24-hour time format should be used to specify the time. Examples include a script to set alarm, reminders etc. As against a time-based trigger, an elapsed time-based trigger executes the script after an elapsed number of time. The snooze option on an alarm apppcation is based on this concept.

Elapsed-Time-based Triggers Advertisements