加载中…
个人资料
SunGis
SunGis
  • 博客等级:
  • 博客积分:0
  • 博客访问:5,179
  • 关注人气:27
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

android 手机 usb连电脑 python 远程调试脚本 生成界面

(2012-12-24 09:41:34)
标签:

杂谈

分类: python/GAE/android[转]
android手机以usb 连接电脑,安装驱动试 adb devices 可以查看到手机已连接
启动SL4A server ,查看监听端口
设置端口转发
adb forward tcp:9999 tcp:57912
--------------
启动python  IDLE
import android
droid = android.Android(('127.0.0.1','9999'))
droid.makeToast("Hello from my computer!")
droid.webViewShow('http://weibo.com')

FullScreenUI  
Full Screen User Interface.
Updated Apr 30, 2012 by rjmatthews62

Introduction

The full screen interface is a new, experimental feature that allows you to define and display a Layout, and respond to button clicks and other key events. This feature is available with the r5 release.

Update: If you are using FullScreenUI extensively, you may wish to upgrade to the latest development branch release r5x which will incorporate a series of issue fixes on layout properties till the next stable release. For the latest list of fixes, issues & work-arounds - seeFullScreenUI_Layout_Property_Issues. For info on r5x, see Unofficial.

Details

Basically, you take a screen layout as built by the android layout designer, and call droid.fullShow

This will display the screen. Button clicks and keypresses (include the BACK and Volume keys) will be returned as events "click" and "key" respectively.

You can query the settings for a given controil using fullQueryDetail, or list all controls using fullQuery.

fullSetProperty will let you set properties. fullDismiss will close the screen down.

Because I had to write my own parsing routines for the view (Android heavily preprocesses existing layouts in the compiler) I don't promise to support every possible property, but extensive use of reflection means it will give most things a serious shot.

Layouts

See http://developer.android.com/guide/topics/ui/index.html for general information on Layouts. The Android ADT includes a Layout editor, which I have used for my examples.

Querying the controls

One you've show the screen using "fullShow", you can query the current state of the controls, provided they have an id defined.


  fullQueryDetail(id)

Properties returned are:

id, type, text, visibility, checked and tag.

More can be included on request.

In the sample code below, the line:


  droid.fullQueryDetail("editText1").result

should return:


  {u'id': u'editText1', 
   u
'text': u'123456789', 
   u
'tag': u'Tag Me', 
   u
'type': u'EditText',
   u
'visibility': u'0'}

Setting Properties

You can use the fullSetProperty command to set properties of your controls, ie:


  droid.fullSetProperty("textView1","text","Other stuff here")

Properities definitely available include "text", "visible" and "checked", but you should be able to set most simple properties. A property in this case is defined as any method the control has that starts with a "set". As an example (taken from example code below):


  droid.fullSetProperty("background","backgroundColor","0xff7f0000")

If you look at http://developer.android.com/reference/android/view/View.html#setBackgroundColor(int), you should see the relationship. Note that case is important.

You should be able to set most simple properties that way.

When defining a property, the layout inflater will recognize standard resources, ie:


  print droid.fullSetProperty("imageView1","src","@android:drawable/star_big_off")

Note that you can only use resources already compiled into sl4a or the standard android package. In theory you could use resources from other packages, but I haven't tried it. Full form of resource property is


@[package:]type/name

If you don't include a package id, it will default to the current package, typically sl4a. If you use the standalone template you should be able to include your own resources in there.

Images

Images can be included in the layout using "ImageView" controls. The property to set to display the image is "src". This can either be a resource from somewhere, or a file url. ie:


droid.fullSetProperty("imageView1","src","@android:drawable/star_big_off")
droid
.fullSetProperty("imageView1","src","file:///sdcard/download/panda72.png")

Colors

When setting colors, you have to define them as either #aarrggbb or 0xaarrggbb. The aa (alpha) is important. For solid colors, this should be set to ff. Ie, black=#ff000000, red=#ffff0000.

As of r5x09, colors should also recognizes #rrggbb, #rgb and #argb ans behave sensibly. Also, as a convenience, all the standard html color names are recognized. See: http://www.w3schools.com/html/html_colornames.asp . Color names are case insensitve.

Background

The background property can take either a color, a resource, or a bitmap file as a value.


droid.fullSetProperty("button1","background","file:///sdcard/download/panda72.png")
droid
.fullSetProperty("button1","background","@android:drawable/star_big_off")
droid
.fullSetProperty("button1","background","#ff00ff00")

Lists

You can associate a list of items with a Spinner or a ListView using fullSetList.


droid.fullSetList("listview1",["One","Two","Three"])
droid
.fullSetList("spinner1",["Red","Green","Blue"])

ListViews will throw an "itemclick" event when an item is selected. Spinners don't yet throw a "click" event, but the selected item will be returned in !selectedPosition.

Responding to Events

Any control that supports the clickable interface will generate a "click" event when tapped. The basic properties of the control will be returned in data.

A button (including Back, Search and the volume controls) will generate a "key" event. The data will contain a map with the keycode (as defined here: http://developer.android.com/reference/android/view/KeyEvent.html.

Some useful keycodes: BACK=4, Search=84, volume up=24, volume down=25, and menu=82. Arrow keys/trackball: up=19, left=20, right=21 and down=22

Some keys (ie, the volume keys) have a default behaviour, such as changing the ringtone volume. You can override this behaviour by callingfullKeyOverride with a list of the keycodes you wish to override.


  droid.fullKeyOverride([24,25],True)

Options Menu

If you have an options menu defined (using addOptionsMenuItem it will be available in the full screen.

Debugging

fullDisplay and fullSetProperty both return messages detailing any errors with the layout or properies, including any unrecognized properties. If asking for more features, please include sample code and these debugging responses.

Example Code


import android
droid
=android.Android()

def eventloop():
  
while True:
    
event=droid.eventWait().result
    
print event
    
if event["name"]=="click":
      id
=event["data"]["id"]
      
if id=="button3":
        
return
      
elif id=="button2":
        droid
.fullSetProperty("editText1","text","OK has been pressed")
      
elif id=="button1":
        droid
.fullSetProperty("textView1","text","Other stuff here")
        
print droid.fullSetProperty("background","backgroundColor","0xff7f0000")
    
elif event["name"]=="screen":
      
if event["data"]=="destroy":
        
return

print "Started"
layout
="""<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
        android
:id="@+id/background"
        android
:orientation="vertical" android:layout_width="match_parent"
        android
:layout_height="match_parent" android:background="#ff000000">
        
<LinearLayout android:layout_width="match_parent"
                android
:layout_height="wrap_content" android:id="@+id/linearLayout1">
                
<Button android:id="@+id/button1" android:layout_width="wrap_content"
                        android
:layout_height="wrap_content" android:text="Test 1"></Button>
                
<Button android:id="@+id/button2" android:layout_width="wrap_content"
                        android
:layout_height="wrap_content" android:text="Ok"></Button>
                
<Button android:id="@+id/button3" android:layout_width="wrap_content"
                        android
:layout_height="wrap_content" android:text="Cancel"></Button>
        
</LinearLayout>
        <TextView android:layout_width="match_parent"
                android:layout_height="wrap_content" android:text="TextView"
                android:id="@+id/
textView1" android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center_vertical|center_horizontal|center"></TextView>
        <EditText android:layout_width="
match_parent"
                android:layout_height="
wrap_content" android:id="@+id/editText1"
                android:tag="
Tag Me" android:inputType="textCapWords|textPhonetic|number">
                <requestFocus></requestFocus>
        </EditText>
        <CheckBox android:layout_height="
wrap_content" android:id="@+id/checkBox1" android:layout_width="234dp" android:text="Howdy,neighbors." android:checked="true"></CheckBox>
</LinearLayout>
"""

print layout
print droid.fullShow(layout)
eventloop
()
print droid.fullQuery()
print "Data entered =",droid.fullQueryDetail("editText1").result
droid
.fullDismiss()

Mini FAQ

Why is my screen transparent? You need to define a background color for your root layout, including the alpha. ie,


android:background="#ff000000"

(Actually, as of 5x13, the color values do not require an explicit alpha value)

TODO

  • A function to query ALL properties, not just the basic ones.
  • Including an options menu (and perhaps context menus?)
  • Ability to override standard actions on keypress.

SL4A API Help -UiFacade

index
User Interface Facade. 

Usage Notes

The UI facade provides access to a selection of dialog boxes for general user interaction, and also hosts the webViewShow call which allows interactive use of html pages.
The general use of the dialog functions is as follows:
  1. Create a dialog using one of the following calls:
  2. Set additional features to your dialog
  3. Display the dialog using dialogShow
  4. Update dialog information if needed
  5. Get the results
    • Using dialogGetResponse, which will wait until the user performs an action to close the dialog box, or
    • Use eventPoll to wait for a "dialog" event.
    • You can find out which list items were selected using dialogGetSelectedItems, which returns an array of numeric indices to your list. For a single choice list, there will only ever be one of these.
  6. Once done, use dialogDismiss to remove the dialog.

You can also manipulate menu options. The menu options are available for both dialogShow and fullShow.
Some notes:
Not every dialogSet function is relevant to every dialog type, ie, dialogSetMaxProgress obviously only applies to dialogs created with a progress bar. Also, an Alert Dialog may have a message or items, not both. If you set both, items will take priority.
In addition to the above functions, dialogGetInput and dialogGetPassword are convenience functions that create, display and return the relevant dialogs in one call.
There is only ever one instance of a dialog. Any dialogCreate call will cause the existing dialog to be destroyed. 
@author MeanEYE.rcf (meaneye.rcf@gmail.com)
addContextMenuItem Adds a new item to context menu. 
label (String) label for this menu item 
event (String) event that will be generated on menu item click 
eventData (Object) (optional) 
Context menus are used primarily with webViewShow
addOptionsMenuItem Adds a new item to options menu. 
label (String) label for this menu item 
event (String) event that will be generated on menu item click 
eventData (Object) (optional) 
iconName (String) Android system menu icon, see http://developer.android.com/reference/android/R.drawable.html (optional)
Example (python)
 import android
 droid=android.Android()
 
 droid.addOptionsMenuItem("Silly","silly",None,"star_on")
 droid.addOptionsMenuItem("Sensible","sensible","I bet.","star_off")
 droid.addOptionsMenuItem("Off","off",None,"ic_menu_revert")
 
 print "Hit menu to see extra options."
 print "Will timeout in 10 seconds if you hit nothing."
 
 while True: # Wait for events from the menu.
   response=droid.eventWait(10000).result
   if response==None:
     break
   print response
   if response["name"]=="off":
     break
 print "And done."
 
 
clearContextMenu Removes all items previously added to context menu.
clearOptionsMenu Removes all items previously added to options menu.
dialogCreateAlert Create alert dialog. 
title (String) (optional) 
message (String) (optional) 
Example (python)
   import android
   droid=android.Android()
   droid.dialogCreateAlert("I like swords.","Do you like swords?")
   droid.dialogSetPositiveButtonText("Yes")
   droid.dialogSetNegativeButtonText("No")
   droid.dialogShow()
   response=droid.dialogGetResponse().result
   droid.dialogDismiss()
   if response.has_key("which"):
     result=response["which"]
     if result=="positive":
       print "Yay! I like swords too!"
     elif result=="negative":
       print "Oh. How sad."
   elif response.has_key("canceled"): # Yes, I know it's mispelled.
     print "You can't even make up your mind?"
   else:
     print "Unknown response=",response
 
   print "Done"
 
dialogCreateDatePicker Create date picker dialog. 
year (Integer) (default=1970) 
month (Integer) (default=1) 
day (Integer) (default=1)
dialogCreateHorizontalProgress Create a horizontal progress dialog. 
title (String) (optional) 
message (String) (optional) 
maximum progress (Integer) (default=100)
dialogCreateInput Create a text input dialog. 
title (String) title of the input box (default=Value) 
message (String) message to display above the input box (default=Please enter value:) 
defaultText (String) text to insert into the input box (optional) 
inputType (String) type of input data, ie number or text (optional) 
For inputType, see InputTypes. Some useful ones are text, number, and textUri. Multiple flags can be supplied, seperated by "|", ie: "textUri|textAutoComplete"
dialogCreatePassword Create a password input dialog. 
title (String) title of the input box (default=Password) 
message (String) message to display above the input box (default=Please enter password:)
dialogCreateSeekBar Create seek bar dialog. 
starting value (Integer) (default=50) 
maximum value (Integer) (default=100) 
title (String) 
message (String) 
Will produce "dialog" events on change, containing:
  • "progress" - Position chosen, between 0 and max
  • "which" = "seekbar"
  • "fromuser" = true/false change is from user input
Response will contain a "progress" element.
dialogCreateSpinnerProgress Create a spinner progress dialog. 
title (String) (optional) 
message (String) (optional) 
maximum progress (Integer) (default=100)
dialogCreateTimePicker Create time picker dialog. 
hour (Integer) (default=0) 
minute (Integer) (default=0) 
is24hour (Boolean) Use 24 hour clock (default=false)
dialogDismiss Dismiss dialog.
dialogGetInput Queries the user for a text input. 
title (String) title of the input box (default=Value) 
message (String) message to display above the input box (default=Please enter value:) 
defaultText (String) text to insert into the input box (optional) 
The result is the user's input, or None (null) if cancel was hit. 
Example (python)
 import android
 droid=android.Android()
 
 print droid.dialogGetInput("Title","Message","Default").result
 
dialogGetPassword Queries the user for a password. 
title (String) title of the password box (default=Password) 
message (String) message to display above the input box (default=Please enter password:)
dialogGetResponse Returns dialog response.
dialogGetSelectedItems This method provides list of items user selected. 
returns: (Set) Selected items
dialogSetCurrentProgress Set progress dialog current value. 
current (Integer)
dialogSetItems Set alert dialog list items. 
items (JSONArray) 
This effectively creates list of options. Clicking on an item will immediately return an "item" element, which is the index of the selected item.
dialogSetMaxProgress Set progress dialog maximum value. 
max (Integer)
dialogSetMultiChoiceItems Set dialog multiple choice items and selection. 
items (JSONArray) 
selected (JSONArray) list of selected items (optional) 
This creates a list of check boxes. You can select multiple items out of the list. A response will not be returned until the dialog is closed, either with the Cancel key or a button (positive/negative/neutral). Use dialogGetSelectedItems() to find out what was selected.
dialogSetNegativeButtonText Set alert dialog button text. 
text (String)
dialogSetNeutralButtonText Set alert dialog button text. 
text (String)
dialogSetPositiveButtonText Set alert dialog positive button text. 
text (String)
dialogSetSingleChoiceItems Set dialog single choice items and selected item. 
items (JSONArray) 
selected (Integer) selected item index (default=0) 
This creates a list of radio buttons. You can select one item out of the list. A response will not be returned until the dialog is closed, either with the Cancel key or a button (positive/negative/neutral). Use dialogGetSelectedItems() to find out what was selected.
dialogShow Show dialog.
fullDismiss Dismiss Full Screen.
fullKeyOverride Override default key actions 
keycodes (JSONArray) List of keycodes to override 
enable (Boolean) Turn overriding or off (default=true) 
This will override the default behaviour of keys while in the fullscreen mode. ie:
   droid.fullKeyOverride([24,25],True)
 
This will override the default behaviour of the volume keys (codes 24 and 25) so that they do not actually adjust the volume. 
Returns a list of currently overridden keycodes.
fullQuery Get Fullscreen Properties
fullQueryDetail Get fullscreen properties for a specific widget 
id (String) id of layout widget
fullSetList Attach a list to a fullscreen widget 
id (String) id of layout widget 
list (JSONArray) List to set
fullSetProperty Set fullscreen widget property 
id (String) id of layout widget 
property (String) name of property to set 
value (String) value to set property to
fullSetTitle Set the Full Screen Activity Title 
title (String) Activity Title
fullShow Show Full Screen. 
layout (String) String containing View layout 
title (String) Activity Title (optional) 
See wiki page for more detail.
webViewShow Display a WebView with the given URL. 
url (String) 
wait (Boolean) block until the user exits the WebView (optional) 
See wiki page for more detail.

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有