python系列学习——移动开发


1. SDK下载

SDK下载地址

注:该SKD需要预先安装jre(Java Runtime Environment)

2. 配置SDK和模拟器

打开 SDK  Manager,安装所需要的packages:


选择Tools-->Manage AVDs,添加一个新的Android虚拟设备(AVD):


3. 安装配置android脚本环境

打开模拟器设备,点击模拟器的浏览器,导航的下面地址:

https://code.google.com/p/android-scripting/


点击二维码图片,下载SL4A包并安装,安装完成后回到浏览器,选择Downloads标签页,下载安装python_form_andorid_rx.apk. 


安装完成后打开该软件,点击Install,下载解压安装面向Android的Python支持文件(这个过程不要点击屏幕任何地方)。


至此 ,Python2.6.2和Python for android都已安装在模拟器中。

4. 测试Python

编写脚本mydroidtest.py:

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import android  
  2. app = android.Android()  
  3.   
  4. msg = "Hello from head first Python on android"  
  5. app.makeToast(msg)  
要把脚本传送到模拟器,需要把它复制到模拟器的虚拟SD卡中,sdk的platform-tools文件夹下有个adb命令,将platform-tools路径添加到系统环境变量中,然后在终端进入脚本所在目录输入命令:
[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. adb push mydroidtest.py /sdcard/sl4a/scripts  
打开SL4A应用,可以看到mydroidtest.py脚本在列表中,单击脚本名,选择转轮图标即可运行该脚本:


如图,模拟器正常运行所编写的代码。


5.  json模块

json.dumps() encode data with json format

json.loads()  decode json data to orogin data


6. android应用

webapp中的模块athletemodel添加get_names_from_store()方法:

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import cPickle as p  
  2. from athletelist import AthleteList  
  3.   
  4. def get_coach_data(filename):  
  5.     try:  
  6.         with open(filename) as f:  
  7.             data = f.readline().strip().split(',')  
  8.             return AthleteList(data.pop(0), data.pop(0), data)  
  9.     except IOError as err:  
  10.         print 'File error: ' + str(err)  
  11.   
  12. def put_to_store(the_files):  
  13.     athletes = {}  
  14.     for f in the_files:  
  15.         ath = get_coach_data(f)  
  16.         athletes[ath.name] = ath  
  17.   
  18.     try:  
  19.         with open('athletes.pickle''w') as athf:  
  20.             p.dump(athletes, athf)  
  21.         return athletes  
  22.     except IOError as err:  
  23.         print 'File error(put_to_store): ' + str(err)  
  24.         return None  
  25.   
  26. def get_from_store():  
  27.     athletes = {}  
  28.     try:  
  29.         with open('athletes.pickle') as athf:  
  30.             athletes = p.load(athf)  
  31.             return athletes  
  32.     except IOError as err:  
  33.         print 'File error(put_to_store): ' + str(err)  
  34.         return None  
  35.   
  36. def get_names_from_store():  
  37.     athletes = get_from_store()  
  38.     name_list = [athletes[ath].name for ath in athletes]  
  39.     return name_list  

athletelist添加to_dict()方法,将athlete数据转换为字典:

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class AthleteList(list):  
  2.     def __init__(self, a_name, a_dob=None, a_times=[]):  
  3.         list.__init__([])  
  4.         self.name = a_name  
  5.         self.dob = a_dob  
  6.         self.extend(a_times)  
  7.  
  8.     @staticmethod  
  9.     def sanitize(the_time):  
  10.         if '-' in the_time:  
  11.             splitter = '-'  
  12.         elif ':' in the_time:  
  13.             splitter = ':'  
  14.         else:  
  15.             return the_time  
  16.         (mins, secs) = the_time.split(splitter)  
  17.         return mins + '.' + secs  
  18.   
  19.     def top3(self):  
  20.         return sorted(set([self.sanitize(t) for t in self]))[0:3]  
  21.   
  22.     def to_dict(self):  
  23.         return {'name'self.name,  
  24.                 'dob'self.dob,  
  25.                 'top3'self.top3()}  


新建python cgi脚本generate_names.py,获取athlete names的json数据:

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. # coding=utf-8  
  2. import yate  
  3. import athletemodel  
  4. import json  
  5. import cgitb  
  6. cgitb.enable()  
  7.   
  8. names = athletemodel.get_names_from_store()  
  9.   
  10. print yate.start_response('application/json')  
  11. print json.dumps(sorted(names))  
新建python cgi脚本generate_data.py,根据athlete name获取相关数据:
[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. # coding=utf-8  
  2.   
  3. import cgi  
  4. import yate  
  5. import json  
  6. import athletemodel  
  7.   
  8. form_data = cgi.FieldStorage()  
  9. athlete_name = form_data['athlete'].value  
  10.   
  11. athletes = athletemodel.get_from_store()  
  12. print yate.start_response('application/json')  
  13. print json.dumps(athletes[athlete_name].to_dict())  

编写android脚本程序coachapp.py:
[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. # coding=utf-8  
  2.   
  3. import android  
  4. import json  
  5. import time  
  6. from urllib import urlencode  
  7. from urllib2 import urlopen  
  8.   
  9. hello_msg = "Welcomd to Coach Kelly's Timing App"  
  10. list_title = "Here is your list of athletes:"  
  11. quit_msg = "Quitting Coach Kelly's App."  
  12. web_server = "http://192.168.115.1:8080"  
  13. get_name_cgi = "/cgi-bin/generate_names.py"  
  14. get_data_cgi = "/cgi-bin/generate_data.py"  
  15.   
  16. def send_to_server(url, post_data=None):  
  17.     """该函数取一个url和一些可选数据,向web服务器发送一个web请求,web响应返回给调用者"""  
  18.     if post_data:  
  19.         page = urlopen(url, urlencode(post_data))  
  20.     else:  
  21.         page = urlopen(url)  
  22.     return page.read().decode('utf8')  
  23.   
  24. app = android.Android()  
  25. def status_update(msg, how_long=2):  
  26.     """显示简短消息提示"""  
  27.     app.makeToast(msg)  
  28.     time.sleep(how_long)  
  29.   
  30. # 显示欢迎消息  
  31. status_update(hello_msg)  
  32.   
  33. # 将web请求发送给服务器,把json相应转换为一个有序列表  
  34. athlete_names = sorted(json.loads(send_to_server(web_server+get_name_cgi)))  
  35.   
  36. # 创建一个包含两个按钮的对话框  
  37. app.dialogCreateAlert(list_title)  
  38. app.dialogSetSingleChoiceItems(athlete_names)  
  39. app.dialogSetPositiveButtonText('Select')  
  40. app.dialogSetNegativeButtonText('Quit')  
  41. app.dialogShow()  
  42.   
  43. # 等待用户点击一个按钮,把结果赋给resp  
  44. resp = app.dialogGetResponse().result  
  45.   
  46. if resp['which'in ('positive'):  
  47.     selected_index = app.dialogGetSelectedItems().result[0]  
  48.     selected_name = athlete_names[selected_index]  
  49.     athlete = json.loads(send_to_server(web_server+get_data_cgi, {'athlete': selected_name}))  
  50.     athlete_title = athlete['name'] + ' (' + athlete['dob'] + '), top 3 times: '  
  51.     app.dialogCreateAlert(athlete_title)  
  52.     app.dialogSetItems(athlete['top3'])  
  53.     app.dialogSetPositiveButtonText('OK')  
  54.     app.dialogShow()  
  55.     resp = app.dialogGetResponse().result  
  56.   
  57. # 显示退出消息  
  58. status_update(quit_msg)  
程序运行结果:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值