当前位置:首页 >> 计算机软件及应用 >>

android笔记0.0.18



API Level 8


Android APIs
http://developer.android.com/reference/packages.html

Technical Resources
Sample Code
http://developer.android.com/resources
/browser.html?tag=sample



Project name 设置工程名 Hello Google Android
Package name 设置包名 zyf.android.test.hello
Activity name 设置活动名 Hello
Application name 设置应用程序名 Hello
Build Target 设置AVD API版本3 Android1.5








Activity 管理器 Activity manager : 该组件用于管理所有的生命周期,并维护
一个用于实现应用内部和应用之间切换 Activity的共享活动栈。

内容提供器 (Content Providers ) 这些组件将数据(如浏览器应用中的书签)封装成
能在应用间共享的形式。


位置管理器 Location Manager :该组件使 Android 能获取设备的物理位置。

通知管理器 ( NOtification Manager )该组件使应用可以将重要的事件 (例如有新短消息)
在状态栏中显示出来,且不会打断用户当前的活动。

包管理器 (package manager ):该组件使应用可以知道设备上安装的其他包的情况。


资源管理器 (Resource):该组件使应用可以访问各种资源


电话管理器 (Telephony) :该组件使应用可以知道设备的电话服务状态。它还负
责电话的拨打和接听。


视图系统 (view System) :该组件 负责管理用户界面元素和生成面向用户界面的事件。

窗口管理器 (window Manger) :该组件将屏幕 上的元素组织到窗口中,分配绘图界面,

同时执行其他窗口相关任务。





==================================

RatingBar

第九讲:用户界面 View(四)

http://hellorheaven.iteye.com/blog/1098649


相簿浏览 Gallery












獲取 Android 設備的 ID,
Settings.Secure.ANDROID_ID
android.provider.Settings.Secure 類的
ANDROID_ID 值是一個第一次啟動 Android
設備時隨機生成的64位數(以十六進制字符串表示),
"應在"保持設備一生不變的.
(當設備執行重置出廠值時, 該值可能改變.)



String Id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);














----------



android.os.Debug查询PSS,VSS,USS等单个进程使用内存信息
MemoryInfo[] memoryInfoArray = am.getProcessMemoryInfo(pids);
MemoryInfo pidMemoryInfo=memoryInfoArray[0];
pidMemoryInfo.getTotalPrivateDirty();

getTotalPrivateDirty()
Return total private dirty memory usage in kB. USS

getTotalPss()
Return total PSS memory usage in kB.
PSS
getTotalSharedDirty()
Return total shared dirty memory usage in kB. RSS


二、直接对Android文件进行解析查询,
/proc/cpuinfo系统CPU的类型等多种信息。
/proc/meminfo 系统内存使用信息

/proc/meminfo
MemTotal: 16344972 kB
MemFree: 13634064 kB
Buffers: 3656 kB
Cached: 1195708 kB
我们查看机器内存时,会发现MemFree的值很小。这主要是因为,
在linux中有这么一种思想,内存不用白不用,
因此它尽可能的cache和buffer一些数据,以方便下次使用。
但实际上这些内存也是可以立刻拿来使用的。
所以 空闲内存=free+buffers+cached=total-used
通过读取文件/proc/meminfo的信息获取Memory的总量。
ActivityManager. getMemoryInfo(ActivityManager.MemoryInfo)获取当前的可用Memory量。

三、通过Android系统提供的Runtime类,执行adb 命令(top,procrank,ps...等命令)查询
通过对执行结果的标准控制台输出进行解析。这样大大的扩展了Android查询功能.例如:
final Process m_process = Runtime.getRuntime().exec("/system/bin/top -n 1");
final StringBuilder sbread = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(m_process.getInputStream()), 8192);

# procrank
Runtime.getRuntime().exec("/system/xbin/procrank");
内存耗用:VSS/RSS/PSS/USS
Terms
VSS - Virtual Set Size 虚拟耗用内存(包含共享库占用的内存)
RSS - Resident Set Size 实际使用物理内存(包含共享库占用的内存)
PSS - Proportional Set Size 实际使用的物理内存(比例分配共享库占用的内存)
USS - Unique Set Size 进程独自占用的物理内存(不包含共享库占用的内存)
一般来说内存占用大小有如下规律:VSS >= RSS >= PSS >= USS




























================================================

javadoc的注释

javadoc的注释方式已经忘得差不多,需要复习一下。

/** ...... */ 注释若干行,并写入 javadoc 文档,
命令行为:javadoc -d 文档存放目录 -author -version 源文件名.java,
在Eclipse中Porject-> Generate Javadoc...

在/** */里面是可以使用HTML的脚本,
例如<li>,<br>等等。可以在类,方法之前加入注释说明。例子如下:

/**
* 方法/类的简述.
* <p>详细说明第一行<br>
* 详细说明第二行
* @param ,用于参数描述
* @return ,描述返回之没有返回值
*/

@author 标明开发该类模块的作者
@version 标明该类模块的版本
@see 参考转向,也就是相关主题
@param 对方法中某参数的说明
@return 对方法返回值的说明
@exception 对方法可能抛出的异常进行说明
@author 作者名
@version 版本号

















=====================================

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.helloactivity" >
<application android:label="He llo, Activity!" >
<activity android:name="HelloActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>





Hello.java


package zyf.android.test.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Hello extends Activity {


public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
//setContentView(R.layout.main);

TextView tv = new TextView(this);

tv.setText("这是一个测试Android的helloWorld");

setContentView(tv);

}
}












main.xml。这个文件的内容是有关用户界面布局和设计的

EX:



<LinearLayout> <!--整体布局 表示线性布局-->
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" 控件布局方向 垂直往下布局
android:layout_width="fill_parent"
android:layout_height="fill_parent" 上层控件填充满
名字空间
<TextView
android:layout_width="fill_parent"
横向填充满
android:layout_height="wrap_content" 纵向按实际高度填充
android:text="@string/hello"
要引用到的hello字符串
/>
图形空间 派生于 View
<Button
android:id="@+id/widget40_button_OK"button控件ID
android:layout_width="wrap_content"
android:layout_height="wrap_content"按实际宽度高度显示填充
android:text="OK"
></Button>
</LinearLayout>






savedInstanceState 保存当时的状态




AndroidManifest.xml文件,
该文件向Android操作系统描述了,
本程序所包括的组件,所实现的功能,
能处理的数据,要请求的资源等等






android.app : 提供高层的程序模型、提供基本的运行环境
android.content : 包含各种的对设备上的数据进行访问和发布的类
android.database :通过内容提供者浏览和操作数据库
android.graphics :底层的图形库,包含画布,颜色过滤,
点,矩形,可以将他们直接绘制到屏幕上.
android.location :定位和相关服务的类
android.media : 提供一些类管理多种音频、视频的媒体接口
android.net : 提供帮助网络访问的类,超过通常的java.net.* 接口
android.os : 提供了系统服务、消息传输、IPC 机制
android.opengl : 提供OpenGL 的工具
android.provider : 提供类访问Android 的内容提供者
android.telephony :提供与拨打电话相关的API 交互
android.view : 提供基础的用户界面接口框架
android.util : 涉及工具性的方法,例如时间日期的操作
android.webkit : 默认浏览器操作接口
android.widget : 包含各种UI 元素(大部分是可见的)在应用程序的屏幕中使用



==========
Context
==========
上下文



public abstract class
Context
extends Object
java.lang.Object
android.content.Context


Context的类主要有Android特有的几个模型,Activity、Service以及BroadcastReceiver

-------------------
Constants

1)ACTIVITY_SERVICE
管理应用程序的系统状态

Use with getSystemService(String) to
retrieve a ActivityManager for interacting 交互
with the global system state.


ActivityManager am =
(ActivityManager) getSystemService(ACTIVITY_SERVICE);




2)
ACCOUNT_SERVICE retrieve a AccountManager for receiving
intents at a time of your choosing

ACCESSIBILITY_SERVICE retrieve a AccessibilityManager for giving
the user feedback for UI events through
the registered event listeners.

ALARM_SERVICE retrieve a AlarmManager for receiving
intents at a time of your choosing.

AUDIO_SERVICE retrieve a AudioManager for handling
management of volume, ringer modes
and audio routing

BIND_AUTO_CREATE
BIND_DEBUG_UNBIND

CLIPBOARD_SERVICE retrieve a ClipboardManager for accessing
and modifying the contents of
the global clipboard
检索访问和修改的全局剪贴板的内容

CONNECTIVITY_SERVICE retrieve a ConnectivityManager for handling
management of network connections


CONTEXT_IGNORE_SECURITY ignore any security restrictions on the Context
being requested, allowing it to always be
loaded.被请求的上下文忽略任何安全限制,
允许它总是被载入。

CONTEXT_INCLUDE_CODE include the application code with the context.

CONTEXT_RESTRICTED

INPUT_METHOD_SERVICE

KEYGUARD_SERVICE 键盘锁的服务

LAYOUT_INFLATER_SERVICE 取得xml里定义的view

LOCATION_SERVICE

MODE_APPEND
MODE_PRIVATE
MODE_WORLD_READABLE
MODE_WORLD_WRITEABLE

NOTIFICATION_SERVICE retrieve a NotificationManager for informing
the user of background events.状态栏的服务

POWER_SERVICE

SEARCH_SERVICE

SENSOR_SERVICE

TELEPHONY_SERVICE

VIBRATOR_SERVICE 震动硬件

WALLPAPER_SERVICE

WIFI_SERVICE

WINDOW_SERVICE 管理打开的窗口程序




----------------------------------
---------------------------------
Methods
-------

getSystemService 获得系统服务

public abstract Object
getSystemService (String name)
Since: API Level 1

Return the handle to a system-level service by name.
The class of the returned object varies by the requested name



ActivityManager am =
(ActivityManager) getSystemService(ACTIVITY_SERVICE);



-------
2)

ContentResolver 解析

public abstract ContentResolver
getContentResolver ()

Since: API Level 1

Return a ContentResolver instance for your
application's package.

解决在不同的应用包之间共享数据的工具


--------------------------------
3)bindService

public abstract


boolean bindService (Intent service, ServiceConnection conn, int flags)

Since: API Level 1

Connect to an application service, creating it if needed.
This defines a dependency between your application and the service.
The given conn will receive the service object
when it is created and be told if it dies and restarts.
The service will be considered required by the system
only for as long as the calling context exists.

For example, if this Context is an Activity that is stopped,
the service will not be required to
continue running until the Activity is resumed.


This function will throw SecurityException
if you do not have permission to bind to the given service.

Note:

this method can not be called from a BroadcastReceiver
component.A pattern you can
use to communicate from a BroadcastReceiver to a Service
is to call startService(Intent) with the arguments containing
the command to be sent, with the service calling its
stopSelf(int) method when done executing that command.
See the API demo App/Service/Service Start Arguments Controller
for an illustration of this. It is okay, however,
to use this method from a BroadcastReceiver that
has been registered with registerReceiver(BroadcastReceiver, IntentFilter),
since the lifetime of this BroadcastReceiver is tied to
another object (the one that registered it).




Parameters


service Identifies the service to connect to.
The Intent may specify either
an explicit component name,
or a logical description (action, category, etc)
to match an IntentFilter published by a service.

标识连接到的服务。这样做的目的可能指定任一个明确的组件名称,
或逻辑描述(动作,类别等)匹配服务出版IntentFilter。


conn Receives information as the service is
started and stopped.


flags Operation options for the binding.
May be 0,
BIND_AUTO_CREATE, BIND_DEBUG_UNBIND,
BIND_NOT_FOREGROUND, BIND_ABOVE_CLIENT,
BIND_ALLOW_OOM_MANAGEMENT, or BIND_WAIVE_PRIORITY.

绑定操作选项

Returns

If you have successfully bound to the service,
true is returned;
false is returned if the connection is
not made so you will not receive the service object.

Throws
SecurityException


See Also

unbindService(ServiceConnection)
startService(Intent)
BIND_AUTO_CREATE
BIND_DEBUG_UNBIND
BIND_NOT_FOREGROUND





EX:

//ServiceConnection msc;
//private Context mContext;



Intent i = new Intent();
i.setClass(XhulooActivity_playmusic.this, MusicService.class);
mContext.bindService(i, msc, BIND_AUTO_CREATE); //执行IBinder()




















package
android.app




========
Activity
========
Activity是Android中的视图部分,负责界面显示

java.lang.Object
android.content.Context
android.content.ContextWrapper
android.view.ContextThemeWrapper
android.app.Activity

Activity有四种基本状态:

1、Running
位于屏幕最前端时,此时处于可见状态,和用户可交互的状态。

2、Paused
当Acitivy被另一个透明的或者非全屏的Activity
覆盖时的状态叫Paused状态,虽然可见但不可交互。

3、Stop
当Activity被另外一个Activity覆盖、
界面不可见时处于Stop状态

4、Killed
Activity被系统杀死或者跟本没启动时就是Killed状态


onCreate()

onRestart()

onStart()在activity第一次对用户可见的时候会被调用

onResume()在activity继续和用户交互的情况会被调用

onPause()

onStop()

onDestroy()





1)
public void setContentView (View view)

可以控制具体哪一个控件和系统的UI联系起来
(我的理解是设置为主显示 View)

Parameters
view The desired content to display.


2)onOptionsItemSelected

public boolean onOptionsItemSelected (MenuItem item)

Parameters
item The menu item that was selected.
Returns

boolean Return false to allow normal
menu processing to proceed, true to consume it here.



ex:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {

case Menu.FIRST + 1:

Toast.makeText(this, "删除菜单被点击了",
Toast.LENGTH_SHORT).show();

break;}











3)public void onOptionsMenuClosed (Menu menu)
Since: API Level 1

This hook is called whenever the options menu is being closed
(either by the user canceling the menu with the back/menu button,
or when an item is selected).

Parameters
menu The options menu as last shown or first
initialized by onCreateOptionsMenu().





4)onPrepareOptionsMenu

public boolean onPrepareOptionsMenu (Menu menu)

选项菜单显示之前onPrepareOptionsMenu方法会被调用,
你可以用此方法来根据打当时的情况调整菜单
Prepare the Screen's standard options menu to be displayed.

Returns

You must return true for the menu to be displayed;
if you return false it will not be shown.




-- - -- -- - -- - -- - -- - - - - - --- - - --
5)startActivityForResult 返回结果的跳转

配合onActivityResult 处理返回结果

public void startActivityForResult
(Intent intent, int requestCode)


Launch an activity for which you would
like a result when it finished.
When this activity exits,
your onActivityResult() method will be
called with the given requestCode.
Using a negative requestCode is
the same as calling startActivity(Intent)
(the activity is not launched as a sub-activity).

Note that this method should only
be used with Intent protocols
that are defined to return a result.
In other protocols
(such as ACTION_MAIN or ACTION_VIEW),
you may not get the result when you expect.
For example,
if the activity you are launching uses the
singleTask launch mode,
it will not run in your task and
thus you will immediately receive a cancel result.


As a special case, if you call startActivityForResult()
with a requestCode >= 0 during the initial
onCreate()/onResume() of your activity,
then your window will not be displayed until
a result is returned back from the started activity.
This is to avoid visible flickering
when redirecting to another activity.

This method throws ActivityNotFoundException
if there was no Activity found to run the given Intent.


Parameters:

intent The intent to start.

requestCode
If >= 0,
this code will be returned
in onActivityResult() when the activity exits.

Throws
android.content.ActivityNotFoundException




EX:
startActivityForResult(intent, 0); //跳转,此处的0 OR >=0




- -- - -- - - - -- - - -- - - - -- - -
6) onActivityResult 处理跳转的返回结果

protected void onActivityResult (int requestCode, int resultCode, Intent data)
Since: API Level 1

Called when an activity you launched exits,
giving you the requestCode you started it with,
the resultCode it returned,
and any additional data from it.
The resultCode will be RESULT_CANCELED
if the activity explicitly returned that,
didn't return any result,
or crashed during its operation.

You will receive this call immediately
before onResume() when your activity is re-starting.


Parameters

requestCode The integer request code originally
supplied to startActivityForResult(),
allowing you to identify who this result came from.


resultCode The integer result code returned
by the child activity through its setResult().


data An Intent, which can return result data to the caller
(various data can be attached to Intent "extras").




EX:

//main
protected void onActivityResult
(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
//resultCode为回传的标记,回传的是RESULT_OK
case RESULT_OK:
Bundle b=data.getExtras();
//data回传的Intent
String str=b.toString();
//String str=b.getString("msg");
//str即为回传的值
break;
default:
break;
}
}


//child
Intent data = new Intent();
data.putExtra("msg","my message");
setResult(RESULT_OK, data);
finish();

- - -- -- - -- -- - - -- - --

7)startActivity 跳转
public void startActivity (Intent intent)

Parameters

intent The intent to start.

Throws
android.content.ActivityNotFoundException

=============================================


===============
ListActivity
===============
public class
extends Activity










==============
Dialog class
java.lang.Object
android.app.Dialog
===========



----------
AlertDialog
import android.app.AlertDialog;
----------

1.0)AlertDialog(Context context)

1.1)protected AlertDialog (Context context, int theme)


AlertDialog.Builder my_ADialog
=new AlertDialog.Builder(this);
// AlertDialog.Builder my_ADialog=new AlertDialog.Builder(XhulooActivity.this); ;

/*设置标题*/
my_ADialog.setTitle("Android 提示");

/*设置显示消息*/
my_ADialog.setMessage("提示对话框消息!!");


/*设置按键*/
my_ADialog.setPositiveButton
("退出HulooActivity",new DialogInterface.OnClickListener()
{public void onClick(DialogInterface dialog, int id) {
HulooActivity.this.finish(); }
// import android.content.DialogInterface; });
my_ADialog.setNegativeButton
("取消", new DialogInterface.OnClickListener()
{ public void onClick(DialogInterface dialog, int id)
{ dialog.cancel(); }
});


/*显示*/
my_ADialog.show();






=============
DialogInterface
=============
import android.content.DialogInterface;


interface
1)DialogInterface.OnCancelListener

Interface used to allow the creator
of a dialog to run some code
when the dialog is canceled.


interface

2)DialogInterface.OnClickListener

Interface used to allow the creator
of a dialog to run some code when
an item on the dialog is clicked..


interface

3)DialogInterface.OnDismissListener

Interface used to allow the creator of
a dialog to run some code when the dialog is dismissed.


interface

4)DialogInterface.OnKeyListener

Interface definition for a callback
to be invoked when a key event is
dispatched to this dialog.


interface

5)DialogInterface.OnMultiChoiceClickListener

Interface used to allow the creator of a
dialog to run some code when an item in
a multi-choice dialog is clicked.


interface

6)DialogInterface.OnShowListener

Interface used to allow the creator of
a dialog to run some code when the dialog is shown.


EX:
my_ADialog.setPositiveButton
("退出HulooActivity.this.finish();并访问人人",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HulooActivity.this.finish();
Uri uri=Uri.parse("http://3g.renren.com");
Intent intent=new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent); //跳转访问互联网
} });




==========================================

========
ActivityManager
==========

extends Object
java.lang.Object
android.app.ActivityManager


Interact with the overall activities running in the system.
交互的系统中运行的整体活动。



ActivityManager.MemoryInfo 可用内存

ActivityManager.ProcessErrorStateInfo

ActivityManager.RecentTaskInfo

ActivityManager.RunningAppProcessInfo 正在运行的进程

ActivityManager.RunningServiceInfo

ActivityManager.RunningTaskInfo


1)getDeviceConfigurationInfo()
获取设备的配置属性

Get the device configuration attributes.

2)getMemoryInfo(ActivityManager.MemoryInfo outInfo)



===========
3)getRunningAppProcesses() 获得正在运行应用信息

public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses ()


Returns a list of application processes that are running on the device.



Note: this method is only intended for debugging or
building a user-facing process management UI.

Returns

Returns a list of RunningAppProcessInfo records, or null if there are no running processes (it will not return an empty list). This list ordering is not specified.

Throws

SecurityException











--------
ActivityManager.MemoryInfo

Fields
1)public long availMem

public boolean lowMemory

public long threshold The threshold of availMem at which
we consider memory to be low and start killing
background services and other
non-extraneous processes.




EX:

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ActivityManager.MemoryInfo mf = new ActivityManager.MemoryInfo();
am.getMemoryInfo(mf);




---------
ActivityManager.RunningAppProcessInfo

Fields
---
public String processName
------
public int importance

The relative importance level that the system places on this process.
-------
public int importanceReasonCode

The reason for importance, if any.

-----
public ComponentName importanceReasonComponent

For the specified values of importanceReasonCode,
this is the name of the component that is being used in this process.
------
public int importanceReasonPid

For the specified values of importanceReasonCode,
this is the process ID of the other process that is a client of this process.

--------
public int lastTrimLevel

Last memory trim level reported to the process:
corresponds to the values supplied to ComponentCallbacks2.onTrimMemory(int).

------
public int lru
An additional ordering within a particular importance category,
providing finer-grained information about
the relative utility of processes within a category.

------
public int pid

The pid of this process; 0 if none

------
public String[]

pkgList

All packages that have been loaded into the process.

----

public int uid

The user id of this process.


EX:

List<RunningAppProcessInfo> procList = am.getRunningAppProcesses();

for(int i = 0; i<procList.size();i++){

procinfo.append(procList.get(i).processName).append("\t\t").
append(procList.get(i).pid).append("\n");
}










===============
android.os.Bundle
==============

Bundle类是一个final类:
public final class
Bundle
extends Objectimplements Parcelable Cloneable


两个activity之间的通讯可以通过bundle类来实现,做法就是:

(1)新建一个bundle类


Bundle mBundle = new Bundle();

(2)bundle类中加入数据(key -value的形式,
另一个activity里面取数据的时候,就要用到key,找出对应的value)

public void putString (String key, String value)
Since: API Level 1

Inserts a String value into the mapping of this Bundle,
replacing any existing value for the given key.
Either key or value may be null.

Parameters
key a String, or null
value a String, or null

mBundle.putString("Data", "data from TestBundle");


(3)新建一个intent对象,并将该bundle加入这个intent对象


Intent intent = new Intent();
intent.setClass(TestBundle.this, Target.class);
intent.putExtras(mBundle);
startActivity(intent); //Launch a new activity







=================================























android.os.Environment



Provides access to environment variables.




1)getExternalStorageDirectory() 获得SD卡的PATH

static File getExternalStorageDirectory()

Gets the Android external storage directory.


EX:
Environment.getExternalStorageDirectory().toString();



===============================
android.os.Build

Information about the current build, extracted from system properties.


[String]
android.os.Build.BOARD 底层驱动控制板
android.os.Build.BRAND The brand the software is customized for
android.os.Build.CPU_ABI CPU类型+ ABI的本机代码的指令集名称

DEVICE 工业设计的名称

DISPLAY A build ID string meant for displaying to the user

FINGERPRINT 一个字符串,它唯一标识此构建(指纹)

HOST

ID a changelist number

MANUFACTURER

MODEL 最终产品的最终用户可见的名称

PRODUCT 整体产品的名称

TAGS Comma-separated tags describing the build,
like "unsigned,debug".

TYPE

USER

================================



Vibrator
extends Object
java.lang.Object
android.os.Vibrator

<uses-permission android:name="android.permission.VIBRATE"></uses-permission>



void cancel()
Turn the vibrator off.

boolean hasVibrator() //Since: API Level 11
Check whether the hardware has a vibrator.

void vibrate(long[] pattern, int repeat)

Vibrate with a given pattern.


void vibrate(long milliseconds)
Turn the vibrator on.




/*震动*/
final Vibrator vi=(Vibrator)getSystemService(VIBRATOR_SERVICE );
long[] pattern = {100, 50,200, 60,300,70,390,80,300,50,200,30}; // OFF/ON/OFF/ON...
int repeat=4;
vi.vibrate(pattern, repeat);




--------------------

==========
Message
==========

public final class

extends Object
implements Parcelable


android.os.Message





























---------------------------------------
=======
Handler 处理程序
=======

public class
Handler
extends Object

android.os.Handler




A Handler allows you to send and process Message
and Runnable objects associated with a thread's MessageQueue.





Handler中分发消息的一些方法
post(Runnable)
postAtTime(Runnable,long)
postDelayed(Runnable long)
sendEmptyMessage(int)
sendMessage(Message)
sendMessageAtTime(Message,long)
sendMessageDelayed(Message,long)
以上post类方法允许你排列一个Runnable对象到主线程队列中,
sendMessage类方法,
允许安排一个带数据的Message对象到队列中,等待更新.













由于Handler运行在主线程中(UI线程中),
它与子线程可以通过Message对象来传递数据,这个时候,
Handler就承担着接受子线程传过来的
(子线程用sedMessage()方法传递)Message对象,
(里面包含数据) , 把这些消息放入主线程队列中,
配合主线程进行更新UI。



二、Handler一些特点
handler可以分发Message对象和Runnable对象到主线程中,
每个Handler实例,
都会绑定到创建他的线程中(一般是位于主线程),
它有两个作用:
(1)安排消息或Runnable 在某个主线程中某个地方执行,
(2)安排一个动作在不同的线程中执行



三、Handler实例
(1) 子类需要继承Handler类,
并重写handleMessage(Message msg) 方法, 用于接受线程数据
以下为一个实例,它实现的功能为 : 通过线程修改界面Button的内容



public class MyHandlerActivity extends Activity {
Button button;
MyHandler myHandler;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.handlertest);

button = (Button) findViewById(R.id.button);
myHandler = new MyHandler();
// 创建新的Handler实例
//绑定到当前线程和消息的队列中,开始分发数据

MyThread m = new MyThread();
new Thread(m).start();
}

/**
* 接受消息,处理消息 ,此Handler会与当前主线程一块运行
* */

class MyHandler extends Handler {
public MyHandler() {
}

public MyHandler(Looper L) {
super(L);
}

// 子类必须重写此方法,接受数据
@Override
public void handleMessage(Message msg) {

Log.d("MyHandler", "handleMessage......");
super.handleMessage(msg);

// 此处可以更新UI
Bundle b = msg.getData();
String color = b.getString("color");
MyHandlerActivity.this.button.append(color);

}
}





class MyThread implements Runnable {
public void run() {

try {
Thread.sleep(10000);
} catch (InterruptedException e) {

e.printStackTrace();
}

Log.d("thread.......", "mThread........");
Message msg = new Message();
Bundle b = new Bundle();// 存放数据
b.putString("color", "我的");
msg.setData(b);

MyHandlerActivity.this.myHandler.sendMessage(msg);
// 向Handler发送消息,更新UI

}
}


------------------------------------



=============
========
Service
========
=============



A Service is not a separate process.
The Service object itself does not imply it is running in its own process;
unless otherwise specified,
it runs in the same process as the application it is part of.

A Service is not a thread.
It is not a means itself to do work off of the main thread
(to avoid Application Not Responding errors)




Service生命周期


第一次启动Service时,先后调用了onCreate(),onStart(),

当停止Service时,则执行onDestroy()方法,这里需要注意的是,

如果Service已启动,当再次启动Service时,不执行onCreate(),而是直接执行onStart()方法



Service与Activity通信:

用到bindService和onBindService方法,
分别执行了Service中IBinder()和onUnbind()方法







































==========
==========
package
android.view
==========
==========



Interfaces


1.1)OnClickListener

public static interface
View.OnClickListener

public abstract void onClick (View v)
Since: API Level 1

Called when a view has been clicked.
Parameters
v The view that was clicked.



1.2)OnKeyListener

public abstract boolean onKey
(View v, int keyCode, KeyEvent event)

Since: API Level 1

Called when a key is dispatched to a view.
This allows listeners to get a chance to
respond before the target view.


Parameters

v The view the key has been dispatched to.

keyCode The code for the physical key that
was pressed

event The KeyEvent object containing full
information about the event.


Returns

True if the listener has consumed the event,
false otherwise.

EX:
public boolean onKey
(View v, int keyCode, KeyEvent event) {
ok_button.setText(mEditText01.getText().toString());
return false;
}







---------------
Public Methods



1)onTouchEvent 屏幕触动事件

public boolean onTouchEvent (MotionEvent event)

Implement this method to handle touch screen motion events.


Parameters
event The motion event.


Returns

True if the event was handled, false otherwise.
如果事件发生则触发事件的响应


2)


























Classes
===============================
View 是一个可以显示的控件对象
java.lang.Object
android.view.View
===============================
1)setBackgroundColor

public void setBackgroundColor (int color)
Since: API Level 1

Sets the background color for this view.
Parameters
color the color of the background




2)setBackgroundResource


public void setBackgroundResource (int resid)
Since: API Level 1

Set the background to a given resource.
The resource should refer to
a Drawable object or 0 to remove the background.
Related XML Attributes

android:background

Parameters
resid The identifier of the resource.


3)设置 焦点改变 监听器
setOnFocusChangeListener
public void setOnFocusChangeListener (View.OnFocusChangeListener l)


Since: API Level 1

Register a callback to be invoked
when focus of this view changed.

Parameters
l The callback that will run.

EX:
mImageButton1.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View arg0, boolean isFocused) {
// TODO Auto-generated method stub
/*若ImageButton 状态为onFocus 改变ImageButton 的图片
并改变textView 的文字*/
if (isFocused == true {
true)
mTextView1.setText(R.string. onfocus );
mImageButton1.setImageResource(R.drawable. onfocusimage );
}
/*若ImageButton 状态为offFocus 改变ImageButton 的图片
并改变textView 的文字*/
else {
mTextView1.setText(R.string. lostfocus );
mImageButton1.setImageResource(R.drawable. lostfocusimage );
}
}
});




4)setOnClickListener

public void setOnClickListener (View.OnClickListener l)
Since: API Level 1

Register a callback to be invoked
when this view is clicked.
If this view is not clickable, it becomes clickable.

Parameters
l The callback that will run


EX:
ok_button.setOnClickListener
(new Button.OnClickListener(){
public void onClick(View v) {
ok_button.setText("Hi ,ok_button clicked!");}
}
);




5)设置按键监听器 setOnKeyListener

public void setOnKeyListener (View.OnKeyListener l)
Since: API Level 1

Register a callback to be invoked
when a key is pressed in this view.

Parameters
l the key listener to attach to this view




6)可见
public void setVisibility (int visibility)
Since: API Level 1

Set the enabled state of this view.
Related XML Attributes

android:visibility

Parameters
visibility One of VISIBLE, INVISIBLE, or GONE.



7)contentDescription
public void setContentDescription (CharSequence contentDescription)




android:contentDescription



Defines text that briefly describes content of the view.
This property is used primarily for accessibility.
Since some views do not have textual representation
this attribute can be used for providing such.
定义的视图,简要介绍内容的文字。此属性主要用于辅助功能。
由于一些意见没有文字表述这个属性可用于提供此类。




8)startAnimation 开始动画


public void startAnimation (Animation animation)
Since: API Level 1

Start the specified animation now.
Parameters
animation the animation to start now


EX:
image.startAnimation(ra);




9)onDraw

protected void onDraw (Canvas canvas)

Implement this to do your drawing.
这个实现你做的绘图。

Parameters
canvas the canvas on which the background will be drawn
















--------------------------
android.widget.TextView
文本 TextView


1)getText()

CharSequence getText()
Return the text the TextView is displaying.


2)getTextSize ()

public float getTextSize ()
Since: API Level 1

Returns

the size (in pixels) of the
default text size in this TextView.


3)setTextSize

public void setTextSize (int unit, float size)
Since: API Level 1

Set the default text size to a given unit and value.
See TypedValue for the possible dimension units.

Related XML Attributes

android:textSize

Parameters
unit The desired dimension unit.
size The desired size in the given units.

所需的尺寸单位
在给定的单位所需的大小
EX:
android:textSize="18sp"



4)
setTextColor 设置文本颜色


public void setTextColor (int color)
Since: API Level 1

Sets the text color for all the states
(normal, selected, focused) to be this color.

Related XML Attributes

android:textColor

android:textColor="#ffffff"



5)setShadowLayer
public void setShadowLayer
(float radius, float dx, float dy, int color)
Since: API Level 1

Gives the text a shadow of
the specified radius and color,
the specified distance from its normal position.

Related XML Attributes

android:shadowColor 阴影颜色
android:shadowDx 阴影的水平偏移量
android:shadowDy 阴影的垂直偏移量
android:shadowRadius 阴影的范围


6)android:ellipsize

ellipsize属性
设置当文字过长时,该控件该如何显示。
有如下值设置:”start”—–省略号显示在开头;
”end”——省略号显示在结尾;
”middle”—-省略号显示在中间;
”marquee” ——以跑马灯的方式显示(动画横向移动)

android:ellipsize="marquee"



7)marqueeRepeatLimit属性

在ellipsize指定marquee的情况下,
设置重复滚动的次数,
当设置为marquee_forever时表示无限次。

marquee_forever -1
Indicates that marquee should repeat indefinitely.











<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="账号"
android:textColor="@color/darkgray"
android:layout_x="61px"
android:layout_y="69px"
>
</TextView>







EX:
1 导入 TextView 包
import android.widget.TextView;

2 在 mainActivity.java 中声明一个 TextView
private TextView mTextView01;


3 在 main.xml 中定义一个 TextView

<TextView android:text="TextView01"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</TextView>


4 利用 findViewById()方法获取 main.xml 中的 TextView

mTextView01 = (TextView) findViewById(R.id. TextView01);


5 设置 TextView 标签内容

String str_2 = "欢迎来到Android 的TextView 世界...";
mTextView01.setText(str_2);


6 设置文本超级链接
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="ALL"
android:text="请访问Android 开发者:
http://developer.android.com/index.html" >
</TextView>






----------------------
输入框 EditText







1)
getText()
Return the text the TextView is displaying.



2)
setSelection(int index)
Move the cursor to offset index
光标移动到偏移索引

3)
setSelection(int start, int stop)

Set the selection anchor to start
and the selection edge to stop.

4)
setText(CharSequence text, TextView.BufferType type)

Sets the text that this TextView is to display
(see setText(CharSequence))
and also sets whether
it is stored in a styleable/spannable buffer
and whether it is editable



EX:
final EditText mEditText=(EditText)findViewById
(R.id. myEditText);











---------------------
输入法 InputMethod


---------------------------
活动方法 MovementMethod


---------------
按钮 Button
import android.widget.Button;









EX:
final Button ok_button=(Button)findViewById(R.id.button_OK);


ok_button.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{ok_button.setText("Hi ,ok_button clicked!");}
});


/*将Button设置成不可选*/
ok.setEnabled(false);















---------------------
单选按钮 RadioButton


----------------
复选框 Checkbox
extends CompoundButton


Inherited XML Attributes
From class android.widget.TextView
From class android.view.View

public void
onPopulateAccessibilityEvent
(AccessibilityEvent event)





android:paddingLeft="30px"

按钮上设置的内容(例如图片)离按钮左边边界30个像素

android:layout_marginLeft="30px"
整个按钮离左边设置的内容30个像素

margin就是指元素边界外的距离,padding刚好相反,定义元素边界内部的距离





private CheckBox iAccept;

iAccept=(CheckBox)findViewById(R.id. CheckBox_Accept );


/*获取XML中字符串*/
CharSequence titleString=getString(R.string. allOK);

/*设置复选框标题 android:hint*/
iAccept.setHint(titleString);

/*设置复选框标题字体颜色 android:textColorHint*/
iAccept.setHintTextColor(Color. RED);

/*将CheckBox设置成未选中*/
iAccept.setChecked(false);

new iAccept.setOnClickListener
(new CheckBox.OnClickListener(){

public void onClick(View v) {

if(iAccept.isChecked()){ //......
}
} } );








-----------------
滚动视图 ScrollView


<?xml version="1.0" encoding="UTF-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">

<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stretchColumns="1">

<TableRow>

<TextView
android:id="@+id/wr_tv"
android:text="@string/hello"
android:textSize="60sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></TextView>
</TableRow>

<Button
android:id="@+id/wr_bt_OK"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="@string/ok"
android:textColor="#ffffff"
android:textSize="18sp" />
</TableLayout>
</ScrollView>



------------------
ImageView
import android.widget.ImageView;





ImageView mImageView = (ImageView)
findViewById(R.id.myImageView1);
mImageView.setImageDrawable
(getResources().getDrawable(R.drawable.action));







ImageButton
extends ImageView



--------------------

public class
Spinner
android.widget.Spinner



--------------------
ListView 列表视图

import android.widget.ListView;


1)public void setAdapter (ListAdapter adapter)
Since: API Level 1

Sets the data behind this ListView


Parameters

adapter The ListAdapter which is
responsible for maintaining the data
backing this list and for producing
a view to represent an item in that data set.

2)






EX:
<ListView
android:id="@+id/list1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>



final String[] data = {"第一章","第二章","第三章","第四章","第五章"};

ListView lv = (ListView) findViewById(R.id.list1);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,data);

//simple_list_item_1是系统本身有的布局
//泛型,JAVA5.0中的新特性,告别是在集合中框架中运用多
//如List<String> list=new ArrsyList<String>();
//指定了此集合中只能存放String类型的数据
//目的是为了安全,属于编译时语法
lv.setAdapter(adapter);

















=========
ViewGroup
=========
extends View
implements ViewManager ViewParent

java.lang.Object
android.view.View
android.view.ViewGroup






android:background="@color/white"


<!--在 values 文件夹中定义一个 drawable.xml 用来存放颜色值-->
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<color name="white" >#FFFFFF</color>
<color name="darkgray" >#938192</color>
<color name="lightgreen" >#7cd12e</color>
</resources>









装载和管理下一层的View对象或ViewGroup对象
是一个容纳其它元素的的容器。
ViewGroup是布局管理器(layout)及view容器的基类
V还定义了嵌套类ViewGroup.LayoutParams
这个类定义了一个显示对象的位置、大小等属性,
view通过LayoutParams中的这些属性值来告诉父级,
它们将如何放置









FrameLayout 帧布局

所有显示对象爱你过都将固定在屏幕的左上角,
不能指定位置,但允许有多个显示对象,
只是后一个会直接覆盖在前一个之上显示,
会把前面的组件部分或全部挡住


--------------------------------
线性布局LinearLayout

是RadioGroup, TabWidget,
TableLayout, TableRow,
ZoomControls类的父类。
LinearLayout可以让它的
子元素垂直或水平的方式排成一行
(不设置方向的时候默认按照垂直方向排列)


1)控件布局方向
android:orientation

horizontal 0 Defines an horizontal widget.横
vertical 1 Defines a vertical widget. 垂直往下布局

setOrientation (int orientation)




------------------------------
绝对布局AbsoluteLayout
坐标布局,可以直接指定子元素的绝对位置






相对布局RelativeLayout
允许子元素指定它们相对于其父元素或兄弟元素的位置

RelativeLayout用到的一些重要的属性:


第一类:属性值为true或false

android:layout_centerHrizontal 水平居中
android:layout_centerVertical 垂直居中
android:layout_centerInparent 相对于父元素完全居中
android:layout_alignParentBottom 贴紧父元素的下边缘
android:layout_alignParentLeft 贴紧父元素的左边缘
android:layout_alignParentRight 贴紧父元素的右边缘
android:layout_alignParentTop 贴紧父元素的上边缘
android:layout_alignWithParentIfMissing 若对应兄弟元素找不到以父元素做参照

第二类:属性值必须为id的引用名“@id/id-name”
android:layout_below 在某元素的下方
android:layout_above 在某元素的的上方
android:layout_toLeftOf 在某元素的左边
android:layout_toRightOf 在某元素的右边

android:layout_alignTop 本元素的上边缘和某元素的的上边缘对齐
android:layout_alignLeft 本元素的左边缘和某元素的的左边缘对齐
android:layout_alignBottom 本元素的下边缘和某元素的的下边缘对齐
android:layout_alignRight 本元素的右边缘和某元素的的右边缘对齐

第三类:属性值为具体的像素值,如30dip,40px
android:layout_marginBottom 离某元素底边缘的距离
android:layout_marginLeft 离某元素左边缘的距离
android:layout_marginRight 离某元素右边缘的距离
android:layout_marginTop 离某元素上边缘的距离



EX:
paddingBottom="4dip" Layout底部留出3像素空白区域
paddingLeft="12dip" Layout左边留出12像素空白
textSize="30dip" TextView的字体为30像素





表格布局TableLayout


以行列的形式管理子元素,
每一行是一个TableRow布局对象,
当然也可以是普通的View对象,
TableRow离每放一个元素就是一列,
总列数由列数最多的那一行决定

collapseColumns –
设置隐藏那些列,列ID从0开始,多个列的话用”,”分隔

stretchColumns –
设置自动伸展那些列,列ID从0开始,多个列的话用”,”分隔

shrinkColumns -
设置自动收缩那些列,列ID从0开始,多个列的话用”,”分隔


------------------------------------------

public interface
MenuItem
android.view.MenuItem




1)
public abstract int getItemId ()
Since: API Level 1

Return the identifier for this menu item.
The identifier can not be changed after
the menu is created.

Returns

The menu item's identifier.







----------
Menu
public interface

android.view.Menu
Known Indirect Subclasses
ContextMenu, SubMenu


Constants



public static final int FIRST
Since: API Level 1

First value for group and item identifier integers.
Constant Value: 1 (0x00000001)






1)add
public abstract MenuItem add
(int groupId, int itemId, int order, int titleRes)

Since: API Level 1

Variation on add(int, int, int, CharSequence)
that takes a string resource identifier
instead of the string itself.


Parameters

groupId

组别,如果不分组的话就写Menu.NONE
The group identifier that this item should be part of.
This can also be used to define groups of items for
batch state changes. Normally use NONE if
an item should not be in a group.


itemId
这个很重要,Android根据这个Id来确定不同的菜单
Unique item ID. Use NONE if you do not need a unique ID.

order
顺序,那个菜单现在在前面由这个参数的大小决定
The order for the item. Use NONE if you do
not care about the order. See getOrder().


titleRes
文本,菜单的显示文本
Resource identifier of title string.


Returns

The newly added menu item


EX:
menu.add(Menu.NONE, Menu.FIRST + 1, 5, "删除")
.setIcon(android.R.drawable.ic_menu_delete);

//setIcon为MEUN ITEM 方法 ic_menu_delete系统自带常数


---------
memory.png

menu.add(Menu.NONE, Menu.FIRST + 1, 1, "内存").
setIcon(R.drawable.memory); //自己提供的资源是以R开头












EX:
为程序添加 Menu 菜单

//创建 OptionsMenu
public boolean onCreateOptionsMenu (Menu menu ){

menu.add(Menu.NONE, Menu.FIRST + 2, 2, "保存").setIcon(

android.R.drawable.ic_menu_edit);}






===============================


ProgressBar

java.lang.Object
android.view.View
android.widget.ProgressBar

========================






1)RatingBar


1.1)
android:isIndicator 是否是一个指示器(用户无法进行更改)

Whether this rating bar is an indicator
(and non-changeable by the user).

Must be a boolean value, either "true" or "false".



  public boolean isIndicator ()

返回值

判断当前的评分条是否仅仅是一个指示器(注:即能否被修改)



  public void setIsIndicator (boolean isIndicator)

  设置当前的评分条是否仅仅是一个指示器(这样用户就不能进行修改操作了)

  参数

  isIndicator Bool值,是否是一个指示器




1.2)
android:numStars


显示的星型数量,必须是一个整形值,像“100”。


public int getNumStars ()

    返回显示的星型数量

      返回值

  显示的星型数量

 public void setNumStars (int numStars)

  设置显示的星型的数量。为了能够正常显示它们,
建议将当前widget的布局宽度设置为
wrap content

  参数

  numStars 星型的数量



1.3)
android:rating


默认的评分,必须是浮点类型,像“1.2”。

public float getRating ()

  获取当前的评分(填充的星型的数量)

  返回值

  当前的评分


public void setRating (float rating)

  设置分数(星型的数量)

  参数

  rating 设置的分数



getRating ()


public float getRating ()
Since: API Level 1

Gets the current rating (number of stars filled).
Returns

The current rating.



1.4)
android:stepSize


评分的步长,必须是浮点类型,像“1.2”。

public float getStepSize ()

  获取评分条的步长

  返回值

  步长


public void setStepSize (float stepSize)

  设置当前评分条的步长(step size)

  参数

  stepSize 评分条的步进。例如:如果想要半个星星,它的值为0.5。



1.5)
  public RatingBar.OnRatingBarChangeListener
getOnRatingBarChangeListener ()

返回值

监听器(可能为空)监听评分改变事件



1.6)  android:max

Defines the maximum value the progress can take.

  public synchronized void setMax (int max)

  设置评分等级的范围,从0到max

  参数

  max 评分条最大范围。



1.7)
  public void setOnRatingBarChangeListener
(RatingBar.OnRatingBarChangeListener listener)

  设置当评分等级发生改变时回调的监听器

  参数

  listener 监听器



EX:
score_RB.setOnRatingBarChangeListener
(new RatingBar.OnRatingBarChangeListener (){

public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromUser) { }

} );





1.8)

  protected synchronized void onMeasure
(int widthMeasureSpec, int heightMeasureSpec)

  权衡 view 和 content 来决定它的宽度和高度的整齐。
它被measure(int, int) 调用 并且应该被子类所覆盖,
以便提供准确高效的布局测量。

  规定: 当覆盖这个方法的时候,
你必须调用 setMeasuredDimension(int, int)
以便存储精确的视图的宽和高。
如果不这样做的话将触发llegalStateException异常,
被函数 measure(int, int)抛出。
调用父类 onMeasure(int, int)是合理的。

  尺寸的基本类的实现默认是背景大小,
除非通过MeasureSpec允许大的尺寸。
子类应该覆盖 onMeasure(int, int) 以便提供更好的布局大小。

如果这个方法被覆盖,
子类应该负责确保标准的宽和高至少是视图的最小宽度和高度的值
(分别为getSuggestedMinimumHeight()
和 getSuggestedMinimumWidth()两方法)。

    参数

    widthMeasureSpec
受主窗口支配的水平空间要求。
这个需求通过 View.MeasureSpec.进行编码。

      heightMeasureSpec
受主窗口支配的垂直空间要求。
这个需求通过 View.MeasureSpec.进行编码。





2)SeekBar

============================


=======
LayoutInflater
=======


public abstract class
LayoutInflater
extends Object
java.lang.Object
android.view.LayoutInflater




Instantiates a layout XML file into
its corresponding View objects

把一个View的对象与XML布局文件关联并实例化
View的对象实例化之后,通过findViewById()
查找布局文件中的指定Id的组件



LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);




EX:
LayoutInflater inflater = (LayoutInflater)XhulooActivity_weatherreport.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

// 使用View的对象itemView与list_item.xml关联
View itemView = inflater.inflate(R.layout.list_item, null);

// 通过findViewById()方法实例R.layout.item内各组件
TextView title = (TextView) itemView.findViewById(R.id.itemTitle);
title.setText(strTitle);
TextView text = (TextView) itemView.findViewById(R.id.itemText);
text.setText(strText);
ImageView image = (ImageView) itemView.findViewById(R.id.itemImage);
image.setImageResource(resId);









=========
KeyEvent
=========
public class
KeyEvent
extends InputEvent
implements Parcelable







===============
Animation动画
================
java.lang.Object
android.view.animation.Animation



Abstraction for an Animation that can be applied to
Views, Surfaces, or other objects.
See the animation package description file.



Known Direct Subclasses

AlphaAnimation, 透明度动画
AnimationSet, 平移动画
RotateAnimation,旋转动画
ScaleAnimation, 缩放动画
TranslateAnimation



1)

public void setDuration (long durationMillis)
Since: API Level 1

How long this animation should last.
The duration cannot be negative.

Related XML Attributes

android:duration

Parameters
durationMillis Duration in milliseconds

Throws
IllegalArgumentException if the duration is < 0











==========
RotateAnimation
==========

java.lang.Object
android.view.animation.Animation
android.view.
animation.RotateAnimation



旋转动画

控制对象的旋转动画。这种旋转发生INT X-Y平面。
你可以指定点,以使用为中心




public RotateAnimation
(float fromDegrees,
float toDegrees,
int pivotXType,
float pivotXValue,
int pivotYType,
float pivotYValue)

Since: API Level 1

Constructor to use when building a RotateAnimation from code




Parameters



fromDegrees Rotation offset to apply at the start of the animation.
旋转的开始角度
旋转偏移在动画开始

toDegrees Rotation offset to apply at the end of the animation.
旋转的结束角度
旋转偏移适用于动画结束


pivotXType Specifies how pivotXValue should be interpreted.
One of
Animation.ABSOLUTE, 具体的
Animation.RELATIVE_TO_SELF,相对于自身
Animation.RELATIVE_TO_PARENT.相对于父控件
X轴的伸缩模式


pivotXValue The X coordinate of the point about which the object
is being rotated, specified as an absolute number
where 0 is the left edge.
This value can either be an absolute number if
pivotXType is ABSOLUTE, or a percentage
(where 1.0 is 100%) otherwise.
X坐标的伸缩值


pivotYType Specifies how pivotYValue should be interpreted.
One of Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF,
or Animation.RELATIVE_TO_PARENT.
Y轴的伸缩模式


pivotYValue The Y coordinate of the point about which the object
is being rotated, specified as an absolute number
where 0 is the top edge.
This value can either be an absolute number if
pivotYType is ABSOLUTE,
or a percentage (where 1.0 is 100%) otherwise.
Y坐标的伸缩值


















































-------------------------------------------------
-------------------------------------------------

======
Toast
extends Object
java.lang.Object
android.widget.Toast
========

1)public Toast (Context context)
Since: API Level 1

Construct an empty Toast object.
You must call setView(View) before you can call show().

Parameters
context The context to use.
Usually your Application or Activity object.



- - -- -- - -- - - -- - -
2.0)makeText

public static Toast makeText
(Context context, int resId, int duration)
Since: API Level 1


Parameters
context The context to use.
Usually your Application or Activity object.
resId The resource id of the string
resource to use. Can be formatted text.

duration How long to display the message.
Either LENGTH_SHORT or LENGTH_LONG

Throws
if the resource can't be found.
Resources.NotFoundException


2.0.1)LENGTH_SHORT

public static final int LENGTH_SHORT
Since: API Level 1

Show the view or text notification
for a short period of time.
This time could be user-definable. This is the default.
See Also

setDuration(int)

Constant Value: 0 (0x00000000)



2.0.2)LENGTH_LONG

public static final int LENGTH_LONG
Since: API Level 1

Show the view or text notification
for a long period of time. This time could be user-definable.

See Also

setDuration(int)

Constant Value: 1 (0x00000001)






2.1)makeText

public static Toast makeText
(Context context, CharSequence text, int duration)
Since: API Level 1

Parameters
context The context to use.
Usually your Application or Activity object.

text The text to show. Can be formatted text.

duration How long to display the message.
Either LENGTH_SHORT or LENGTH_LONG







EX:
//1
Toast.makeText(this,"浮动小提示", Toast.LENGTH_LONG).show();

//2
Toast imgToast;
ImageView imgView;
imgView = new ImageView(this);
imgView.setImageResource(R.drawable.icon);
imgToast = new Toast(this);
imgToast.setView(imgView);
imgToast.setDuration(Toast.LENGTH_LONG);
imgToast.show();


1.默认效果

代码

Toast.makeText(getApplicationContext(), "默认Toast样式",
Toast.LENGTH_SHORT).show();



2.自定义显示位置效果

代码

toast = Toast.makeText(getApplicationContext(),
"自定义位置Toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();



3.带图片效果



代码

toast = Toast.makeText(getApplicationContext(),
"带图片的Toast", Toast.LENGTH_LONG);

toast.setGravity(Gravity.CENTER, 0, 0);

LinearLayout toastView = (LinearLayout) toast.getView();

ImageView imageCodeProject =
new ImageView(getApplicationContext());

imageCodeProject.setImageResource(R.drawable.icon);

toastView.addView(imageCodeProject, 0);

toast.show();




/*创建新Toast对象*/
new
this
Toast showImageToast=new Toast(this);
/*创建新ImageView对象*/
ImageView imageView=new ImageView(this);
/*从资源中获取图片*/
imageView.setImageResource(R.drawable. argon );
/*设置Toast上的View--(ImageView)*/
showImageToast.setView(imageView);
/*设置Toast显示时间*/
showImageToast.setDuration(Toast. LENGTH_LONG);
/*显示Toast*/
showImageToast.show();





4.完全自定义效果

代码

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom,
(ViewGroup) findViewById(R.id.llToast));
ImageView image = (ImageView) layout
.findViewById(R.id.tvImageToast);
image.setImageResource(R.drawable.icon);
TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
title.setText("Attention");
TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
text.setText("完全自定义Toast");
toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);//****
toast.show();



5.其他线程

代码

new Thread(new Runnable() {
public void run() {
showToast();
}
}).start();

---------------------


public void onClick(View v) {
Toast toast = null;
switch (v.getId()) {
ffgfdgdfg
case R.id.btnSimpleToast:
Toast.makeText(...).show();
break;

case R.id.***:
toast = Toast.makeText(getApplicationContext(),
"自定义位置Toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
break;

case R.id.btnSimpleToastWithImage:
...
toast.show();
break;

case R.id.btnCustomToast:
...
break;

case R.id.btnRunToastFromOtherThread:
new Thread(new Runnable() {
public void run() {
showToast();
}
}).start();
break;

}

}











- - -- - - - -- - - -- - - - - -- - -


BaseAdapter



void notifyDataSetChanged()
//通知数据变化了,告诉绑定Adapter的widget来更新UI






==============
ArrayAdapter适配器
=============
public class
ArrayAdapter
extends BaseAdapter
implements Filterable
java.lang.Object
android.widget.BaseAdapter
android.widget.ArrayAdapter<T>


推荐大家什么情况使用arrayadapter,
什么时候使用baseadapter。
当数量较多,比如超过100条或频繁动态增减时
使用arrayadapter可以方便控制ui,
通过setNotifyOnChanage方法,
如果比较简单仅仅呈现直接从
baseadapter更节省资源。



0)void notifyDataSetChanged()
//通知数据变化了,告诉绑定Adapter的widget来更新UI




1)add
public void add (T object)
Since: API Level 1

Adds the specified object at the end of the array.
Parameters
object The object to add at the end of the array.


EX:adapter.add("string1");





2)clear
void clear()
//清除所有元素

3)
static ArrayAdapter<CharSequence>
createFromResource
(Context context, int textArrayResId, int textViewResId)
//从layout资源构造arrayadapter


4)
Context getContext()
//获取实例



5)
int getCount()



6)
View getDropDownView
(int position, View convertView, ViewGroup parent)
//获取drop down的popup风格选择条目的内容,
参数1是位置,参数2可以通过强制转换直接获取本条的内容

7)
Filter getFilter()
//使用正则过滤数据

8)
T getItem(int position)
//获取单条内容

9)
long getItemId(int position)

10)
int getPosition(T item)
//通过内容获取是某条

11)
View getView(int position, View convertView, ViewGroup parent)


void insert(T object, int index)
//插入新条目到数组的index位置

12)



void remove(T object)
//移出一条从数组,这里并没有指定位置


void setDropDownViewResource(int resource)
//设置dropdown的layout风格

Sets the layout resource to create the drop down views.


void setNotifyOnChange(boolean notifyOnChange)

//本条是arrayadapter最强大的功能,处理大数据时使用该方法,
可以降低ui的处理量,刷新ui可以更快速,主要可以停止对
(add(T), insert(T, int), remove(T), clear() 的操作,
当然可以通过 notifyDataSetChanged().
或 setNotifyOnChange(true) 通知变化

void sort(Comparator<? super T> comparator)
//常用的排序,使用arrayadapter可以直接排序,十分方便
























======
Intent
========
java.lang.Object
android.content.Intent

import android.content.Intent;

执行某个操作的一个抽象描述

Intent 负责提供组件之间相互调用的相关信息传递,
实现调用者和被调用者之间的解耦。


Intent的属性:

----
Action ,对执行动作的描述


----
data ,是对执行动作所要操作的数据的描述

-----
catagory 类别,是被请求组件的额外描述信息

public static final String
CATEGORY_LAUNCHER =
"android.intent.category.LAUNCHER";

-------
extra 附加信息


1)public Intent putExtras (Intent src)
Since: API Level 1

Copy all extras in 'src' in to this intent.
Parameters
src Contains the extras to copy.



EX:
添加附加信息:
Bundle bundle = new Bundle();
intent.putExtras(bundle);

-------
component 组件,
显式指定Intent的目标组件的名称。
如果指定了component属性,
系统会直接使用它指定的组件,而非匹配查找。



IntentFilter来向系统说明
自己可以响应和处理那些Intent请求。
组件一般通过AndroidManifest.xml文件
的<Intent-Filter>描述



通过解析各种 intent,
从一个屏幕导航到另一个屏幕是很简单的。
当向前导航时,activity 将会调用
startActivity(Intent myIntent)方法。
然后,系统会在所有安装的应用程序中定义的 IntentFilter 中查找,
找到最匹配 myIntent 的 Intent 对应的 activity。
新的 activity 接收到 myIntent 的通知后,开始运行。
当 startActivity 方法被调用将触发解析 myIntent 的动作,
这个机制提供了两个关键好处

A、Activities 能够重复利用从其它组件中以
Intent 的形式产生的一个请求;

B、Activities 可以在任何时候被一个具有相同
IntentFilter 的新的 Activity 取代。



---------------------
1)setClass
public Intent setClass (Context packageContext, Class<?> cls)
Since: API Level 1



Parameters:

packageContext A Context of the application
package implementing this class.

cls The class name to set,
equivalent to setClassName
(context, cls.getName()).

Returns

Returns the same Intent object,
for chaining multiple calls into a single statement.

EX:
intent.setClass(Activity.this,Activity2.class);

- -- -- - - -- - - - - - - - - - - -
2)getIntent() 得到意图

This method is deprecated.这种方法已经过时了


Use parseUri(String, int) instead.



parseUri


public static Intent parseUri (String uri, int flags)
Since: API Level 4

Create an intent from a URI. This URI may encode the action,
category, and other intent fields, if it was returned by toUri(int).
If the Intent was not generate by toUri(),
its data will be the entire URI and its action will be ACTION_VIEW.

The URI given here must not be relative --
that is, it must include the scheme and full path.


Parameters

uri The URI to turn into an Intent.

flags Additional processing flags. Either 0 or URI_INTENT_SCHEME.

Returns

Intent The newly created Intent object.


Throws
URISyntaxException


----------
setComponent 设置组件

返回一个Class对象

public Intent setComponent (ComponentName component)
Since: API Level 1

(Usually optional) Explicitly set the component to handle the intent.



Parameters

component The name of the application component to handle the intent,
or null to let the system find one for you.

Returns

Returns the same Intent object,
for chaining multiple calls into a single statement.


EX:

//private ComponentName component;

//component = new ComponentName(this, MusicService.class);


Intent mIntent01 = new Intent
(wo.wocom.xwell.MusicService.PREVIOUS_ACTION);

mIntent01.setComponent(component);
startService(mIntent01);











--------------------------------------------------
Intent调用大全、系统自带Intent调用大全


1.从google搜索内容
Intent intent = new Intent();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"searchString")
startActivity(intent);

2.浏览网页
Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);

3.显示地图
Uri uri = Uri.parse("geo:38.899533,-77.036476");
Intent it = new Intent(Intent.Action_VIEW,uri);
startActivity(it);

4.路径规划
Uri uri = Uri.parse
("http://maps.google.com/maps?f=dsaddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");
Intent it = new Intent(Intent.ACTION_VIEW,URI);
startActivity(it);

5.拨打电话
Uri uri = Uri.parse("tel:xxxxxx");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);

6.调用发短信的程序
Intent it = new Intent(Intent.ACTION_VIEW);
it.putExtra("sms_body", "The SMS text");
it.setType("vnd.android-dir/mms-sms");
startActivity(it);

7.发送短信
Uri uri = Uri.parse("smsto:0800000123");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "The SMS text");
startActivity(it);
String body="this is sms demo";
Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", number, null));
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true);
startActivity(mmsintent);

8.发送彩信
Uri uri = Uri.parse("content://media/external/images/media/23");
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra("sms_body", "some text");
it.putExtra(Intent.EXTRA_STREAM, uri);
it.setType("image/png");
startActivity(it);
StringBuilder sb = new StringBuilder();
sb.append("file://");
sb.append(fd.getAbsoluteFile());
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mmsto", number, null));
// Below extra datas are all optional.
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());
intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent);
startActivity(intent);

9.发送Email
Uri uri = Uri.parse("mailto:xxx@abc.com");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(it);
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.setType("text/plain");
startActivity(Intent.createChooser(it, "Choose Email Client"));
Intent it=new Intent(Intent.ACTION_SEND);
String[] tos={"me@abc.com"};
String[] ccs={"you@abc.com"};
it.putExtra(Intent.EXTRA_EMAIL, tos);
it.putExtra(Intent.EXTRA_CC, ccs);
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.setType("message/rfc822");
startActivity(Intent.createChooser(it, "Choose Email Client"));

Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");
sendIntent.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));

10.播放多媒体
Intent it = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:///sdcard/song.mp3");
it.setDataAndType(uri, "audio/mp3");
startActivity(it);
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);

11.uninstall apk
Uri uri = Uri.fromParts("package", strPackageName, null);
Intent it = new Intent(Intent.ACTION_DELETE, uri);
startActivity(it);

12.install apk
Uri installUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);

13. 打开照相机
<1>Intent i = new Intent(Intent.ACTION_CAMERA_BUTTON, null);
this.sendBroadcast(i);
<2>long dateTaken = System.currentTimeMillis();
String name = createName(dateTaken) + ".jpg";
fileName = folder + name;
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, fileName);
values.put("_data", fileName);
values.put(Images.Media.PICASA_ID, fileName);
values.put(Images.Media.DISPLAY_NAME, fileName);
values.put(Images.Media.DESCRIPTION, fileName);
values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, fileName);
Uri photoUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

Intent inttPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
inttPhoto.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(inttPhoto, 10);

14.从gallery选取图片
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, 11);

15. 打开录音机
Intent mi = new Intent(Media.RECORD_SOUND_ACTION);
startActivity(mi);

16.显示应用详细列表
Uri uri = Uri.parse("market://details?id=app_id");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
//where app_id is the application ID, find the ID
//by clicking on your application on Market home
//page, and notice the ID from the address bar

刚才找app id未果,结果发现用package name也可以
Uri uri = Uri.parse("market://details?id=<packagename>");
这个简单多了

17.寻找应用
Uri uri = Uri.parse("market://search?q=pname:pkg_name");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
//where pkg_name is the full package path for an application

18.打开联系人列表
<1>
Intent i = new Intent();
i.setAction(Intent.ACTION_GET_CONTENT);
i.setType("vnd.android.cursor.item/phone");
startActivityForResult(i, REQUEST_TEXT);

<2>
Uri uri = Uri.parse("content://contacts/people");
Intent it = new Intent(Intent.ACTION_PICK, uri);
startActivityForResult(it, REQUEST_TEXT);

19.打开另一程序
Intent i = new Intent();
ComponentName cn = new ComponentName("com.yellowbook.android2",
"com.yellowbook.android2.AndroidSearch");
i.setComponent(cn);
i.setAction("android.intent.action.MAIN");
startActivityForResult(i, RESULT_OK);



//调用浏览器

Uri uri = Uri.parse("");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);


//显示某个坐标在地图上

Uri uri = Uri.parse("geo:38.899533,-77.036476");
Intent it = new Intent(Intent.Action_VIEW,uri);
startActivity(it);


//显示路径

Uri uri = Uri.parse
("http://maps.google.com/maps?
f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");
Intent it = new Intent(Intent.ACTION_VIEW,URI);
startActivity(it);


//拨打电话

Uri uri = Uri.parse("tel:10086");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);

Uri uri = Uri.parse("tel.10086");
Intent it =new Intent(Intent.ACTION_CALL,uri);
需要添加 <uses-permission id="android.permission.CALL_PHONE" />
这个权限到androidmanifest.xml


//发送短信或彩信

Intent it = new Intent(Intent.ACTION_VIEW);
it.putExtra("sms_body", "The SMS text");
it.setType("vnd.android-dir/mms-sms");
startActivity(it);


//发送短信

Uri uri = Uri.parse("smsto:10086");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "cwj");
startActivity(it);


//发送彩信

Uri uri = Uri.parse("content://media/external/images/media/23");
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra("sms_body", "some text");
it.putExtra(Intent.EXTRA_STREAM, uri);
it.setType("image/png");
startActivity(it);


//发送邮件
Uri uri = Uri.parse("mailto:android123@163.com");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(it);

Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, android123@163.com);
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.setType("text/plain");
startActivity(Intent.createChooser(it, "Choose Email Client"));

Intent it=new Intent(Intent.ACTION_SEND);
String[] tos={"me@abc.com"};
String[] ccs={"you@abc.com"};
it.putExtra(Intent.EXTRA_EMAIL, tos);
it.putExtra(Intent.EXTRA_CC, ccs);
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.setType("message/rfc822");
startActivity(Intent.createChooser(it, "Choose Email Client"));


//播放媒体文件

Intent it = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:///sdcard/cwj.mp3");
it.setDataAndType(uri, "audio/mp3");
startActivity(it);

Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);


//卸载APK

Uri uri = Uri.fromParts("package", strPackageName, null);
Intent it = new Intent(Intent.ACTION_DELETE, uri);
startActivity(it);


//卸载apk 2
Uri uninstallUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_DELETE, uninstallUri);


//安装APK
Uri installUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);


//播放音乐

Uri playUri = Uri.parse("/sdcard/download/sth.mp3");
returnIt = new Intent(Intent.ACTION_VIEW, playUri);


//发送附近

Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/cwj.mp3");
sendIntent.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));


//market上某个应用信,pkg_name就是应用的packageName

Uri uri = Uri.parse("market://search?q=pname:pkg_name");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);


//market上某个应用信息,app_id可以通过www网站看下

Uri uri = Uri.parse("market://details?id=app_id");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);


//调用搜索
Intent intent = new Intent();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"android123")
startActivity(intent);








==========================




===============
ComponentName 组件名称
===============
extends Object

public final class


java.lang.Object
android.content.ComponentName

组件名称,intent会根据component name
启动一个组件(activity,service,contentProvider)



1) public ComponentName (String pkg, String cls)
Since: API Level 1

Create a new component identifier.


Parameters
pkg The name of the package that the component exists in.
Can not be null.

cls The name of the class inside of pkg that implements the component.
Can not be null.



EX:

private ComponentName component;

component = new ComponentName(this,
MusicService.class);



--------------------
2)public ComponentName (Context pkg, Class<?> cls)
Since: API Level 1

Create a new component identifier from a Context and Class object.


Parameters


pkg A Context for the package implementing the component,
from which the actual package name will be retrieved.



cls The Class object of the desired component,
from which the actual class name will be retrieved.









=========================================

===============
ServiceConnection
===============


public interface

android.content.ServiceConnection

Known Indirect Subclasses
MediaScannerConnection



Interface for monitoring the state of an application service.
See Service and Context.bindService() for more information.



----------
1)
onServiceConnected

abstract void

onServiceConnected(ComponentName name, IBinder service)

Called when a connection to the Service has been established,
with the IBinder of the communication channel to the Service.





--------------
2)
onServiceDisconnected

abstract void

onServiceDisconnected(ComponentName name)

Called when a connection to the Service has been lost.





EX:


// private MusicService ms; //调用服务


// 连接对象 ServiceConnection在Context.bindService和context.unBindService()里用到
ServiceConnection msc = new ServiceConnection() {
//当bindService时,让TextView显示MyService里getSystemTime()的返回值

public void onServiceConnected(ComponentName name, IBinder ser) {

Log.i(TAG, "onServiceCon--PM_Xhuloo");
ms = ((MusicService.MyBinder)ser).getService(); // ser--onServiceConnected()的参数

Log.i(TAG, "onServiceConnected--PM_Xhuloo"+ms.getSystemTime());
music_PM_tv.setText("from MusicService :" +ms.getSystemTime());
//ms.getSystemTime()
}

public void onServiceDisconnected(ComponentName name) {
Log.i(TAG, "onServiceDiscon--PM_Xhuloo");

}
};











========================================================
IntentReceiver


当你希望你的应用能够对一个外部的事件
(如当电话呼入时,或者数据网络可用时,
或者到了晚上时)做出响
应,你可以使用一个 IntentReceiver。
虽然 IntentReceiver 在感兴趣的事件发生时,
会使用 NotificationManager
通知用户,但它并不能生成一个 UI。
IntentReceiver 在 AndroidManifest.xml 中注册,
但也可以在代码中使用
Context.registerReceiver()进行注册。
当一个 intentreceiver 被触发时,
你的应用不必对请求调用 intentreceiver,
系统会在需要的时候启动你的应用。
各种应用还可以通过使用
Context.broadcastIntent() 将它们自己的
intentreceiver 广播给其它应用程序。





Content Provider

用来解决在不同的应用包之间共享数据的工具。
所有被一个 Android 应用程序创建的偏好设置,
文件和数据库都是私有的。
为了和其他应用程序共享数据,
应用程序不得不创建一个 Content Provider
要回索其他应用程序的数据,
它自己的 Content Provider 必须被调用
Android 本地 Content Provider 包括:

CallLog:地址和接收到的电话信息
Contact.People.Phones:存储电话号码
Setting.System:系统设置和偏好设置
等等





Service


startService(Intent service) 后,
即使调用 startService()的进程结束,
Service 仍然还存在,知道有进程调用

stopService(),或者Service自己自杀(stopSelf())就没法

bindService()后,
Service 就和调用 bindService()的进程同生共死,
也就是说当调用 bindService()的进程死,
那么它 bind 的 Service 也要跟着被结束,
当然期间也可以调用 unbindService()让 Service 结束

两种方式混合使用时,比如说你 startService(),
我 bindService()了,
那么只有你 stopService()了而且我也 unbindService()了,
这个 Service 才会被结束。


=======================================================================


=======
Paint 画笔
=======

public class


Paint
extends Object
java.lang.Object
android.graphics.Paint



Known Direct Subclasses
TextPaint



------------
Constants 常量

1)
int ANTI_ALIAS_FLAG 位掩码标志启用抗锯齿

(因为高分辨率的信号以低分辨率表示或
无法准确运算出3D图形坐标定位时
所导致的图形混叠(aliasing)而产生的,
反锯齿技术能有效地解决这些问题)

-------
--------

1)setColor

public void setColor (int color)

Set the paint's color


Parameters
color

The new color (including alpha) to set in the paint.

----------
2) setStrokeJoin 设置联接外缘的形式

public void setStrokeJoin (Paint.Join join)
Since: API Level 1

Set the paint's Join.


Parameters

join set the paint's Join,
used whenever the paint's style is Stroke or StrokeAndFill.



Paint.Join

BEVEL The outer edges of a join meet with a straight line
联接外缘满足直线

MITER The outer edges of a join meet at a sharp angle
锐角

ROUND The outer edges of a join meet in a circular arc.
圆弧


--------

3)setStrokeCap 设置线条端点的形式

public void setStrokeCap (Paint.Cap cap)


Set the paint's Cap.


Parameters

cap

set the paint's line cap style,
used whenever the paint's style is Stroke or StrokeAndFill.


Paint.Cap

BUTT The stroke ends with the path, and does not project beyond it.

ROUND 半圆,在路径的末尾中心

SQUARE 正方形,中心在路径的末尾

--------
4) setStrokeWidth 设置画笔宽度

public void setStrokeWidth (float width)
Since: API Level 1

Set the width for stroking. Pass 0 to stroke in hairline mode.
Hairlines always draws a single pixel
independent of the canva's matrix.


Parameters
width set the paint's stroke width,
used whenever the paint's style is Stroke or StrokeAndFill.


---------------
5)setStyle

public void setStyle (Paint.Style style)
Since: API Level 1

Set the paint's style,
used for controlling how primitives' geometries are interpreted
(except for drawBitmap, which always assumes Fill).

Parameters

style The new style to set in the paint


Paint.Style
FILL

Geometry and text drawn with this style will be filled,
ignoring all stroke-related settings in the paint.

FILL_AND_STROKE

Geometry and text drawn with this style will be
both filled and stroked at the same time,
respecting the stroke-related fields on the paint.

STROKE

Geometry and text drawn with this style will be stroked,
respecting the stroke-related fields on the paint.






-----------------------------------------

=======
Path 路径
======

public class


Path

extends Object
java.lang.Object
android.graphics.Path

Path类封装了多个直线段,二次曲线,三次曲线组成的几何路径





















=====
Color
=====
public class
Color
extends Object
java.lang.Object
android.graphics.Color


Color.BLACK 黑色
Color.BLUE 蓝色
Color.CYAN 青绿色
Color.DKGRAY 灰黑色
Color.GRAY 灰色
Color.GREEN 绿色
Color.LTGRAY 浅灰色
Color.MAGENTA 红紫色
Color.RED 红色
Color.TRANSPARENT 透明
Color.WHITE 白色
Color.YELLOW 黄色


(1)获取颜色color的RGB属性

alpha(int color) 透 明 的 程 度
Return the alpha component of a color int.

blue(int color)
Return the blue component of a color int.

green(int color)
Return the green component of a color int.

red(int color)
Return the red component of a color int.



(2)根据RGB三个参数,
或者加上透明度参数合成得到color的值

parseColor(String colorString)

Parse the color string, and return the corresponding color-int.

rgb(int red, int green, int blue)
Return a color-int from red, green, blue components.


argb(int alpha, int red, int green, int blue)
Return a color-int from alpha, red, green, blue components.

Parameters
alpha Alpha component [0..255] of the color
red Red component [0..255] of the color
green Green component [0..255] of the color
blue Blue component [0..255] of the color


(3)RGB颜色值与HSV值的转换

HSV值
色相(H)hue是色彩的基本属性,就是平常所说的颜色名称,如红色、黄色等。
饱和度(S)saturation是指色彩的纯度,
越高色彩越纯,低则逐渐变灰,取0-100%的数值。
明度(V)value(色调),亮度(B),取0-100%。


HSVToColor(float[] hsv)
Convert HSV components to an ARGB color.


HSVToColor(int alpha, float[] hsv)
Convert HSV components to an ARGB color.


RGBToHSV(int red, int green, int blue, float[] hsv)
Convert RGB components to HSV.


colorToHSV(int color, float[] hsv)
Convert the argb color to its HSV components.





android.graphics.Typeface
int Style 类型
粗体
BOLD 粗斜体
BOLD_ITALIC
ITALIC 斜体
NORMAL 普通字体

Typeface 类型

DEFAULT 默认字体
DEFAULT_BOLD 默认粗体
MONOSPACE 单间隔字体
SANS_SERIF 无衬线字体
SERIF 衬线字体

Typeface.create(Typeface family,int style)
创建一个混合型新的字体:有 4*5 中搭配
Typeface.setTypeface (Typeface tf, int style)
设置一个混合型字体:有 4*5 中搭配
Typeface.setTypeface(Typeface tf)
设置一个只有 Typeface 风格的字体:有五种形式

==========================================







DisplayMetrics 类取得画面宽高






EX:

DisplayMetrics displaysMetrics=new DisplayMetrics();
//DisplayMetrics 一个描述普通显示信息的结构,例如显示大小、密度、字体尺寸

getWindowManager().getDefaultDisplay().getMetrics(displaysMetrics);
//getManager()获取显示定制窗口的管理器。
//获取默认显示Display对象
//通过 Display 对象的数据来初始化一个 DisplayMetrics 对象

String showSize="手机屏幕分辨率: \n"+
displaysMetrics.widthPixels+"*"+displaysMetrics.heightPixels;

TextView myShow=(TextView)findViewById(R.id. TextView01 );

myShow.setText(showSize);






===========
R.layout

http://developer.android.com/reference/android/R.layout.html

1)
public static final int simple_list_item_1
Since: API Level 1

Constant Value: 17367043 (0x01090003)
//系统本身list_item的布局

2)
public static final int simple_expandable_list_item_2
Since: API Level 1

Constant Value: 17367047 (0x01090007)

===========
android.util.Log



Log.v() Log.d() Log.i() Log.w() 以及 Log.e() 。
根据首字母对应VERBOSE,DEBUG,INFO, WARN,ERROR。


Ecilpse Logcat 没显示 window --Open persepctive




  1、Log.v 的调试颜色为黑色的,任何消息都会输出,
这里的v代表verbose累赘的意思,平时使用就是Log.v("","");


  2、Log.d的输出颜色是蓝色的,仅输出debug调试的意思,
但他会输出上层的信息,过滤起来可以通过DDMS的Logcat标签来选择.


  3、Log.i的输出为绿色,一般提示性的消息information,
它不会输出Log.v和Log.d的信息,但会显示i、w和e的信息


  4、Log.w的意思为橙色,可以看作为warning警告,
一般需要我们注意优化Android代码,同时选择它后还会输出Log.e的信息。


  5、Log.e为红色,可以想到error错误,
这里仅显示红色的错误信息,这些错误就需要我们认真的分析,查看栈的信息了。




EX:
private static final String TAG = "MyActivity";//定义在onCreate前
//MyActivity--当前的Activity名

Log.v(MyActivity.TAG, "index=" + i);


===============
android.util.FloatMath


static float ceil(float value)
Returns the float conversion of the most negative (i.e.

EX:
Math.ceil(99.1) = 100.0
Math.ceil(-99.1) = -99.0
Math.ceil(99.9) = 100.0
Math.ceil(-99.9) = -99.0

static float cos(float angle)
Returns the closest float approximation of the cosine of the argument.


static float floor(float value)
Returns the float conversion of the most positive (i.e.

EX:
Math.floor(99.1) = 99.0
Math.floor(-99.1) = -100.0
Math.floor(99.9) = 99.0
Math.floor(-99.9) = -100.0

static float sin(float angle)
Returns the closest float approximation of the sine of the argument.


static float sqrt(float value)
Returns the closest float approximation of the
square root of the argument.计算value的平方根

=================
android.util.DisplayMetrics


显示度量



EX:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);


DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
//获得手机的宽带和高度像素单位为px
int width_screen = dm.widthPixels;
int height_screen = dm.heightPixels;

float density_screen =dm.density;
//密度
float densityDpi_screen =dm.density;
//显示屏上显示的字体的缩放系数
float xdpi_screen =dm.xdpi;
//每英寸的屏幕在X维的确切物理像素。
float ydpi_screen =dm.ydpi;

String ScreenInfo_s =new String
("screeninfo:"+"分辨率:"+height_screen+"*"+width_screen
+"\n"+"密度density"+density_screen
+"\n"+"xdpi"+xdpi_screen
+"\n"+"ydpi"+ydpi_screen
);
====================================

=========
ArrayList
=========

java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.ArrayList<E>

public class
ArrayList
extends AbstractList<E>
implements Serializable Cloneable RandomAccess



1)clear()

Removes all elements from this ArrayList, leaving it empty.

EX:

ArrayList<String> items_AL = new ArrayList<String>();
items_AL.clear(); //清除ITEMS内容

2)isEmpty()
Returns if this Collection contains no elements.


3)get

public E get (int index)
Since: API Level 1

Returns the element at the specified location in this list.
Parameters
index the index of the element to return.
Returns

the element at the specified index.


















=============

R.drawable


extends Object
java.lang.Object
android.R.drawable


http://docs.since2006.com/android/2.1-drawables.php


int icon = android.R.drawable.arrow_down_float;



不完整

arrow_down_float

int ic_menu_add
int ic_menu_agenda
int ic_menu_always_landscape_portrait
int ic_menu_call
int ic_menu_camera
int ic_menu_close_clear_cancel
int ic_menu_compass
int ic_menu_crop
int ic_menu_day
int ic_menu_delete
int ic_menu_directions
int ic_menu_edit
int ic_menu_gallery
int ic_menu_help
int ic_menu_info_details
int ic_menu_manage
int ic_menu_mapmode
int ic_menu_month
int ic_menu_more
int ic_menu_my_calendar
int ic_menu_mylocation
int ic_menu_myplaces
int ic_menu_preferences
int ic_menu_recent_history
int ic_menu_report_image
int ic_menu_revert
int ic_menu_rotate
int ic_menu_save
int ic_menu_search
int ic_menu_send
int ic_menu_set_as
int ic_menu_share
int ic_menu_slideshow
int ic_menu_sort_alphabetically
int ic_menu_sort_by_size
int ic_menu_today
int ic_menu_upload
int ic_menu_upload_you_tube
int ic_menu_view
int ic_menu_week
int ic_menu_zoom


========================
package
android.hardware
=======================


Classes


-------
Sensor
-------
extends Object
java.lang.Object
android.hardware.Sensor
import android.hardware.Sensor;

方向传感器: Sensor.TYPE_ORIENTATION
加速度(重力)传感器: Sensor.TYPE_ACCELEROMETER (加速度)
光线传感器: Sensor.TYPE_LIGHT
磁场传感器: Sensor.TYPE_MAGNETIC_FIELD
距离(临近性)传感器: Sensor.TYPE_PROXIMITY
温度传感器: Sensor.TYPE_TEMPERATURE



1)public float getPower()
Since: API Level 3

Returns

the power in mA used by this sensor while in use




getMaximumRange () //最大射程传感器,在传感器的单位
getVendor () //这种传感器的供应商字符串
getName ()
getVersion ()
getResolution () //分辨率,分辨率的传感器,在传感器的单位


2)getType () //传感器的泛型类型

public int getType ()
Since: API Level 3

Returns

generic type of this sensor.




EX:
Sensor sensor=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);




-----------------------------------------------------

SensorEvent

import android.hardware.SensorEvent;






1)
public final float[] values
Since: API Level 3

The length and contents of the values array depends on which
sensor type is being monitored
(see also SensorEvent for a definition
of the coordinate system used).





1.1)重力

Sensor.TYPE_ACCELEROMETER:
All values are in SI units (m/s^2)

values[0]: Acceleration minus Gx on the x-axis

values[1]: Acceleration minus Gy on the y-axis

values[2]: Acceleration minus Gz on the z-axis

EX:

x=se.values[SensorManager.DATA_X];
y=se.values[SensorManager.DATA_Y];
z=se.values[SensorManager.DATA_Z];



1.2) 方向

Sensor.TYPE_ORIENTATION:
All values are angles in degrees.



values[0]:

Azimuth, angle between the magnetic north direction
and the y-axis, around the z-axis (0 to 359).
0=North, 90=East, 180=South, 270=West
方位角,磁北的方向和Y轴,绕Z轴(0到359)之间的角度。
0 =向北,90 =180=南,270=西东


values[1]:
Pitch, rotation around x-axis (-180 to 180),
with positive values when the z-axis moves toward the y-axis.
Pitch,绕x轴转,当z轴往y轴移时,值为正;反之为负)





values[2]:
Roll, rotation around y-axis (-90 to 90),
with positive values when the x-axis moves toward the z-axis.


(Roll,绕y轴转,当x轴往z轴移时,值为正;反之为负)




Note:

This definition is different from yaw,
pitch and roll used in aviation where the
X axis is along the long side of the plane (tail to nose).

Note:

This sensor type exists for legacy reasons,
please use getRotationMatrix() in conjunction
with remapCoordinateSystem() and getOrientation()
to compute these values instead.

Important note:

For historical reasons the roll angle
is positive in the clockwise direction
(mathematically speaking, it should be
positive in the counter-clockwise direction).
















--------------
SensorManager 传感器管理器
--------------
extends Object
java.lang.Object
android.hardware.SensorManager

import android.hardware.SensorManager;



SensorManager lets you access the device's sensors.
Get an instance(实例) of this class by calling
Context.getSystemService() with the argument SENSOR_SERVICE.


Constants

1)
public static final int DATA_X
Since: API Level 1

This constant is deprecated.
use Sensor instead.

Index of the X value in the array returned by
onSensorChanged(int, float[])
Constant Value: 0 (0x00000000)

2)
public static final int DATA_Y
Constant Value: 1 (0x00000001)

3)
public static final int DATA_Z
Constant Value: 2 (0x00000002)

4)public static final float STANDARD_GRAVITY
Since: API Level 1
系统设置的重力加速度标准值
Standard gravity (g) on Earth. This value is equivalent to 1G
Constant Value: 9.80665





----------
Public Methods

1)getDefaultSensor

public Sensor getDefaultSensor (int type)
Since: API Level 3

Use this method to get the default sensor for a given type.
Note that the returned sensor could be a composite sensor,
and its data could be averaged or filtered.
If you need to access the raw sensors use getSensorList.


Parameters
type of sensors requested

Returns
the default sensors matching the asked type.


-------------
2)registerListener 注册监听器

public boolean registerListener
(SensorEventListener listener, Sensor sensor, int rate)

Since: API Level 3

Registers a SensorEventListener for the given sensor.


-------
Parameters

listener A SensorEventListener object.

sensor The Sensor to register to.

rate The rate sensor events are delivered at.
This is only a hint to the system.
Events may be received faster or slower
than the specified rate. Usually events are received faster.
The value must be one of

SENSOR_DELAY_NORMAL, 取得倾斜度的时候使用(缺省)
SENSOR_DELAY_UI, 用户接口用
SENSOR_DELAY_GAME, 游戏用
or SENSOR_DELAY_FASTEST 在游戏想特别快的反应速度的时候使用




or, the desired delay between events in microsecond.
该在微秒事件之间所需的延迟

频率分析:
1、SensorManager.SENSOR_DELAY_FASTEST
频率:3hz——4Hz之间,
一般:4Hz。
解释:一秒钟执行4次。

2、SensorManager.SENSOR_DELAY_GAME
频率:30hz——45Hz之间,
一般:38Hz。
解释:一秒钟执行38次。

3、SensorManager.SENSOR_DELAY_NORMAL
频率:30hz——45Hz之间,
一般:38Hz。
解释:一秒钟执行38次。

4、SensorManager.SENSOR_DELAY_UI
频率:13hz——18Hz之间,
一般:15Hz。
解释:一秒钟执行15次。

---------
Returns

true if the sensor is supported and successfully enabled.


EX:

sm.registerListener(sel, sensor,SensorManager.SENSOR_DELAY_GAME);

//SensorEventListener sel=new SensorEventListener(){ //。。}
//SensorManager sm=(SensorManager) this.getSystemService(SENSOR_SERVICE);


















EX:
public class SensorActivity extends Activity, implements SensorEventListener {
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;

public SensorActivity() {
mSensorManager = (SensorManager)
getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.
getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

protected void onResume() {
super.onResume();
mSensorManager.registerListener(this,mAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
}

protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

public void onSensorChanged(SensorEvent event) {
}
}


















-----------------------------------------------------


Interfaces

-----------
SensorEventListener



import android.hardware.SensorEventListener;



--------------
1)onAccuracyChanged 传感器的精度已经改变时调用

public abstract void onAccuracyChanged
(Sensor sensor, int accuracy)


Called when the accuracy of a sensor has changed.

See SensorManager for details.
Parameters
accuracy The new accuracy of this sensor


-----------
2)onSensorChanged 传感器值

public abstract void onSensorChanged (SensorEvent event)


Called when sensor values have changed.

See SensorManager for details on possible sensor types.

See also SensorEvent.

NOTE: The application doesn't own the event
object passed as a parameter and therefore cannot hold on o it.
The object may be part of an internal pool
and may be reused by the framework.

Parameters

event the SensorEvent.







EX:

//获得重力感应硬件控制器

SensorManager sm=
(SensorManager) this.getSystemService(SENSOR_SERVICE);

Sensor sensor=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);


//添加重力感应侦听,并实现其方法,
SensorEventListener sel=new SensorEventListener(){
public void onSensorChanged(SensorEvent se) {
x=se.values[SensorManager.DATA_X];
y=se.values[SensorManager.DATA_Y];
z=se.values[SensorManager.DATA_Z];

TextView textView_sensor=(TextView)
findViewById(R.id.textView_sensor);
textView_sensor.setText("重力感应"+"x="+x+"y="+(int)y+"z="+(int)z);
}

public void onAccuracyChanged(Sensor arg0, int arg1) { }
};


//注册Listener,SENSOR_DELAY_GAME为检测的精确度,
sm.registerListener(sel, sensor,SensorManager.SENSOR_DELAY_GAME);





-- - - -- - - - - -- - - - -- - - - - - -- - - -




3)onAccuracyChanged(int sensor,int accuracy)

当传感器的准确性更改时。
参数包括两个整数:一个表示传感器,另一个表示该传感器新的准确值。

--------------------------





=======================================================

===========
MotionEvent 运动事件
============

mouse, pen, finger, trackball


public final class

MotionEvent

extends InputEvent
implements Parcelable


java.lang.Object
android.view.InputEvent
android.view.MotionEvent





1)getX 得到X轴坐标

public final float getX (int pointerIndex)
Since: API Level 5

对于给定的指针索引返回此事件的X坐标
(使用getPointerId(int)来找到这个索引指针标识符)。
全数字像素;
该值可以具有子像素精确的输入设备的一小部分。


参数

pointerIndex

生指数的指针来检索。
值可以是从0(第一个指针,该指针是向下)getPointerCount()-1。

See Also

AXIS_X



2)getY 得到Y轴标

public final float getY (int pointerIndex)
Since: API Level 5

Returns the Y coordinate of this event for the given pointer
index (use getPointerId(int) to find the pointer identifier for this index).
Whole numbers are pixels; the value may have a
fraction for input devices that are sub-pixel precise.



Parameters
pointerIndex Raw index of pointer to retrieve.
Value may be from 0 (the first pointer that is down)
to getPointerCount()-1.




3)getAction 得到动作


public final int getAction ()
Since: API Level 1


返回被执行的那种行动。
考虑使用getActionMasked()和的getActionIndex()
检索的独立的被标记动作和指针索引。

Return the kind of action being performed.
Consider using getActionMasked() and getActionIndex()
to retrieve the separate masked action and pointer index.


Returns

The action, such as
ACTION_DOWN or
the combination of ACTION_POINTER_DOWN
with a shifted pointer index.


EX:

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
}


------------------------


Constants


int ACTION_DOWN

A pressed gesture has started,
the motion contains the initial starting location.

运动的压制手势已经开始,包括最初的起始位置。

这也是一个很好的时间来检查区分二级和三级的按钮,
点击按钮的状态,并对其进行适当的处理。
getButtonState()来检索按钮的状态。





int ACTION_MOVE

A change has happened during a press gesture
(between ACTION_DOWN and ACTION_UP



int ACTION_UP


Constant for getActionMasked():
A pressed gesture has finished,
the motion contains the final release location
as well as any intermediate points
since the last down or move event.



















===========================


import java.io.File;

/*初始化一个File 对象,指定路径为/sdcard*/
File file = new File("/sdcard");


2)

public File[] listFiles ()
Since: API Level 1

Returns an array of files contained in the directory
represented by this file.
The result is null if this file is not a directory.
The paths of the files in the array are absolute
if the path of this file is absolute,
they are relative otherwise.


Returns

an array of files or null.










EX:
/*文件游览功能的
* 打开指定PATH
* 定义在外面*/
public ArrayList<String> open_path(String file_path,ArrayList<String> item){


File[] file_index_f = new File(file_path).listFiles(); //列出file_path下的文件

item.add(getString(R.string.to_top)); //最前添加一个

for (File file : file_index_f) {
//for (循环变量类型 循环变量名称 : 要被遍历的对象) 循环体
item.add(file.getPath());
}
return item;

}




/*文件游览功能*/
open_path("/",items_AL); //调用自定义函数,return items (ArrayList<String>)
final ArrayAdapter<String> fileList_ArrayAd =
new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,items_AL);
//items中的PATH加到ADAPTER(配适器)
file_index_LV.setAdapter(fileList_ArrayAd);

/*列表点击监听响应*/
file_index_LV.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {

String selectItem=new String
(parent.getAdapter().getItem(position).toString());

Toast.makeText(XhulooActivity_myplaces.this, "MP_flie_Toast:打开"
+selectItem, Toast.LENGTH_LONG).show();

items_AL.clear();
//清除ITEM内容
open_path(selectItem,items_AL);
fileList_ArrayAd.notifyDataSetChanged();
//通知数据改变,反应该刷新视图

} });






============================
============================

android.telephony


Classes

-------
CellLocation
----------
Abstract class that represents the location of the device.



-------------
NeighboringCellInfo
----------
Represents the neighboring cell information,
including Received Signal Strength and Cell ID location.



--------
PhoneNumberFormattingTextWatcher
---------
Watches a TextView and if a phone number is entered will format it.


-----------
PhoneNumberUtils
----------
Various utilities for dealing with phone number strings.



PhoneStateListener A listener class for monitoring changes in
specific telephony states on the device, including service state,
signal strength, message waiting indicator (voicemail), and others.



ServiceState Contains phone state and service related information.




SignalStrength Contains phone signal strength related information.




SmsManager Manages SMS operations such as sending data, text, and pdu SMS messages.



SmsMessage A Short Message Service message.



SmsMessage.SubmitPdu



TelephonyManager Provides access to information about the telephony services on the device.



======
Enums

SmsMessage.MessageClass SMS Class enumeration.


-----------------------------------------------------------------------

=================
TelephonyManager
extends Object
java.lang.Object
android.telephony.TelephonyManager
================




<!-- 联网权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 获取机型信息权限 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 获取短信发送权限 -->
<uses-permission android:name="android.permission.SEND_SMS" />





1)getDeviceId () 手机串号

public String getDeviceId ()
Since: API Level 1

Returns the unique device ID,
for example, the IMEI for GSM
and the MEID or ESN for CDMA phones.
Return null if device ID is not available.

Requires Permission: READ_PHONE_STATE




2)通话状态
public int getCallState ()
Since: API Level 1

Returns a constant indicating the
call state (cellular) on the device.




3)getDataActivity 数据活动状态

public int getDataActivity ()
Since: API Level 1

Returns a constant indicating the type
of activity on a data connection (cellular).

See Also

DATA_ACTIVITY_NONE
DATA_ACTIVITY_IN
DATA_ACTIVITY_OUT
DATA_ACTIVITY_INOUT
DATA_ACTIVITY_DORMANT 数据连接是活跃的,但物理链路是关闭 休眠




4)getDataState ()

public int getDataState () 获取数据连接状态
Since: API Level 1

Returns a constant indicating the current
data connection state (cellular).

See Also

DATA_CONNECTED 数据连接状态:已连接
DATA_CONNECTING 数据连接状态:正在连接
DATA_DISCONNECTED 数据连接状态:断开
DATA_SUSPENDED 数据连接状态:暂停

5)getDeviceSoftwareVersion
移动终端的软件版本,例如:GSM手机的IMEI/SV码

public String getDeviceSoftwareVersion ()
Since: API Level 1

Returns the software version number for the device,
for example, the IMEI/SV for GSM phones.
Return null if the software version is not available.

Requires Permission: READ_PHONE_STATE


6)getLine1Number () 返回手机号码,对于GSM网络来说即MSISDN

public String getLine1Number ()
Since: API Level 1

Returns the phone number string for line 1,
for example, the MSISDN for a GSM phone.
Return null if it is unavailable.

Requires Permission: READ_PHONE_STATE



7)getNeighboringCellInfo ()

public List<NeighboringCellInfo> getNeighboringCellInfo ()
Since: API Level 3

Returns the neighboring cell information of the device.
Returns

List of NeighboringCellInfo or null if info unavailable.

Requires Permission:
(@link android.Manifest.permission#ACCESS_COARSE_UPDATES}







8)getNetworkCountryIso

SIM卡运营商国家代码

public String getNetworkCountryIso ()
Since: API Level 1

Returns the ISO country code equivalent of the current
registered operator's MCC (Mobile Country Code).

Availability: Only when user is registered to a network.
Result may be unreliable on CDMA networks
(use getPhoneType() to determine if on a CDMA network).




9)
public String getNetworkOperator ()
Since: API Level 1

Returns the numeric name (MCC+MNC) of current registered operator.

Availability: Only when user is registered to a network.
Result may be unreliable on CDMA networks
(use getPhoneType() to determine if on a CDMA network).

返回目前的注册运营商的数字域名(MCC+ MNC)的。


10)
public String getNetworkOperatorName ()
Since: API Level 1

返回目前注册运营商的字母名称。

Returns the alphabetic name of current registered operator.

Availability: Only when user is registered to a network.
Result may be unreliable on CDMA networks
(use getPhoneType() to determine if on a CDMA network).


11)
public int getNetworkType ()
Since: API Level 1

Returns a constant indicating the radio technology
(network type) currently in use on the device for data transmission.

返回一个常量,表示目前在数据传输设备上使用的无线电技术(网络型)。

Returns

the network type

See Also

NETWORK_TYPE_UNKNOWN
NETWORK_TYPE_GPRS
NETWORK_TYPE_EDGE
NETWORK_TYPE_UMTS
NETWORK_TYPE_HSDPA
NETWORK_TYPE_HSUPA
NETWORK_TYPE_HSPA
NETWORK_TYPE_CDMA
NETWORK_TYPE_EVDO_0
NETWORK_TYPE_EVDO_A
NETWORK_TYPE_EVDO_B
NETWORK_TYPE_1xRTT
NETWORK_TYPE_IDEN
NETWORK_TYPE_LTE
NETWORK_TYPE_EHRPD
NETWORK_TYPE_HSPAP


12)
public int getPhoneType ()
Since: API Level 1

返回一个常量,表示设备的电话类型。
Returns a constant indicating the device phone type.
This indicates the type of radio used to transmit voice calls.

See Also

PHONE_TYPE_NONE
PHONE_TYPE_GSM
PHONE_TYPE_CDMA
PHONE_TYPE_SIP


13)

public String getSimCountryIso ()
Since: API Level 1

Returns the ISO country code equivalent
for the SIM provider's country code.

ISO国家代码相当于返回SIM卡供应商的国家代码




14)
public String getSimOperator ()
Since: API Level 1

SIM卡供应商MCC+MNC


Returns the MCC+MNC
(mobile country code + mobile network code)
of the provider of the SIM. 5 or 6 decimal digits.

Availability: SIM state must be SIM_STATE_READY
See Also

getSimState()



15)
public String getSimOperatorName ()
Since: API Level 1

Returns the Service Provider Name (SPN).
服务供应商名称

Availability: SIM state must be SIM_STATE_READY
See Also

getSimState()


16)
public String getSimSerialNumber ()
Since: API Level 1

Returns the serial number of the SIM, if applicable.
Return null if it is unavailable.
SIM卡的序列号,如适用。返回null,如果它是不可用的。

Requires Permission: READ_PHONE_STATE


17)SIM卡状态
public int getSimState ()
Since: API Level 1

Returns a constant indicating the state of the device SIM card.
See Also

SIM_STATE_UNKNOWN
SIM_STATE_ABSENT
SIM_STATE_PIN_REQUIRED
SIM_STATE_PUK_REQUIRED
SIM_STATE_NETWORK_LOCKED
SIM_STATE_READY

18)

public String getSubscriberId ()
Since: API Level 1

返回唯一的用户ID,例如,为GSM手机的IMSI
Returns the unique subscriber ID, for example,
the IMSI for a GSM phone. Return null if it is unavailable.

Requires Permission: READ_PHONE_STATE


19)

public String getVoiceMailAlphaTag ()
Since: API Level 1

Retrieves the alphabetic identifier
associated with the voice mail number.

Requires Permission: READ_PHONE_STATE



20)
public String getVoiceMailNumber ()
Since: API Level 1

Returns the voice mail number. Return null if it is unavailable.
撷取与语音信箱号码相关联的字母标识符

Requires Permission: READ_PHONE_STATE


21)
public boolean hasIccCard ()
Since: API Level 5

Returns

true if a ICC card is present



22)无线网络漫游
public boolean isNetworkRoaming ()
Since: API Level 1

Returns true if the device is considered roaming
on the current network, for GSM purposes.

Availability: Only when user registered to a network.



















EX:

TelephonyManager tm = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);





String telephone_info_s=new String
("手机串号:"+tm.getDeviceId()+"\n"
+"通话状态:"+tm.getCallState()+"\n"
+"数据活动状态:"+tm.getDataActivity()+"\n"
+"数据连接状态:"+tm.getDataState()+"\n"
+"终端软件版本:"+tm.getDeviceSoftwareVersion()+"\n"
+"手机号码:"+tm.getLine1Number()+"\n"
+NBCinfo_sb
+"运营商国别码:"+tm.getNetworkCountryIso()+"\n"
+"运营商数字域名MCC+MNC:"+tm.getNetworkOperator()+"\n"
+"目前注册运营商:"+tm.getNetworkOperatorName()+"\n"
+"网络类型:"+tm.getNetworkType()+"\n"
+"电话类型:"+tm.getPhoneType()+"\n"
+"SIM卡供应商代码:"+tm.getSimCountryIso()+"\n"
+"SIM卡供应商MCC+MNC:"+tm.getSimOperator()+"\n"
+"服务供应商名称:"+tm.getSimOperatorName()+"\n"
+"SIM卡序列号:"+tm.getSimSerialNumber()+"\n"
+"SIM卡状态:"+tm.getSimState()+"\n"
+"用户ID:"+tm.getSubscriberId()+"\n"
+"语音信箱标识符:"+tm.getVoiceMailAlphaTag()+"\n"
+"ICC card:"+tm.hasIccCard()+"\n"
+"无线网络漫游:"+tm.isNetworkRoaming ()
);





















------------------------------------------------------
===================
NeighboringCellInfo
===================

public class
NeighboringCellInfo
extends Object
implements Parcelable
java.lang.Object
android.telephony.NeighboringCellInfo



1)
public int describeContents ()
Since: API Level 3

Describe the kinds of special objects contained
in this Parcelable's marshalled representation.
Returns

a bitmask indicating the set of special object
types marshalled by the Parcelable.

2)
public int getCid ()
Since: API Level 3

Returns

cell id in GSM, 0xffff max legal value
UNKNOWN_CID if in UMTS or CDMA or unknown

3)

public int getLac ()
Since: API Level 5

Returns

LAC in GSM, 0xffff max legal value UNKNOWN_CID if in UMTS or CMDA or unknown


4)

public int getNetworkType ()
Since: API Level 5

Returns

Radio network type while neighboring cell location is stored.

Return

TelephonyManager.NETWORK_TYPE_UNKNOWN

means that the location information is unavailable.

TelephonyManager.NETWORK_TYPE_GPRS or TelephonyManager.NETWORK_TYPE_EDGE

means that Neighboring Cell information is stored for
GSM network,in which NeighboringCellInfo.getLac and
NeighboringCellInfo.getCid should be called to access location.

TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_HSDPA,
TelephonyManager.NETWORK_TYPE_HSUPA, or TelephonyManager.NETWORK_TYPE_HSPA

means that Neighboring Cell information is stored for UMTS network,
in which NeighboringCellInfo.getPsc should be called to access location.

5)手机扰码
public int getPsc ()
Since: API Level 5

Returns

Primary Scrambling Code in 9 bits format in UMTS,
0x1ff max value UNKNOWN_CID if in GSM or CMDA or unknown

6)获取邻居小区信号强度
public int getRssi ()
Since: API Level 3

Returns

received signal strength or UNKNOWN_RSSI if unknown For GSM,
it is in "asu" ranging from 0 to 31 (dBm = -113 + 2*asu)
0 means "-113 dBm or less" and 31 means "-51 dBm or greater"
For UMTS, it is the Level index of CPICH RSCP defined in TS 25.125










EX:
List<NeighboringCellInfo> infos=tm.getNeighboringCellInfo();
for(NeighboringCellInfo NBCinfo:infos){
//for(循环变量类型 循环变量名称 : 要被遍历的对象) 循环体
NBCinfo_sb.append("小区号"+NBCinfo.getCid()+
" LAC位置区域码:"+NBCinfo.getLac()+"\n"
+"网络类型:"+NBCinfo.getNetworkType()
+"主扰码"+NBCinfo.getPsc()+"\n"
+"信号强度"+NBCinfo.getRssi()+"\n\n");

}







===========================
Settings.Secure
===========================



extends Settings.NameValueTable
java.lang.Object
android.provider.Settings.NameValueTable
android.provider.Settings.Secure




Secure system settings, containing system preferences that
applications can read but are not allowed to write.
These are for preferences that the user must explicitly
modify through the system UI or
specialized APIs for those values,
not modified directly by applications.





------------
0)Summary

0.1)

ANDROID_ID

public static final String ANDROID_ID

Since: API Level 3

A 64-bit number (as a hex string) that is randomly
generated on the device's first boot and should
remain constant for the lifetime of the device.
(The value may change if a factory reset
is performed on the device.)

Constant Value: "android_id"




0.2)BACKGROUND_DATA 背景数据(Background data )

public static final String BACKGROUND_DATA

Since: API Level 3
Whether background data usage is allowed by the user.
See ConnectivityManager for more info.

Constant Value: "background_data"


0.3)public static final String BLUETOOTH_ON

Since: API Level 3
Whether bluetooth is enabled/disabled 0=disabled. 1=enabled.

Constant Value: "bluetooth_on"











0.4)
public static final String INSTALL_NON_MARKET_APPS

Since: API Level 3
Whether the package installer should allow installation
of apps downloaded from sources other than Google Play.

1 = allow installing from other sources

0 = only allow installing from Google Play

Constant Value: "install_non_market_apps"



0.5)
public static final String SYS_PROP_SETTING_VERSION

Since: API Level 3
Constant Value: "sys.settings_secure_version"





0.6)WIFI


public static final String

WIFI_MAX_DHCP_RETRY_COUNT

Since: API Level 3
The maximum number of times we will retry a connection
to an access point for which we have failed in acquiring
an IP address from DHCP.
A value of N means that we will make N+1 connection attempts in all.

Constant Value: "wifi_max_dhcp_retry_count"






public static final String

WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS

Since: API Level 3
Maximum amount of time in milliseconds to hold a wakelock
while waiting for mobile data connectivity to
be established after a disconnect from Wi-Fi.

Constant Value: "wifi_mobile_data_transition_wakelock_timeout_ms"






public static final String

WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON

Since: API Level 3
Whether to notify the user of open networks.

If not connected and the scan results have an open network,
we will put this notification up.
If we attempt to connect to a network or the open network(s) disappear,
we remove the notification. When we show the notification,
we will not show it again for WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY time.

Constant Value: "wifi_networks_available_notification_on"






public static final String

WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY

Since: API Level 3
Delay (in seconds) before repeating the Wi-Fi networks
available notification. Connecting to a network will reset the timer.

Constant Value: "wifi_networks_available_repeat_delay"




public static final String

WIFI_NUM_OPEN_NETWORKS_KEPT

Since: API Level 3
When the number of open networks exceeds this number,
the least-recently-used excess networks will be removed.

Constant Value: "wifi_num_open_networks_kept"




public static final String

WIFI_ON

Since: API Level 3
Whether the Wi-Fi should be on.
Only the Wi-Fi service should touch this.

Constant Value: "wifi_on"





public static final String


WIFI_WATCHDOG_ACCEPTABLE_PACKET_LOSS_PERCENTAGE

Since: API Level 3
The acceptable packet loss percentage
(range 0 - 100) before trying another AP on the same network.

Constant Value: "wifi_watchdog_acceptable_packet_loss_percentage"





public static final String

WIFI_WATCHDOG_AP_COUNT

Since: API Level 3
The number of access points required
for a network in order for the watchdog to monitor it.

Constant Value: "wifi_watchdog_ap_count"







public static final String

WIFI_WATCHDOG_BACKGROUND_CHECK_DELAY_MS

Since: API Level 3
The delay between background checks.

Constant Value: "wifi_watchdog_background_check_delay_ms"




public static final String

WIFI_WATCHDOG_BACKGROUND_CHECK_ENABLED

Since: API Level 3
Whether the Wi-Fi watchdog is enabled for
background checking even after it thinks
the user has connected to a good access point.

Constant Value: "wifi_watchdog_background_check_enabled"




public static final String


WIFI_WATCHDOG_BACKGROUND_CHECK_TIMEOUT_MS

Since: API Level 3
The timeout for a background ping

Constant Value: "wifi_watchdog_background_check_timeout_ms"







public static final String

WIFI_WATCHDOG_INITIAL_IGNORED_PING_COUNT

Since: API Level 3
The number of initial pings to perform
that *may* be ignored if they fail. Again,
if these fail, they will *not* be used in
packet loss calculation. For example,
one network always seemed to time out for
the first couple pings, so this is set to 3 by default.

Constant Value: "wifi_watchdog_initial_ignored_ping_count"





public static final String


WIFI_WATCHDOG_MAX_AP_CHECKS

Since: API Level 3
The maximum number of access points (per network)
to attempt to test. If this number is reached,
the watchdog will no longer monitor the initial
connection state for the network.
This is a safeguard for networks containing
multiple APs whose DNS does not respond to pings.

Constant Value: "wifi_watchdog_max_ap_checks"






public static final String

WIFI_WATCHDOG_ON

Since: API Level 3
Whether the Wi-Fi watchdog is enabled.

Constant Value: "wifi_watchdog_on"




public static final String

WIFI_WATCHDOG_PING_COUNT

Since: API Level 3
The number of pings to test if
an access point is a good connection.

Constant Value: "wifi_watchdog_ping_count"




public static final String


WIFI_WATCHDOG_PING_DELAY_MS

Since: API Level 3
The delay between pings.

Constant Value: "wifi_watchdog_ping_delay_ms"




public static final String


WIFI_WATCHDOG_PING_TIMEOUT_MS

Since: API Level 3
The timeout per ping.

Constant Value: "wifi_watchdog_ping_timeout_ms"




public static final String


WIFI_WATCHDOG_WATCH_LIST

Since: API Level 3
A comma-separated list of SSIDs
for which the Wi-Fi watchdog should be enabled.

Constant Value: "wifi_watchdog_watch_list"





------------------

1)
synchronized static String

getString(ContentResolver resolver, String name)

Look up a name in the database.



Parameters


resolver to access the database with
name to look up in the table



Returns
the corresponding value, or null if not present


EX:
androidId = "" +
android.provider.Settings.Secure.
getString
(getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);


=====================================================




























































































================
================
package
org.apache.http
================
================



The core interfaces and classes of the HTTP components.
These deal with the fundamental things required for
using the HTTP protocol, such as representing
a message including it's headers and optional entity,
and connections over which messages are sent.
In order to prepare messages before sending or after receiving,
there are interceptors for requests and responses.

-------
Interfaces


ConnectionReuseStrategy Interface for deciding whether a connection
should be kept alive.

FormattedHeader An HTTP header which is already formatted.

Header Represents an HTTP header field.

HeaderElement One element of an HTTP header value.

HeaderElementIterator A type-safe iterator for HeaderElement objects.

HeaderIterator A type-safe iterator for Header objects.

HttpClientConnection An HTTP connection for use on the client side.

HttpConnection A generic HTTP connection,
useful on client and server side.

HttpConnectionMetrics The point of access to the statistics
of an HttpConnection.

HttpEntity An entity that can be sent or received
with an HTTP message.

HttpEntityEnclosingRequest A request with an entity.

HttpInetConnection An HTTP connection over the Internet Protocol (IP).

HttpMessage A generic HTTP message.

HttpRequest An HTTP request.

HttpRequestFactory A factory for HttpRequest objects.

HttpRequestInterceptor Processes a request.

HttpResponse An HTTP response.

HttpResponseFactory A factory for HttpResponse objects.

HttpResponseInterceptor Processes a response.

HttpServerConnection An HTTP connection for use on the server side.

HttpStatus Constants enumerating the HTTP status codes.

NameValuePair A simple class encapsulating an attribute/value pair.

ReasonPhraseCatalog Interface for obtaining reason phrases for HTTP
status codes.

RequestLine The first line of an HttpRequest.

StatusLine Represents a status line as returned from
a HTTP server.

TokenIterator An iterator for String tokens.



--------
Classes


HttpHost Holds all of the variables needed to describe
an HTTP connection to a host.

HttpVersion Represents an HTTP version, as specified in RFC 2616.

ProtocolVersion Represents a protocol version, as specified in RFC 2616.





-------
Exceptions


ConnectionClosedException Indicates that a connection has been closed.

HttpException Signals that an HTTP exception has occurred.

MalformedChunkCodingException Signals a malformed chunked stream.

MethodNotSupportedException Indicates that an HTTP method is not
supported.

NoHttpResponseException Signals that the target server failed to
respond with a valid HTTP response.

ParseException Indicates a parse error.

ProtocolException Signals that an HTTP protocol violation
has occurred.

UnsupportedHttpVersionException Indicates an unsupported version of the HTTP
protocol.


---------------------------------------------







============================================

=============
MediaPlayer
=============




public class

extends Object
java.lang.Object
android.media.MediaPlayer





MediaPlayer流程图

http://developer.android.com/images/mediaplayer_state_diagram.gif





1)reset 重置为未初始化


public void reset ()
Since: API Level 1

Resets the MediaPlayer to its uninitialized state.
After calling this method,
you will have to initialize it again
by setting the data source and calling prepare().


2)
setDataSource


public void setDataSource (String path)
Since: API Level 1

Sets the data source (file-path or http/rtsp URL) to use.


Parameters
path the path of the file, or the http/rtsp URL of the stream you want to play



Throws
IllegalStateException if it is called in an invalid state




---------------
public void setDataSource
(Context context, Uri uri, Map<String, String> headers)


Sets the data source as a content Uri.


Parameters
context the Context to use when resolving the Uri
uri the Content URI of the data you want to play
headers the headers to be sent together with the request for the data


Throws
IllegalStateException if it is called in an invalid state
IOException
IllegalArgumentException
SecurityException



3)
prepare

Prepares the player for playback, synchronously.
After setting the datasource and the display surface,
you need to either call prepare() or prepareAsync().
For files, it is OK to call prepare(),
which blocks until MediaPlayer is ready for playback.



Throws
IllegalStateException if it is called in an invalid state
IOException



4)
start

Starts or resumes playback.
If playback had previously been paused,
playback will continue from where it was paused.
If playback had been stopped,
or never started before, playback will start at the beginning.


Throws
IllegalStateException if it is called in an invalid state


5)
release


public void release ()

释放MediaPlayer对象与此相关的资源




EX:




public void inite() {
MediaPlayer_MS.reset();

try {

MediaPlayer_MS.setDataSource("/sdcard/music/勉强幸福_林宥嘉 .mp3");
//MediaPlayer_MS.setDataSource(dataSource);
MediaPlayer_MS.prepare();
MediaPlayer_MS.start();

} catch (IllegalArgumentException e1) { e1.printStackTrace();
} catch (IllegalStateException e1) { e1.printStackTrace();
} catch (IOException e1) { e1.printStackTrace(); }











































































































=========================================================
创建数据库

Context.createDatabase(String name,int version ,int mode,CursorFactory factory)创建一个新的数据库并
返回一个 SQLiteDatabase 对象
假如数据库不能被创建,则抛出 FileNotFoundException 异常
新创建 SQLite 数据库方法
new
SQLiteDatabase mydataBase=SQLiteDatabase. create (new CursorFactory(){
//创建一个数据库
//工厂类,一个可选工厂类,当查询时调用来实例化一个光标
@Override
public Cursor newCursor(SQLiteDatabase db,
SQLiteCursorDriver masterQuery, String editTable,
SQLiteQuery query) {
// TODO Auto-generated method stub
return null
null;
}
});
SQLiteDatabase myDataBase=this
this.openOrCreateDatabase("myDataBase.db",
MODE_PRIVATE, new CursorFactory(){
//创建新的数据库,名称myDatabase,模式MODE_PRIVATE,鼠标工厂
//工厂类,一个可选工厂类,当查询时调用来实例化一个光标
@Override
public Cursor newCursor(SQLiteDatabase db,
SQLiteCursorDriver masterQuery, String editTable,
SQLiteQuery query) {
// TODO Auto-generated method stub
return null
null;
}
});
删除数据库


Context.deleteDatabase(String name)删除指定名称的数据库
假如数据库成功删除则返回 true,失败则为 false(例如数据库不存在)
//删除指定名称的数据库
this
this.deleteDatabase("myDatabase.db");
打开数据库


Context.openDatabase(String file,CursorFactory factory) 打 开 一 个 存 在 的 数 据 库 并 返 回 一 个
SQLiteDatabase 对象
如果数据库不存在则抛出 FileNotFoundException 异常
//创建一个名为:myDataBase的数据库,后缀为.db
this
SQLiteDatabase my_DataBase=this
this.openOrCreateDatabase("myDateBase.db",
MODE_PRIVATE, null
null);
my_DataBase.close();//不要忘记关闭数据库
非查询 SQL 指令



1
SQLiteDatabase.execSQL(String sql)可以用来执行非查询 SQL 指令,这些指令没有结果
包括:CREATE TABLE / DROP TABLE / INSERT 等等
例如:
创建一个名为"test"并带两个参数的表
//创建一个名为"test"并带两个参数的表
my_DataBase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY,
someNumber INTERGER);");


2 在数据库中插入一个元组
//在数据库中插入一个元组
my_DataBase.execSQL("INSERT INTO test (_id,someNumber) values(1,8);");




3 删除表
//删除表
my_DataBase.execSQL("DROP TABLE test");
-
查询 SQL 指令-游标 Cursors
Android 使用游标(Cursors)来导航浏览查询结果
游标(Cursors)被 android.database.Cursor 对象来描述
一个游标(Cursors)是一个简单的指针,它从查询结果的一个元组跳到下一个元组(或是前一个或是第
一个或是......)
游标(Cursors)在它定位位置的那一刻返回元组数据
表 test





_id someNumber
1 8
2 10
3 2


//为了创建一个Cursor(游标),必须执行一个查询,要么通过SQL使用rawQuery()方法
//或是更精心设计的方法,像query()方法
Cursor cur=my_DataBase.rawQuery("SELECT * FORM test", null
null);
null
if
if(cur!=null
null){//游标不为空
//返回给定名称的列的基于0开始的index,如果该属性列不存在则返回-1
//通过它们的index来检索属性值
int numColumn=cur.getColumnIndex("someNumber");
if
if(cur.moveToFirst()){
//cur.moveToFirst()让游标指向第一行,如果游标指向第一行,则返回true
do {
int num=cur.getInt(numColumn);//获得当前行该属性的值
/*Cursor提供了不同的方法来回索不同的数据类型
例如getInt(int index)/getString(int index)等等*/
/*做一些事情*/
} while (cur.moveToNext());
/*游标移动到下一行,如果游标已经通过了结果集中的最后,
即没有行可以移动时,则返回false*/
//其他可能移动的是 previous() 和first()方法
}
}



=========================================





====================================

Android Permission 大全

====================================


Android SDK 1.0 访问权限许可





http://developer.android.com/reference
/android/Manifest.permission.html

http://developer.android.com/reference
/android/Manifest.permission_group.html


android.permission-group.ACCOUNTS

android.permission-group.COST_MONEY

android.permission-group.DEVELOPMENT_TOOLS

android.permission-group.HARDWARE_CONTROLS

android.permission-group.LOCATION

android.permission-group.MESSAGES

android.permission-group.NETWORK

android.permission-group.PERSONAL_INFO

android.permission-group.PHONE_CALLS

android.permission-group.STORAGE

android.permission-group.SYSTEM_TOOLS







程序执行需要读取到安全敏感项
必需在 androidmanifest.xml 中声明相关权限请求, 完整列表如下:


android.permission.ACCESS_CHECKIN_PROPERTIES

允许读写访问"properties"表在 checkin 数据库中,
改值可以修改上传( Allows read/write access to the "properties"
table in the checkin database, to change values that get uploaded)


android.permission.ACCESS_COARSE_LOCATION

允许一个程序访问 CellID 或 WiFi 热点来获取粗略的位置
(Allows an application to access coarse
(e.g., Cell-ID,WiFi) location)
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />



android.permission.ACCESS_FINE_LOCATION

允许一个程序访问精良位置(如 GPS)
(Allows an application to access fine (e.g., GPS) location)


android.permission.ACCESS_LOCATION_EXTRA_COMMANDS

允许应用程序访问额外的位置提供命令
(Allows an application to access extra location provider commands)


android.permission.ACCESS_MOCK_LOCATION

允许程序创建模拟位置提供用于测试
(Allows an application to create mock location providers for testing)


android.permission.ACCESS_NETWORK_STATE

允许程序访问有关 GSM 网络信息
(Allows applications to access information about networks)


android.permission.ACCESS_SURFACE_FLINGER

允许程序使用 SurfaceFlinger 底层特性
(Allows an application to use SurfaceFlinger's low level features)


android.permission.ACCESS_WIFI_STATE

允许程序访问 Wi-Fi 网络状态信息
(Allows applications to access information about Wi-Fi networks)


android.permission.ADD_SYSTEM_SERVICE

允许程序发布系统级服务
(Allows an application to publish system-level services).


android.permission.BATTERY_STATS

允许程序更新手机电池统计信息
(Allows an application to update the collected battery statistics)


android.permission.BLUETOOTH

允许程序连接到已配对的蓝牙设备
(Allows applications to connect to paired bluetooth devices)


android.permission.BLUETOOTH_ADMIN

允许程序发现和配对蓝牙设备
(Allows applications to discover and pair bluetooth devices)


android.permission.BRICK

请求能够禁用设备(非常危险)
(Required to be able to disable the device (very *erous!).)


android.permission.BROADCAST_PACKAGE_REMOVED

允许程序广播一个提示消息在一个应用程序包已经移除后
(Allows an application to broadcast a notification that
an application package has been removed)


android.permission.BROADCAST_STICKY

允许一个程序广播常用 intents
(Allows an application to broadcast sticky intents)


android.permission.CALL_PHONE

允许一个程序初始化一个电话拨号不需通过拨号用户界面需要用户确认
(Allows an application to initiate a
phone call without going through the Dialer
user interface for the user to confirm the call being placed.)


android.permission.CALL_PRIVILEGED

允许一个程序拨打任何号码,
包含紧急号码无需通过拨号用户界面需要用户确认
(Allows an application to call
any phone number,
including emergency numbers,
without going through the Dialer user
interface for the user to
confirm the call being placed)


android.permission.CAMERA

请求访问使用照相设备
(Required to be able to access the camera device. )


android.permission.CHANGE_COMPONENT_ENABLED_STATE

允许一个程序是否改变一个组件或其他的启用或禁用
(Allows an application to change whether an application
component (other than its own) is enabled or not. )


android.permission.CHANGE_CONFIGURATION

允许一个程序修改当前设置,
如本地化
(Allows an application to modify the current configuration,
such as locale. )


android.permission.CHANGE_NETWORK_STATE

允许程序改变网络连接状态
(Allows applications to change network connectivity state)


android.permission.CHANGE_WIFI_STATE
允许程序改变 Wi-Fi 连接状态
(Allows applications to change Wi-Fi connectivity state)


android.permission.CLEAR_APP_CACHE
允许一个程序清楚缓存从所有安装的程序在设备中
(Allows an application to clear the caches of all installed
applications on the device. )


android.permission.CLEAR_APP_USER_DATA
允许一个程序清除用户设置(Allows an application to clear user data)


android.permission.CONTROL_LOCATION_UPDATES
允许启用禁止位置更新提示从无线模块
(Allows enabling/disabling location update notifications from the radio. )


android.permission.DELETE_CACHE_FILES
允许程序删除缓存文件(Allows an application to delete cache files)


android.permission.DELETE_PACKAGES
允许一个程序删除包(Allows an application to delete packages)


android.permission.DEVICE_POWER
允许访问底层电源管理(Allows low-level access to power management)


android.permission.DIAGNOSTIC
允许程序 RW 诊断资源
(Allows applications to RW to diagnostic resources. )


android.permission.DISABLE_KEYGUARD
允许程序禁用键盘锁
(Allows applications to disable the keyguard )


android.permission.DUMP
允许程序返回状态抓取信息从系统服务
(Allows an application to retrieve state dump information from system
services.)


android.permission.EXPAND_STATUS_BAR
允许一个程序扩展收缩在状态栏,android
开发网提示应该是一个类似 Windows Mobile 中的托盘程序(Allows an
application to expand or collapse the status bar. )


android.permission.FACTORY_TEST
作为一个工厂测试程序,运行在 root 用户
(Run as a manufacturer test application, running as the root user. )


android.permission.FLASHLIGHT
访问闪光灯,android 开发网提示 HTC Dream 不包含闪光灯
(Allows access to the flashlight )


android.permission.FORCE_BACK
允许程序强行一个后退操作是否在顶层 activities
(Allows an application to force a BACK operation on whatever is
the top activity. )


android.permission.FOTA_UPDATE
暂时不了解这是做什么使用的,android 开发网分析可能是一个预留权限.


android.permission.GET_ACCOUNTS

访问一个帐户列表在 Accounts Service 中
(Allows access to the list of accounts in the Accounts Service)


android.permission.GET_PACKAGE_SIZE

允许一个程序获取任何 package 占用空间容量
(Allows an application to find out
the space used by any package. )


android.permission.GET_TASKS

允许一个程序获取信息有关当前或最近运行的任务,
一个缩略的任务状态,是否活动等等(Allows an
application to get information about the
currently or recently running tasks:
a thumbnail representation of the tasks,
what activities are running in it, etc.)

android.permission.HARDWARE_TEST
允许访问硬件(Allows access to hardware peripherals. )


android.permission.INJECT_EVENTS
允许一个程序截获用户事件如按键、触摸、轨迹球等等到一个时间流,
android 开发网提醒算是 hook 技术吧
(Allows an application to inject user events
(keys, touch, trackball) into the event
stream and deliver them to ANY
window.)


android.permission.INSTALL_PACKAGES
允许一个程序安装 packages(Allows an application to install packages. )


android.permission.INTERNAL_SYSTEM_WINDOW
允许打开窗口使用系统用户界面(Allows an application
to open windows that are for use by parts of the system
user interface. )


android.permission.INTERNET
允许程序打开网络套接字(Allows applications to open network sockets)


android.permission.MANAGE_APP_TOKENS
允许程序管理(创建、催后、z- order 默认向 z 轴推移)
程序引用在窗口管理器中(Allows an application to manage
(create, destroy, Z-order)
application tokens in the window manager. )


android.permission.MASTER_CLEAR
目前还没有明确的解释,android 开发网分析可能是清除一切数据,类似硬格机


android.permission.MODIFY_AUDIO_SETTINGS
允许程序修改全局音频设置(Allows an
application to modify global audio settings)



android.permission.MODIFY_PHONE_STATE

允许修改话机状态,如电源,人机接口等

(Allows modification of the telephony
state - power on, mmi, etc. )




android.permission.MOUNT_UNMOUNT_FILESYSTEMS

允许挂载和反挂载文件系统可移动存储
(Allows mounting and unmounting
file systems for removable storage. )




android.permission.PERSISTENT_ACTIVITY

允许一个程序设置他的 activities 显示

(Allow an application to make its activities persistent. )



android.permission.PROCESS_OUTGOING_CALLS

允许程序监视、修改有关播出电话
(Allows an application to monitor,
modify, or abort outgoing calls)



android.permission.READ_CALENDAR
允许程序读取用户日历数据
(Allows an application to read the user's calendar data.)


android.permission.READ_CONTACTS
允许程序读取用户联系人数据
(Allows an application to read the user's contacts data.)


android.permission.READ_FRAME_BUFFER
允许程序屏幕波或和更多常规的访问帧缓冲数据
(Allows an application to take screen shots and more generally
get access to the frame buffer data)


android.permission.READ_INPUT_STATE
允许程序返回当前按键状态
(Allows an application to retrieve
the current state of keys and switches. )


android.permission.READ_LOGS
允许程序读取底层系统日志文件
(Allows an application to read the low-level system log files. )


android.permission.READ_OWNER_DATA
允许程序读取所有者数据
(Allows an application to read the owner's data)


android.permission.READ_SMS
允许程序读取短信息
(Allows an application to read SMS messages.)


android.permission.READ_SYNC_SETTINGS
允许程序读取同步设置
(Allows applications to read the sync settings)


android.permission.READ_SYNC_STATS
允许程序读取同步状态
(Allows applications to read the sync stats)


android.permission.REBOOT
请求能够重新启动设备
(Required to be able to reboot the device. )


android.permission.RECEIVE_BOOT_COMPLETED
允许一个程序接收到 ACTION_BOOT_COMPLETED
广播在系统完成启动(Allows an application to receive the
ACTION_BOOT_COMPLETED that is
broadcast after the system finishes booting. )


android.permission.RECEIVE_MMS
允许一个程序监控将收到 MMS 彩信,记录或处理
(Allows an application to monitor incoming MMS messages, to
record or perform processing on them. )


android.permission.RECEIVE_SMS
允许程序监控一个将收到短信息,记录或处理
(Allows an application to monitor incoming SMS messages, to
record or perform processing on them.)

android.permission.RECEIVE_WAP_PUSH
允许程序监控将收到 WAP PUSH 信息
(Allows an application to monitor incoming WAP push messages. )

android.permission.RECORD_AUDIO
允许程序录制音频(Allows an application to record audio)

android.permission.REORDER_TASKS
允许程序改变 Z 轴排列任务
(Allows an application to change the Z-order of tasks)

android.permission.RESTART_PACKAGES
允许程序重新启动其他程序
(Allows an application to restart other applications)

android.permission.SEND_SMS
允许程序发送 SMS 短信(Allows an application to send SMS messages)

android.permission.READ_PHONE_STATE
允许程序获取通话状态(Allows read only access to phone state)


android.permission.SET_ACTIVITY_WATCHER
允许程序监控或控制 activities 已经启动全局系统中
Allows an application to watch and control how activities are
started globally in the system.


android.permission.SET_ALWAYS_FINISH

允许程序控制是否活动间接完成在处于后台时
Allows an application to control
whether activities are immediately
finished when put in the background.


android.permission.SET_ANIMATION_SCALE
修改全局信息比例
(Modify the global animation scaling factor.)



android.permission.SET_DEBUG_APP

配置一个程序用于调试
(Configure an application for debugging.)


android.permission.SET_ORIENTATION
允许底层访问设置屏幕方向和实际旋转
(Allows low-level access to
setting the orientation (actually rotation) of the
screen.)


android.permission.SET_PREFERRED_APPLICATIONS
允许一个程序修改列表参数
PackageManager.addPackageToPreferred()
和 PackageManager.removePackageFromPreferred() 方 法
(Allows an
application to modify the list of preferred applications
with the PackageManager.addPackageToPreferred()
and PackageManager.removePackageFromPreferred() methods.)


android.permission.SET_PROCESS_FOREGROUND
允许程 序当前运行 程序强行到 前台
(Allows an application to force
any currently running process to be in the
foreground.)


android.permission.SET_PROCESS_LIMIT
允许设 置最大的运 行进程数量
(Allows an application to set
the maximum number of (not needed) application
processes that can be running. )

android.permission.SET_TIME_ZONE
允许程序设置时间区域
(Allows applications to set the system time zone)


android.permission.SET_WALLPAPER
允许程序设置壁纸(Allows applications to set the wallpaper )


android.permission.SET_WALLPAPER_HINTS
允许程序设置壁纸 hits(Allows applications to set the wallpaper hints)


android.permission.SIGNAL_PERSISTENT_PROCESSES
允许程序请求发送信号到所有显示的进程中
(Allow an application to request that
a signal be sent to all persistent
processes)


android.permission.STATUS_BAR
允许程序打开、关闭或禁用状态栏及图标
Allows an application to open, close,
or disable the status bar and its
icons.


android.permission.SUBSCRIBED_FEEDS_READ
允 许 一 个 程 序 访 问 订 阅 RSS Feed 内 容 提 供
(Allows an application to allow access the subscribed feeds
ContentProvider. )


android.permission.SUBSCRIBED_FEEDS_WRITE
系统暂时保留改设置


android.permission.SYSTEM_ALERT_WINDOW
允许一个程序打开窗口使用 TYPE_SYSTEM_ALERT,
显示在其他所有程序的顶层(Allows an application to
open windows using the type TYPE_SYSTEM_ALERT,
shown on top of all other applications. )


android.permission.VIBRATE
允许访问振动设备(Allows access to the vibrator)


android.permission.WAKE_LOCK
允许使用 PowerManager 的 WakeLocks
保持进程在休眠时从屏幕消失
( Allows using PowerManager WakeLocks
to keep processor from sleeping or screen from dimming)




android.permission.WRITE_APN_SETTINGS
允许程序写入 API 设置(Allows applications to write the apn settings)


android.permission.WRITE_CALENDAR
允许一个程序写入但不读取用户日历数据
(Allows an application to write (but not read) the user's calendar data. )


android.permission.WRITE_CONTACTS
允许程序写入但不读取用户联系人数据
(Allows an application to write (but not read) the user's contacts data. )


android.permission.WRITE_GSERVICES
允许程序修改 Google 服务地图
(Allows an application to modify the Google service map. )


android.permission.WRITE_OWNER_DATA
允许一个程序写入但不读取所有者数据
(Allows an application to write (but not read) the owner's data.)


android.permission.WRITE_SETTINGS
允许程序读取或写入系统设置
(Allows an application to read or write the system settings. )


android.permission.WRITE_SMS
允许程序写短信
(Allows an application to write SMS messages)


android.permission.WRITE_SYNC_SETTINGS
允许程序写入同步设置
(Allows applications to write the sync settings)



--------------------------------------------------------------------

API LEVEL 8

ACCESS_CHECKIN_PROPERTIES

Allows read/write access to the "properties" table in the checkin database, to change values that get uploaded.


ACCESS_COARSE_LOCATION

Allows an application to access coarse (e.g., Cell-ID, WiFi) location


ACCESS_FINE_LOCATION

Allows an application to access fine (e.g., GPS) location


ACCESS_LOCATION_EXTRA_COMMANDS

Allows an application to access extra location provider commands


ACCESS_MOCK_LOCATION

Allows an application to create mock location providers for testing


ACCESS_NETWORK_STATE

Allows applications to access information about networks



ACCESS_SURFACE_FLINGER

Allows an application to use SurfaceFlinger's low level features



ACCESS_WIFI_STATE

Allows applications to access information about Wi-Fi networks



ACCOUNT_MANAGER

Allows applications to call into AccountAuthenticators.



AUTHENTICATE_ACCOUNTS

Allows an application to act as an AccountAuthenticator for the AccountManager


BATTERY_STATS

Allows an application to collect battery statistics





BIND_APPWIDGET Allows an application to tell the AppWidget service which application can access AppWidget's data.
BIND_DEVICE_ADMIN Must be required by device administration receiver, to ensure that only the system can interact with it.
BIND_INPUT_METHOD Must be required by an InputMethodService, to ensure that only the system can bind to it.


BIND_WALLPAPER Must be required by a WallpaperService, to ensure that only the system can bind to it.
BLUETOOTH Allows applications to connect to paired bluetooth devices
BLUETOOTH_ADMIN Allows applications to discover and pair bluetooth devices
BRICK Required to be able to disable the device (very dangerous!).
BROADCAST_PACKAGE_REMOVED Allows an application to broadcast a notification that an application package has been removed.
BROADCAST_SMS Allows an application to broadcast an SMS receipt notification
BROADCAST_STICKY Allows an application to broadcast sticky intents.
BROADCAST_WAP_PUSH Allows an application to broadcast a WAP PUSH receipt notification
CALL_PHONE Allows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call being placed.
CALL_PRIVILEGED Allows an application to call any phone number, including emergency numbers, without going through the Dialer user interface for the user to confirm the call being placed.

CAMERA Required to be able to access the camera device.
CHANGE_COMPONENT_ENABLED_STATE Allows an application to change whether an application component (other than its own) is enabled or not.
CHANGE_CONFIGURATION Allows an application to modify the current configuration, such as locale.
CHANGE_NETWORK_STATE Allows applications to change network connectivity state
CHANGE_WIFI_MULTICAST_STATE Allows applications to enter Wi-Fi Multicast mode
CHANGE_WIFI_STATE Allows applications to change Wi-Fi connectivity state
CLEAR_APP_CACHE Allows an application to clear the caches of all installed applications on the device.
CLEAR_APP_USER_DATA Allows an application to clear user data
CONTROL_LOCATION_UPDATES Allows enabling/disabling location update notifications from the radio.
DELETE_CACHE_FILES Allows an application to delete cache files.
DELETE_PACKAGES Allows an application to delete packages.
DEVICE_POWER Allows low-level access to power management
DIAGNOSTIC Allows applications to RW to diagnostic resources.
DISABLE_KEYGUARD Allows applications to disable the keyguard
DUMP Allows an application to retrieve state dump information from system services.
EXPAND_STATUS_BAR Allows an application to expand or collapse the status bar.
FACTORY_TEST Run as a manufacturer test application, running as the root user.
FLASHLIGHT Allows access to the flashlight
FORCE_BACK Allows an application to force a BACK operation on whatever is the top activity.
GET_ACCOUNTS Allows access to the list of accounts in the Accounts Service
GET_PACKAGE_SIZE Allows an application to find out the space used by any package.
GET_TASKS Allows an application to get information about the currently or recently running tasks.
GLOBAL_SEARCH This permission can be used on content providers to allow the global search system to access their data.
HARDWARE_TEST Allows access to hardware peripherals.
INJECT_EVENTS Allows an application to inject user events (keys, touch, trackball) into the event stream and deliver them to ANY window.
INSTALL_LOCATION_PROVIDER Allows an application to install a location provider into the Location Manager
INSTALL_PACKAGES Allows an application to install packages.
INTERNAL_SYSTEM_WINDOW Allows an application to open windows that are for use by parts of the system user interface.
INTERNET Allows applications to open network sockets.
KILL_BACKGROUND_PROCESSES Allows an application to call killBackgroundProcesses(String).
MANAGE_ACCOUNTS Allows an application to manage the list of accounts in the AccountManager
MANAGE_APP_TOKENS Allows an application to manage (create, destroy, Z-order) application tokens in the window manager.
MASTER_CLEAR
MODIFY_AUDIO_SETTINGS Allows an application to modify global audio settings
MODIFY_PHONE_STATE Allows modification of the telephony state - power on, mmi, etc.
MOUNT_FORMAT_FILESYSTEMS Allows formatting file systems for removable storage.
MOUNT_UNMOUNT_FILESYSTEMS Allows mounting and unmounting file systems for removable storage.



PERSISTENT_ACTIVITY This constant is deprecated. This functionality will be removed in the future; please do not use. Allow an application to make its activities persistent.
PROCESS_OUTGOING_CALLS Allows an application to monitor, modify, or abort outgoing calls.
READ_CALENDAR Allows an application to read the user's calendar data.


READ_CONTACTS Allows an application to read the user's contacts data.


READ_FRAME_BUFFER Allows an application to take screen shots and more generally get access to the frame buffer data
READ_HISTORY_BOOKMARKS Allows an application to read (but not write) the user's browsing history and bookmarks.
READ_INPUT_STATE This constant is deprecated. The API that used this permission has been removed.
READ_LOGS Allows an application to read the low-level system log files.

READ_PHONE_STATE Allows read only access to phone state.

READ_SMS Allows an application to read SMS messages.




READ_SYNC_SETTINGS Allows applications to read the sync settings
READ_SYNC_STATS Allows applications to read the sync stats




REBOOT Required to be able to reboot the device.
RECEIVE_BOOT_COMPLETED Allows an application to receive the ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting.
RECEIVE_MMS Allows an application to monitor incoming MMS messages, to record or perform processing on them.
RECEIVE_SMS Allows an application to monitor incoming SMS messages, to record or perform processing on them.
RECEIVE_WAP_PUSH Allows an application to monitor incoming WAP push messages.
RECORD_AUDIO Allows an application to record audio
REORDER_TASKS Allows an application to change the Z-order of tasks
RESTART_PACKAGES This constant is deprecated. The restartPackage(String) API is no longer supported.
SEND_SMS Allows an application to send SMS messages.
SET_ACTIVITY_WATCHER Allows an application to watch and control how activities are started globally in the system.


SET_ALWAYS_FINISH Allows an application to control whether activities are immediately finished when put in the background.
SET_ANIMATION_SCALE Modify the global animation scaling factor.
SET_DEBUG_APP Configure an application for debugging.
SET_ORIENTATION Allows low-level access to setting the orientation (actually rotation) of the screen.


SET_PREFERRED_APPLICATIONS This constant is deprecated. No longer useful, see addPackageToPreferred(String) for details.
SET_PROCESS_LIMIT Allows an application to set the maximum number of (not needed) application processes that can be running.
SET_TIME Allows applications to set the system time
SET_TIME_ZONE Allows applications to set the system time zone
SET_WALLPAPER Allows applications to set the wallpaper
SET_WALLPAPER_HINTS Allows applications to set the wallpaper hints
SIGNAL_PERSISTENT_PROCESSES Allow an application to request that a signal be sent to all persistent processes
STATUS_BAR Allows an application to open, close, or disable the status bar and its icons.
SUBSCRIBED_FEEDS_READ Allows an application to allow access the subscribed feeds ContentProvider.
SUBSCRIBED_FEEDS_WRITE
SYSTEM_ALERT_WINDOW Allows an application to open windows using the type TYPE_SYSTEM_ALERT, shown on top of all other applications.
UPDATE_DEVICE_STATS Allows an application to update device statistics.
USE_CREDENTIALS Allows an application to request authtokens from the AccountManager

VIBRATE Allows access to the vibrator
WAKE_LOCK Allows using PowerManager WakeLocks to keep processor from sleeping or screen from dimming
WRITE_APN_SETTINGS Allows applications to write the apn settings
WRITE_CALENDAR Allows an application to write (but not read) the user's calendar data.


WRITE_CONTACTS Allows an application to write (but not read) the user's contacts data.
WRITE_EXTERNAL_STORAGE Allows an application to write to external storage
WRITE_GSERVICES Allows an application to modify the Google service map.
WRITE_HISTORY_BOOKMARKS Allows an application to write (but not read) the user's browsing history and bookmarks.


WRITE_SECURE_SETTINGS Allows an application to read or write the secure system settings.
WRITE_SETTINGS Allows an application to read or write the system settings.
WRITE_SMS Allows an application to write SMS messages.


WRITE_SYNC_SETTINGS Allows applications to write the sync settings





==================================================================

ubuntu 下连接真机进行调试

http://code.google.com/p/51-android/






























==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
==================================================================================================================================
Android JNI NDK

Java Native Interface





project-->properties-->Builders--->new--->program
--->location (*/android-ndk-r8b/ndk-build)
--->working directory(${workspace_loc:/Xhuloo/jni})
---->refresh --specify resources


--------------------------------------------------------------
Android.mk
-------------------------------------------------------------

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := hello-ndk-jni #编译的目标对象
LOCAL_LDLIBS :=-L$(SYSROOT)/system/lib -llog #编译指定额外库,"-lxxx"格式
LOCAL_SRC_FILES := hello-ndk-jni.c #编译的源文件

include $(BUILD_SHARED_LIBRARY)
#$(call import-module,android/native_app_glue)


------------

#位于工程根目录中,call my-dir功能由编译器提供
#返回当前目录地址(包含 Android.mk本身)

#执行makefile,清理所有以LOCAL_开头的内容




LOCAL_SRC_FILES – 编译的源文件

LOCAL_C_INCLUDES – 需要包含的头文件目录

LOCAL_SHARED_LIBRARIES – 链接时需要的外部库

LOCAL_PRELINK_MODULE – 是否需要prelink处理(动态库优化)

LOCAL_MODULE – 编译的目标对象

BUILD_SHARED_LIBRARY – 指明要编译成动态库

LOCAL_LDLIBS 可执行程序或库的编译指定额外库,"-lxxx"格式

--------------------------------------------

hello-ndk-jni.c
--------------------------------------------

#include <stdio.h>
#include <string.h>
#include <jni.h>

#define LOG_TAG "hello-ndk-jni" //自定义的变量,相当于logcat函数中的tag
#undef LOG
#include <android/log.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__))

jstring Java_wo_wocom_xwell_XAplasma_stringFromNDKJNI( JNIEnv* env,jobject thiz ){

return (*env)->NewStringUTF(env, "well,i from hello-ndk-jni!!!");

}

void Java_wo_wocom_xwell_XAplasma_printLOGI(JNIEnv * env, jobject jobj){

LOGI("LOGI\n");
}



------------



http://www.cnmsdn.com/html/201106/1308859771ID10067.html

*.so的入口函数

  ---- JNI_OnLoad()与JNI_OnUnload()函数的用途

  当Android的VM(Virtual Machine)执行到System.loadLibrary()函数时,首先会去执行C组件里的JNI_OnLoad()函数。它的用途有二:

  (1)告诉VM此C组件使用那一个JNI版本。如果你的*.so档没有提供JNI_OnLoad()函数,VM会默认该*.so档是使用最老的 JNI 1.1版本。由于新版的JNI做了许多扩充,如果需要使用JNI的新版功能,例如JNI 1.4的java.nio.ByteBuffer,就必须藉由JNI_OnLoad()函数来告知VM。

  (2)由于VM执行到System.loadLibrary()函数时,就会立即先呼叫JNI_OnLoad(),所以C组件的开发者可以藉由JNI_OnLoad()来进行C组件内的初期值之设定(Initialization) 。

  
而当VM释放该C组件时,则会呼叫JNI_OnUnload()函数来进行善后清除动作




具体的每一个字符的对应关系如下

  字符 Java类型 C类型

  V void void

  Z jboolean boolean

  I jint int

  J jlong long

  D jdouble double

  F jfloat float

  B jbyte byte

  C jchar char

  S jshort short

  数组则以"["开始,用两个字符表示

  [I jintArray int[]

  [F jfloatArray float[]

  [B jbyteArray byte[]

  [C jcharArray char[]

  [S jshortArray short[]

  [D jdoubleArray double[]

  [J jlongArray long[]

[Z jbooleanArray boolean[]


Java函数的参数是class,则以"L"开头,以";"结尾,
中间是用"/" 隔开的包及类名。而其对应的C函数名的参数则为jobject.
一个例外是String类,其对应的类为jstring

  Ljava/lang/String; String jstring

  Ljava/net/Socket; Socket jobject

  如果JAVA函数位于一个嵌入类,则用$作为类名间的分隔符。

  例如 "(Ljava/lang/String;Landroid/os/FileUtils$FileStatus;)Z"

























相关文章:
Android开发教程&笔记(从零基础到快速开发)_图文.ppt
暂无评价|0人阅读|0次下载 | 举报文档 Android开发教程&笔记(从零基础到快速开发...android list avd ADT0.9.0 版本只能在命令行中创建 开启命令行进入 Android ...
黑马程序员android开发笔记(一).doc
暂无评价|0人阅读|0次下载|举报文档黑马程序员android开发笔记(一)_计算机软件及...相对布局&单位介绍 18、现形布局&布局的组合 19、表格布局&绝对布局 20、帧...
android笔记18:读其他应用的资源.doc
暂无评价|0人阅读|0次下载 | 举报文档 android笔记18:读其他应用的
Android学习笔记.pdf
Android学习笔记 - android界面间参数传递... 暂无评价|0人阅读|0次下载|举报文档Android学习笔记_计算机...AndroidManifest.xml 文件如下: <?xml version="1.0" e...
Android学习笔记总结初学者必看.doc
Android学习笔记总结初学者必看 - android开发帮助文档... 暂无评价|0人阅读|0次下载 | 举报文档 标签: 学习笔记| 初学者| Android学习笔记总结初学者必看_电脑基...
android笔记一.doc
暂无评价|0人阅读|0次下载 | 举报文档 android笔记一_计算机软件及应
Android笔记.txt
暂无评价|0人阅读|0次下载 | 举报文档 Android笔记_计算机硬件及网络_IT/计算机...Android的发展: 03年: 05年收购,做dalvik vm的研发 07年,sdk1.0已经开发 ...
android学习笔记_图文.doc
android学习笔记 - android开发过程中常用技巧... (), 0)){ //imm.showSoftInput(textView,0); ...Android 学习笔记 16.18 打开联系人列表 <1> Intent i...
android笔记.doc
android笔记 - android基础和环境的搭建的详细步骤... 暂无评价|0人阅读|0次下载 | 举报文档 android笔记_计算机...//dl.google.com/android/ADT-8.0.1.zip 安...
android笔记_图文.doc
暂无评价|0人阅读|0次下载 | 举报文档 android笔记_计算机软件及应用
Android 各版本下载地址.txt
暂无评价|0人阅读|0次下载 | 举报文档 Android 各版本下载地址_互联网_IT/计算机...//dl-ssl.google.com/android/repository/build-tools_r18.0.1-windows.zip...
android第一行代码(全书附自学笔记).doc
android第一行代码(全书附自学笔记)_计算机软件及应用_IT/计算机_专业资料。看了...18 19 市场占有率 1.2% 19.0% 0.1% 15.2% 35.3% 17.1% 9.6% 2.5...
Android 日常笔记(一)_图文.pdf
暂无评价|0人阅读|0次下载|举报文档Android 日常笔记(一)_计算机软件及应用_IT...- 表示不确定的java类型 S、U、V - 2nd、3rd、4th types 18. 关于listview...
Android 学习笔记.doc
暂无评价|0人阅读|0次下载 | 举报文档 Android 学习笔记_计算机软件及应用_IT...xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http...
Android小笔记.doc
暂无评价|0人阅读|0次下载 | 举报文档 Android笔记_计算机软件及应
Android笔记.txt
暂无评价|0人阅读|0次下载|举报文档 Android笔记_计算机硬件及网络_IT/计算机_....0"encoding="utf-8"?> <TextView xmlns:android="http://schemas.android....
Android开发实战经典---自己学习的笔记总结.doc
暂无评价|0人阅读|0次下载|举报文档Android开发实战经典---自己学习的笔记总结...<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="...
第一行代码Android学习笔记完全版.doc
暂无评价|0人阅读|0次下载 | 举报文档 第一行代码Android学习笔记完全版_其它语言学习_外语学习_教育专区。学习《第一行代码》的学习笔记,比第一版增加了许多 第...
android学习笔记.txt
android学习笔记 - 个人的android学习经历总结... android学习笔记_其它_高等教育_教育专区。个人的android...于是重新下了一个adt.18.0.0.zip,试成功了,但是无法...
android笔记.txt
暂无评价|0人阅读|0次下载 | 举报文档 android笔记_计算机硬件及网络
更多相关标签: