这是一篇发表在kivyspacegame上的文章,讲的是如何使用python在你的安卓设备上访问传感器。这篇教程是为这些用kivy开发python移动apps而写的。Kivy运行速度非常快,并且很容易使用。访问博客以获取更多的关于用Kivy开发游戏的教程。也可以看看google play store上的Helios: Mining Adventure游戏程序。

这篇教程将关注plyer,一个可以读取传感器,发送email,以及将文本转成语音,显示通知等等功能的库。如果你正在用python开发移动运用程序,访问传感器将会是一项很复杂的工作。Plyer大大的将工作简单化。

这篇教程涵盖了安装plyer,构建使用plyerandroid包,并且举了一些显示通知,使手机振动,让android设备对你说话的小例子。

(运行在手机上的运用截图)

I. 背景


Android包含访问传感器的内置API.通过python访问Java类比较复杂,这个过程通过pyjnius得以简化。Pyjnius需要一些额外的跑腿的工作以处理一些特性。对于苹果设备来说,用的是pyobjusPlyer被创造出来是为了简化访问手机传感器的,并且使用的是与平台无关的pythonic的方法。同样的plyer代码可以运行在Windows/Linux/iOS/android

 

II. 安装Plyer


在终端下运行下面的命令:

sudo pip install git+https://github.com/kivy/[email protected]

有一个消息会通知你plyer已经安装成功了。你也要确保带有plyerpython-for-android已经安装成功。要不然,当你在你的手机上运行你的代码时,程序将会因你的软件包里没有plyer库而崩溃。 


III. plyer一起打包


除非你已经在python-for-android中包含了plyer,否则你的软件包里将不会包含plyer,为了解决这个问题,需要将plyer添加到python-for-android

定位到你的python-for-android目录,例如:
cd /home/kivy/android/python-for-android dist/
运行带正确参数的distribute.sh 以包含plyer,以及其它你需要的东东:

./distribute.sh -m plyer pyjnius jpeg png kivy

 

IV. 代码:


首先,导入关键的模块:

import kivykivy.require('1.8.0')from kivy.app import Appfrom kivy.uix.widget import Widgetfrom kivy.uix.label import Labelfrom kivy.core.window import Windowfrom plyer import notification, vibrator, tts, email, accelerometerfrom kivy.clock import Clock

其次,设置图形:

#setup graphicsfrom kivy.config import ConfigConfig.set('graphics','resizable',0)#Graphics fixfrom kivy.core.window import Window;Window.clearcolor = (0,0,0,1.)


对于这个例子,将有一个主类用于与android api连接。它包含了一些函数以实现这个过程。

class GUI(Widget):    #this is the main widget that contains the game    def __init__(self, **kwargs):        super(GUI, self).__init__(**kwargs)        #add a label to advertise the blog        l = Label(text='kivyspacegame.wordpress.com')        l.x = Window.width/2 - l.width/2        l.y = Window.height/2        self.add_widget(l)        #setup accelerometer        try:            #we've already imported the accelerometer from plyer            #it's very easy to access            accelerometer.enable()        except:            #when you run the code on linux, expect this to happen            l.text = 'cant enable acceleromteer'        #setup acceleromter labels        #We create a label to display accelerometer output        self.label = Label(text = 'accelerometer:')        self.label.y = Window.height*0.25        self.label.x = Window.width*0.5        self.add_widget(self.label)        #setup timer to update accelerometer        #we want to regularly read the accelerometer        Clock.schedule_interval(self.check_accel, 1.0/60.0)        #these four functions use other plyer features to talk to the android api        self.notify()        self.vibrate()        self.talk()        self.email()    def check_accel(self,dt):                #update label                try:                    self.txt = str(round(accelerometer.acceleration[0],4)) +','                     + str(round(accelerometer.acceleration[1],4)) + ','                     + str(round(accelerometer.acceleration[2],4))                    self.label.text='accelerometer: ' + self.txt                except:                    #expect this on linux                    self.label.text = ' cant read accelerometer'    def notify(self):        try:            #this notification will pop up on ubuntu as well!'            notification.notify(title="Kivy Notification",message="Plyer Up and Running!",        app_name="kivy_test",app_icon="icon.png",timeout=10)        except:            print 'error notifiying'    def vibrate(self):        try:            #the vibrator will only work on a vibrating device (ie android)            vibrator.vibrate(time=3)        except:            print 'error vibrating'    def talk(self):        try:            tts.speak(message='Resistance is FUTILE. Select an e-mail app.')        except:            print 'cant talk'    def email(self):        try:            email.send(recipient = '[email protected]',subject =            'Thanks!', text ='Enjoyed your lesson')        except:            print 'cant email'

最后的代码:

class ClientApp(App):     def build(self):        #this is where the root widget goes        #should be a canvas        app = GUI()        return app if __name__ == '__main__' :    ClientApp().run()


V. 将应用程序打包


当你的代码已经准备好,并且在linux上运行没问题之后,进入你的发布目录打包运用程序:

cd /home/kivy/android/python-for-android/dist/default

再输入下面的命令,请根据实际情况调整目录。小心不要将不必要的空间给包含进去。这个命令将会在打包成功后将运用程序安装到你的手机上:

./build.py –dir /home/kivy/code/TeachToCode/GuestLessonSensors/ –name “PlyerTest” –package com.molecularflowgames.PlyerTest –version 1.0 –icon /home/kivy/code/TeachToCode/GuestLessonSensors/icon.png –orientation landscape –permission VIBRATE debug installd




这是一个可以在你的运用程序中使用的图标


原文链接:http://bytedebugger.wordpress.com/2014/07/06/guest-post-accessing-android-sensors-with-kivy-via-plyer/

更多相关文章

  1. 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
  2. Android的xml-Rpc实现
  3. 致Android开发者的Kotlin入门
  4. android 下载文件(支持多任务,支持断点.....)
  5. 浅入浅出 Android(安卓)安全:第四章 Android(安卓)框架层安全
  6. Android之socket
  7. Android基于Ffmpeg 的软编软解的可视对讲
  8. Android(安卓)5.0 Camera系统源码分析(1):CameraService启动流程
  9. Android应用程序资源——menu菜单资源

随机推荐

  1. 【Android】使用Git控制Android程序的git
  2. 启动 flutter项目时报Could not find com
  3. Android工具包
  4. Error:Execution failed for task ':app:
  5. Android am/pm命令用法
  6. adb连接不上模拟器的问题
  7. Android自定义View之一:初探实例
  8. Android 后台保活设计2019,最新版本
  9. Android 读取正在运行非系统的程序
  10. 【Android】获取apk的版本及包名等信息