0

I'm running Python on Android using SL4A. I have a script to calculate an average that looks like this:

import android
droid = android.Android()
var1 = 10
var2 = 20
var3 = 30
average = float((var1+var2+var3)/3)
droid.makeToast('Average:'+str(average))
f=open('/data/data/com.example.devicecommunication/files/result.txt','w')
f.write(str(average))
f.close()

My requirement is to add a method to droid named stop, so I can define my own logic there. Is this possible?

Carl Smith
  • 3,025
  • 24
  • 36
user1741274
  • 759
  • 3
  • 13
  • 25

2 Answers2

1

You can define classes and methods with Python in sl4a, like this:

class MyDroid():
  def stop(self):
    return "I stopped"

Is this what you're looking for?

You have a LOT of examples (Tutorials, API reference, overview) on the Wiki page of SL4A : HERE.

You can define a global variable, which you use to run your program in a loop, and when the condition is not met anymore, you call stop which takes you out of the loop and ends the program.

Something like will work:

runScript = True

def stop():
  global runSCript
  runScript = False

while runScript:
  --do actions
  if --condition-- :
    stop()

I don't think this is best practice for Python, but it works..

Radu Gheorghiu
  • 20,049
  • 16
  • 72
  • 107
  • You can do a `do while` loop and when calling `stop`, the condition in the while is no longer true and so the program jumps out of the while and ends. – Radu Gheorghiu Jun 26 '13 at 11:33
0

You can bind anything you like to the droid object...

droid.stop = lambda: 1
print(droid.stop()) # prints 1

It's not clear what you'd like to do though. The script you posted has no obvious use for a stop method. You can do something like the following, but I'm not sure why you would:

def stop():
    import sys
    sys.exit()

droid.stop = stop

You need to explain the problem you're trying to solve in more detail.

Carl Smith
  • 3,025
  • 24
  • 36