本文整理汇总了Python中android.AndroidService.stop方法的典型用法代码示例。如果您正苦于以下问题:Python AndroidService.stop方法的具体用法?Python AndroidService.stop怎么用?Python AndroidService.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类android.AndroidService
的用法示例。
在下文中一共展示了AndroidService.stop方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RemoteKivyApp
# 需要导入模块: from android import AndroidService [as 别名]
# 或者: from android.AndroidService import stop [as 别名]
class RemoteKivyApp(App):
def build(self):
global app
app = self
self.service = AndroidService('Kivy Remote Shell',
'remote shell is running')
self.service.start('8000')
return MainScreen()
def quit_app(self):
self.service.stop()
self.stop()
示例2: FlashApp
# 需要导入模块: from android import AndroidService [as 别名]
# 或者: from android.AndroidService import stop [as 别名]
class FlashApp(App):
def build(self):
self.root = Switch()
self.service = AndroidService('Kivy FlashLight', 'I haz a FlashLight!')
self.root.bind(active=self.toggle_flash)
return self.root
def toggle_flash(self, *args):
if self.root.active:
self.service.start()
else:
self.service.stop()
示例3: DjandroApp
# 需要导入模块: from android import AndroidService [as 别名]
# 或者: from android.AndroidService import stop [as 别名]
class DjandroApp(App):
def build(self):
self.service = AndroidService('Django', 'Django is running')
open(LOGPATH, 'w').close() # Touch the logfile
self.running = False
self.logging = False
def toggle(self):
action = self.stop if self.running else self.start
self.running = not self.running
action()
self.root.ids['info'].text = "[color=#ff0000]Django is OFF[/color]"
if self.running:
self.root.ids['info'].text = "[color=#00ff00]Django is ON[/color]"
btn_text = 'Stop' if self.running else 'Start'
self.root.ids['btn'].text = btn_text + " Django"
def start(self):
self.service.start(LOGPATH)
self.start_logging()
def stop(self):
self.service.stop()
self.logging = False
self.running = False
def start_logging(self):
self.console = Thread(target=self.logger)
self.logging = True
self.console.start()
def logger(self):
label = self.root.ids['console']
log = open(LOGPATH, 'r')
label.text = log.read()
while self.logging:
log.seek(log.tell())
label.text += log.read()
sleep(0.2)
def on_pause(self):
if self.logging:
self.logging = False
self.console.join()
return True
def on_resume(self):
if self.running:
self.start_logging()
示例4: ServiceExample
# 需要导入模块: from android import AndroidService [as 别名]
# 或者: from android.AndroidService import stop [as 别名]
class ServiceExample(App):
def start_service(self):
# Make a thing to test passing vars to the service
appdict = {"string": "Hello!",
"int": 1,
"list": [1,2,3,4,5]}
# Makin' that service
self.service = AndroidService('Sevice example', 'service is running')
# This just starts the service. I shouldn't need a comment here.
self.service.start(dumpd)
def stop_service(self):
self.service.stop()
示例5: BestVibratorAppServiceController
# 需要导入模块: from android import AndroidService [as 别名]
# 或者: from android.AndroidService import stop [as 别名]
class BestVibratorAppServiceController(object):
def __init__(self, **kwargs):
super(BestVibratorAppServiceController, self).__init__(**kwargs)
self.SERVICE_ACTIVE=False
if platform=="android":
from android import AndroidService
self.service=AndroidService("Best Vibrator Service", "running")
self.service.start("Best Vibrator Service started")
self.SERVICE_ACTIVE=True
osc.init()
def service_stop(self):
self.service.stop()
self.SERVICE_ACTIVE=False
示例6: ServiceTestApp
# 需要导入模块: from android import AndroidService [as 别名]
# 或者: from android.AndroidService import stop [as 别名]
class ServiceTestApp(App):
def start_service(self):
self.service = AndroidService('Sevice example', 'service is running')
self.service.start('Hello From Service')
def stop_service(self):
self.service.stop()
def on_start(self, *l):
Logger.info('start')
self.start_service()
pass
def on_stop(self, *l):
Logger.info('stop')
self.stop_service()
def on_pause(self):
return True
def on_resume(self):
pass
示例7: PhotoRiverApp
# 需要导入模块: from android import AndroidService [as 别名]
# 或者: from android.AndroidService import stop [as 别名]
class PhotoRiverApp(App):
flashair_uri = ""
folder = ""
album_name = ""
def on_start(self):
self.service = AndroidService()
def start_service(self):
service_args = dict(
flashair_uri=self.flashair_uri,
folder=self.folder,
album_name=self.album_name,
)
self.service.start(json.dumps(service_args))
def stop_service(self):
self.service.stop()
def on_pause(self):
return True
def on_resume(self):
return True
示例8: Service
# 需要导入模块: from android import AndroidService [as 别名]
# 或者: from android.AndroidService import stop [as 别名]
class Service():
#Configuracoes do ThreadComm
CONFIG_THREADCOMMPORT = 51352
CONFIG_THREADCOMMID = "sigmawebplus"
#Variaveis
_state = STATE_NOTSTARTED
_formerState = STATE_NOTSTARTED
_forceThread = None
_androidTrigger = False #Hack: O service do Android soh pode ser aberto pelo main thread. Uso essa flag para avisar o main thread a hora de abrir
_androidTriggerEnd = False
_androidService = None #Guarda do ponteiro do Android Service, para poder fechar depois
_lastDisconnection = 0 #Essa variavel serve para ter um timeout de 5 segundos entre cada reconexao
#Objetos
_threadComm = None #Ponteiro para o objeto do ThreadComm (utilizado para se comunicar com o service)
_data = None #Objeto 'Dict' utilizado para armazenar todos as propriedade que estão sinronizadas com o service
'''
Salva os dados recebido como parametro e inicializa o servico de forma assincrona
Nota: Se o service já existir, os dados serão sobreescritos em favor dos dados do service
'''
def start(self, data, forceThread=False):
if (self.getState() == STATE_NOTSTARTED):
Debug().note('service.start(): Iniciando server')
self._setState(STATE_CONNECTING)
self._data = data #Salva dados no objeto
self._forceThread = forceThread
thread = Thread(target=self._start, name='service._start()') #Faz a inicializacao do Service em outro thread
thread.daemon = False
thread.start()
else:
Debug().note('service.start(): Reiniciando server')
thread = Thread(target=self._restart, name='service._restart()', args=(data, forceThread))
thread.daemon = False
thread.start()
'''
Manda um aviso para o service se finalizar e espera a resposta do service!
ATENCAO: Essa funcao eh bloqueante. Ela trava o andamento do programa ateh receber o sinal do service!
'''
def stop(self, killService=True):
while (self.getState() == STATE_CONNECTING): sleep(0.1) #Espera o ThreadComm conectar, caso ele esteja no modo 'Conectando'
if self.isAlive():
self._setState(STATE_DISCONNECTING)
self._stop(killService)
else:
Debug().warn('service.stop(): Service nao esta rodando. Nada para parar! CurrentState: '+str(self.getState()))
'''
Retorna True se o service esta conectado e pronto para funcionar
'''
def isAlive(self):
if (self.getState() == STATE_CONNECTEDTHREAD) or (self.getState() == STATE_CONNECTEDANDROID) or (self.getState() == STATE_CONNECTEDREMOTE):
return True
else: return False
'''
Retorna o estado que o objeto se encontra. Uma lista de estados pode ser vista no inicio desse arquivo
'''
def getState(self):
return self._state
def getFormerState(self):
return self._formerState
'''
Retorna o valor da chave solicitada
'''
def getKey(self, key):
try: return str(self._data[key])
except: return ''
'''
Seta o valor da chave e avisa o service desta mudanca
'''
def setKey(self, key, value):
self._data[key] = str(value)
if self.isAlive(): self._sendKey(key)
'''
Este metodo faz o objeto buscar se há novas mensagens no ThreadComm
Retorna uma lista com as keys e valores de todas os dados modificados [[key1, value1], [key2, value2], ...]
Nota: Ele não vai retornar a key se o valor recebido for igual o valor já presente!
Nota2: Ele tambem é responsavel pelo main loop do service (ele responde outros tipos de mensagens)
Nota3: A logica do loop foi movida para a funcao _parseMessage() para melhorar a leitura
'''
def getKeys(self):
self._startAndroid() #Hack: O service do Android soh pode ser aberto pelo main thread. Uso essa funcao para o main thread verificar se deve abrir ou nao
if not self.isAlive(): return None #Verifica se o servidor esta conctado
returnData = []
while True:
#Busca novas mensagens no ThreadCom
try: message = self._threadComm.recvMsg()
except: break
#Faz o parse da mensagem recebida e, se o valor retornado não for nulo, adiciona na returnData
data = self._parseMessage(message)
#.........这里部分代码省略.........
示例9: SettingsFrame
# 需要导入模块: from android import AndroidService [as 别名]
# 或者: from android.AndroidService import stop [as 别名]
class SettingsFrame(StackLayout):
"""Settingsframe is the main frame of the application"""
cfg_file = None
"""The config file to use"""
service_status = None
"""The status of the service"""
service_progress = None
"""The progress of the current job"""
def init(self, _cfg_file=None):
self.ids.destination_host.ids.input_selection.bind(text=self._update_host)
self.ids.destination_path.on_status = self.do_on_smbselector_status
self.load_settings(_cfg_file)
self.service = None
osc.init()
self.oscid = osc.listen(port=3002)
osc.bind(self.oscid, self.progress_callback, "/progress_callback")
osc.bind(self.oscid, self.status_callback, "/status_callback")
# Check if service is running
self.service_running = False
osc.sendMsg("/status", [], port=3000)
osc.sendMsg("/progress", [], port=3000)
sleep(0.3)
osc.readQueue(self.oscid)
Clock.schedule_interval(self.process_messages, 1)
####### Service #################
#######################################################################################
def do_on_smbselector_status(self, _message):
"""
:param _message: A string message
"""
self.ids.l_test_smbselector_result.text = re.sub("(.{40})", "\\1\n", _message, 0, re.DOTALL)
def process_messages(self, *args):
"""Receive messages"""
osc.readQueue(self.oscid)
def status_callback(self, *args):
"""If the client receives a status message, reflect that in the label_status widget
:param args: Message arguments.
"""
self.service_running = True
self.service_status = str(args[0][2])
self.ids.label_status.text = self.service_status
def progress_callback(self, *args):
"""If the client receives a progress message, reflect that in the label_progress widget
:param args: Message arguments.
"""
self.service_running = True
self.service_progress = str(args[0][2])
self.ids.label_progress.text = re.sub("(.{40})", "\\1\n", self.service_progress, 0, re.DOTALL)
def start_service(self):
"""Start the service"""
self.save_settings()
print("Starting service")
self.service_running = False
osc.sendMsg("/status", [], port=3000)
osc.sendMsg("/progress", [], port=3000)
sleep(0.1)
osc.readQueue(self.oscid)
if not self.service_status:
# Wait a little longer and try again
sleep(0.5)
osc.readQueue(self.oscid)
if not self.service_status:
print("Start_service: Service is not running, starting")
if self.service is None:
if platform == "android":
from android import AndroidService
self.service = AndroidService("Optimal file sync service", "running")
self.service.start("service started")
else:
# Start process on linux.
print("Running on !android initializing service using Popen.")
self.service = subprocess.Popen(args = ["python", "./service/main.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
print("Start_service: Service is already running, not starting.")
def stop_service(self):
"""Stop the service"""
print("Asking service to stop.")
self.service_running = False
osc.sendMsg("/status", [], port=3000)
sleep(0.2)
osc.readQueue(self.oscid)
osc.sendMsg("/stop", [], port=3000)
sleep(0.2)
osc.readQueue(self.oscid)
#.........这里部分代码省略.........