块儿2"/>
android工具代码块儿2
Activity的切换
1. //从A到B,没有数据传递
Intent intent = newIntent();
Intent.setClass(A.this ,B.class);
startActivity(intent);
A.this.finish();
2. 两个Activity之间传递数据(简单)
//A数据传给B
//A中代码:”passData” 是自定义的识别标志,可以随便命名~ 还可以添加多个
Intent intent = new Intent();
intent.setClass(A.this, B.class);
Bundle mBundle = new Bundle();
mBundle.putString("passData", "ray'blog");//压入数据
intent.putExtras(mBundle);
startActivity(intent);
A.this.finish();
//B中接受数据的代码:
//读出数据,则data的值为 ray‘blog
Bundle bundle =getIntent().getExtras();
String data = bundle.getString( "passData" );
3. 两个Activity之间传递数据(复杂方法)
相关的几个函数
startActivityForResult
public final void setResult(intresultCode, String data)
回调函数
protected voidonActivityResult(int requestCode, int resultCode, Intent data)
例如A到B, 从B得到A的数据
//A到B
static final int RG_REQUEST = 0;
Intent intent = new Intent();
intent.setClass(A.this, B.class);
startActivityForResult(intent,RG_REQUEST);
//在B中处理
Bundle bundle = new Bundle();
bundle.putString("DataKey",edittext.getText().toString());//给bundle 写入数据
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
//最后在A的回调函数里面接收数据
if (requestCode == RG_REQUEST) {
if (resultCode ==RESULT_CANCELED)
setTitle("Canceled...");
elseif(resultCode == RESULT_OK) {
setTitle((String)data.getCharSequenceExtra("DataKey"));
}
}
4. 详解
一个Android应用程序很少会只有一个Activity对象,如何在多个Activity之间进行跳转,而且能够互相传值是一个很基本的要求。 在前面创建的MyApp中,我们通过点击按钮可以更新当前界面上的文本内容。现在我们想换种方式,在点击按钮后,显示一个新的屏幕,在这个屏幕上输入一段话,然后再返回到原先的界面显示刚才输入的那句话。 首先我们新建这个新屏幕的布局文件input.xml,并添加一个文本输入框和一个按钮(注意,xml元素的命名不要和其他布局文件中的定义重名,因为所有的资源都在R中进行索引,比如id,如果重名了在使用R.id.*的时候就会有问题了)。这个布局文件对应的是一个Activity,因此我们再新建一个Input类(继承自Activity)用于显示这个布局并响应事件。
然后,还有一个重要的工作,那就是在清单文件AndroidManifest.xml中告诉程序,我定义了一个新的Activity,你可以去调用它。
我们希望在以前的那个主界面上点击按钮以后可以跳转到文本输入界面,所以我们需要对按钮的onClick事件进行定义:
在这段代码里出现了一些新东西。首先是Intent,它是Android一个很重要的类.Intent直译是“意图”,什么是意图呢?比如你想从这个Activity跳转到另外一个Activity,这就是一个意图。它不但可以连接多个Activity,还可以在它们之间传递数据。在这里,我们就是用Intent从MyApp对象跳转到了Input对象。再看紧跟着的startActivityForResult()方法,顾名思义,它可以从一个定义好的Intent对象启动一个新的Activity,并且,这个Activity会返回执行的结果,这些内容下面马上就会提到。好,这里我们已经可以调出新Activity了,我们看一下执行的结果: 你马上可以想到,现在需要对新的Activity(Input)进行处理了。我们在点击“确定”按钮的时候,需要获得上面EditText对象中的文本,然后返回到前一个Activity(MyApp)中去。看我们的按钮事件处理:
这里的关键是SharedPreferences对象,这是在多个Activity(同一包中)共享数据的方式,本质上它就是一个可以在包的范围内进行数据共享的文件。 我们通过一个标签“Text”获得了和文本相关的那个SharedPreferences对象(“Text”仅仅是自己定义的一个标签),然后给它赋予一个“text”对象值为当前文本框中输入的文本。设置完成以后,设置当前Activity的执行结果为RESULT_OK,再关闭当前的Activity,剩下的事情就可以回到MyApp这个主界面中去执行了。 其实剩下的事情也很简单,在MyApp这个Activity中,我们需要重写一个函数,onActivityResult()。因为我们启动Input这个Activity的时候使用的是startActivityForResult()方法,这个方法会使Input执行完以后返回给MyApp一个结果,MyApp接收到返回结果的时候会触发onActivityResult事件,对于结果的处理就在onActivityResult()中进行。同样,我们通过“Text”这个标签获得SharedPreferences对象,再把字符串从“text”对象中取出来并显示到当前屏幕上。 另外说明一下,requestCode是用来标识请求对象,我们刚才在启动Activity的时候使用的是“startActivityForResult(intent, 0)”,这里的0就是requestCode,当然,你可以设置成任何你喜欢的值。
我们看一下执行结果:
调用浏览器 ,载入某网址
Uri uri = uri.parse(“”);
Intent it = newIntent(Intent.ACTION_VIEW , uri)
startActivity(it);
Android 中打开浏览器
Intent viewIntent = new Intent(“android.intent.VIEW”, Uri.parse(“”));
startActivity(ViewIntent);
15. 让图片旋转
Bitmap bitmapOrg =BitmapFactory.decodeResource(this.getContext().getResource() ,R.drawable.moon);
Matrix matrix = new Matrix();
matrix.postRotate(-90);//旋转的角度
Bitmap resizedBitmap =Bitmap.createBitmap(bitmapOrg , 0 ,0 bitmapOrg.getWidth() ,bitmapOrg.getHeight() , matrix , true);
BitmapDrawable bmd = newBitmapDrawable(resizedBitmap);
. 格式化string.xml
//in string.xml
Thanks for visiting %s. You age is %d!
//and in the java code;
String.format(getString(R.string.my_text), “oschina”,33);
1. 注册一个BroadcastReceiver
registerReceiver(mMasterResetReceiver , newIntentFilter(“oms.action.MASTERRESET”));
Private BroadcastReceiver mMasterResetReceiver =new BroadcastReceiver(){
Public voidonReceive(Context context , Intent intent){
String action =intent.getAction();
If(“oms.action.MASTERRESET”.equals(action)){
RecoverDefaultConfig();
}
}
}
2. 定义ContentObserver , 监听某个数据库
privateContentObserver mDownloadsObserver = newDownloadsChangeObserver(Downloads.CONTENT_URI);
privateDownloadsChangeObserver extends ContentObserver
{
publicDownloadsChangeObserver(Uri uri)
{
Super(new Handler());
}
@Override
Public voidonChange(boolean selfChange){}
}
9. 显示toast
Toast.makeText(this.getApplicationContext() ,R.id.item , Toast.LENGTH_SHORT).show();
//从资源文件string.xml 里面取提示信息
Toast.makeText(this,getString(R.string.welcome), Toast.LENGTH_SHORT).show();
12. 建立GPRS连接
//Dial the GPRS linlk
private boolean openDataConnection()
{
// Set up data connection
DataConnection conn =DataConnection.getInstance();
If(connectMode == 0){
ret =conn.openConnection(mContext , “cmwap” , “cmwap” , “cmwap”);
}else{
Ret =conn.openConnection(mContext , “cmnet”, “” , “”);
}
}
13. PreferenceActivity用法
public class Setting extends PreferenceActivity
{
public voidonCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferenceFromResource(R.xml.settings);
}
}
14. 通过HttpClient从指定的server 获取数据
DefaultHttpClient httpclient = newDefaultHttpClient();
HttpGet method = new HttpGet(“/templets/defaults/index.html”);
HttpResource resp;
Reader reader = nul;
try{
//AllClientPNames.TIMEOUT
HttpParams params = newBasicHttpParams();
params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 10000);
httpClient.setParams(params);
resp =httpClient.execute(method);
int status =resp.getStatusLine().getStatusCode();
If(status !=HttpStatus.SC_OK)
{
Return false;
}
// HttpStatus.SC_OK;
return true;
}catch(ClientProtocolException e){
//TODO Auto-generatedcatch block
e.printStackTrace();
}catch (IOException e)
{
//TODO Auto-generatedcatch block
e.printStackTrace();
}finally{
If(reader != null)
Try{
reader.close();
}catch(IOException e)
{
//TODO Auto-generatedcatch block
e.printStackTrace();
}
}
22. Android中添加联系人
Public Uri addContact(Context context,){
ContentValues values =new ContentValues();
values.put(People.NAME ,name);
Uri uri =getContentResolver().insert(People.CONTENT_URI , values);
Uri numberUri =Uri.withAppendedPath(uri,People.Phones.CONTENT_DIRECTORY);
values.clear();
values.put(Contact.Phones.TYPE,People.Phones.TYPE_MOBILE);
values.put(People.NUMBER, phone);
getContentResolver().insert(numberUri, values);
return uri;
}
31. btn_selector
<?xml version = “1.0” encoding = “utf-8”?>
<selector xmlns:android=””>
<!--pressed-->
<item android:state_pressed= “true”android:drawable=”@drawable/btn_press”/>
<!--focused-->
<itemandroid:state_focused=”true” android:drawable=”@drawable/btn”/>
<!--default-->
<itemandroid:drawable=”@drawable/btn”/>
</selector>
32. 关闭游标和数据库
private void close(Cursor cursor , SQLiteDatabasedatabase){
try{
if(cursor!=null&&!cursor.isClosed()){
Cursor.close();
}
}catch(Exception e){}
try {
dbHelper.closeDb(database);
}catch(Exception e){
}
}
33 MD5加密
Public static String md5(String string){
Byte[] hash;
try{
hash =MessageDigest.getInstance(“MD5”).digest(string.getBytes(“UTF-8”));
}catch(NoSuchAlgorithmExceptione){
throw newRuntimeException(“Huh , MD5 should be supported?” , e);
}catch(UnsupportedEncodingException e){
throw newRuntimeException(“Huh , UTF-8 should be supported?” , e);
}
StringBuilder hex = newStringBuilder(hash.length * 2);
for(byte b : hash){
if((b &0xFF)<0x10)hex.append(“0”);
hex.append(Integer.toHexString(b&0xFF));
}
returnhex.toString().toLowerCase();
}
36. 可以使用AlertDialog.Builder才产生一个提示框
例如像messagebox那样的
newAlertDialog.Builder(this)
.setTitle(“Android提示”)
.setMessage(“这是一个提示,请确定”)
.show();
带一个确定的对话框
NewAlertDialog.Builder(this);
.setMessage(“这是第二个提示”)
.setPositiveButton(“确定”,newDialogInterface.OnClickListener(){ public void onClick(DialogInterface , inti){//按钮事 件}})
.show();
AlertDialog.Builder还有很多复杂用法,有确定和取消的对话框
newAlertDialog.Builder(this)
.setTitle("提示")
.setMessage("确定退出?")
.setIcon(R.drawable.quit)
.setPositiveButton("确定", new DialogInterface.OnClickListener(){
public void onClick(DialogInterfacedialog, int whichButton) {
setResult(RESULT_OK);//确定按钮事件
finish();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int whichButton) {
//取消按钮事件
}
})
.show();
39. menu的用法
public static final intITEM_1_ID = Menu.FIRST;
public static final intITEM_2_ID = Menu.FIRST + 1;
public static final intITEM_3_ID = Menu.FIRST + 2;
public booleanonCreateOptionsMenu(Menu menu){
super.onCreateOptionMenu(menu);
//不带图标的Menu
menu.add(0 , ITEM_1_ID ,0 , “item-1”);
//带图标的Menu
menu.add(0, ITEM_2_ID , 0, “item-2”).setIcon(R.drawable.editbills2);
menu.add(0, ITEM_2_ID , 0, “item-2”).setIcon(R.drawable.editbills1);
return true;
}
public booleanonOptionItemSelected(MenuItem item){
Switch(item.getItemId()){
case 1:
Toast.makeText(this , “menu1”,TOAST.LENGTH_SHORT).show();
retrun true;
Case 2:
return true;
case 3:
return true;
}
Return false;
}
42. Android UI Layout
1.AbsoluteLayout
在 Android UI 中,最基本的构建单位(building block)是 android.view.View。一个 View 占据屏幕上的一个矩形区域,并负责该区域的绘画和事件处理。View 有一些子类,比如 ImageView、TextView 等可分别用来显示图像、文字…… View 还有一个特殊的子类 ViewGroup,ViewGroup 在 UI layout 中充当“容器”的角色,用以“包含”其他 View 以及 ViewGroup:
viewgroup.png
由于 ViewGroup 是一个 abstract class无法直接实例化,所以在 layout 中真正充当“容器”角色的应该是 ViewGroup 的子类 :AbsoluteLayout、 FrameLayout、 LinearLayout、 RelativeLayout 等。在实际的 UI 编程中,使用不同的 Layout 类作为容器,对该容器中的各个子 View 的排列方式有很大影响。比如,LinearLayout 中的各个子 View 按照横向或者纵向线性排列;而 AbsoluteLayout中各个子 View 可以指定以像素为单位的“绝对”位置。AbsoluteLayout 的这种“绝对”定位的布局方式和我们非常熟悉的 Windows 编程中的 SetWindowPos() 或 Form1.Left = 10 的布局方式是一样的,比较简单:
现在我们新建一个 Android 工程中,在其主 Activity 类中添加如下三个成员:
private AbsoluteLayout al;
private TextView tv;
private View v;
改写这个类的 onCreate 方法如下:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
//构造一个 AbsoluteLayout,设置其背景色
al = newAbsoluteLayout(this);
al.setBackgroundColor(Color.YELLOW);
//构造一个 TextView 并设置其 text 和 背景色
tv = newTextView(this);
tv.setText("Androidis a software stack for mobile devices that includes an operating system,middleware and key applications. ");
tv.setBackgroundColor(Color.BLUE);
// 用该 View 在父 View 中的 width,height,x,y 作为参数构造一个 AbsoluteLayout.LayoutParams
AbsoluteLayout.LayoutParams tvLP = new AbsoluteLayout.LayoutParams(70,50, 10, 20);
// 把这个 TextView 加入到 AbsoluteLayout中,并应用上一步创建的 LayoutParams。这样 TextView 就会显示在我 们指定的位置上了。
al.addView(tv, tvLP);
v = newView(this);
v.setBackgroundColor(Color.RED);
AbsoluteLayout.LayoutParams vLP = new AbsoluteLayout.LayoutParams(70,50, 90, 70);
//也可以先为子 View 设置 LayoutParams,然后再调用一个参数的ViewGroup.addView(View) 来添加。效果是一样 的。
v.setLayoutParams(vLP);
al.addView(v);
// 设置 al 为本 Activity 的 content
// 这样,在该 Activity 被调用时,就会显示该 AbsoluteLayout 和其子 View
this.setContentView(al);
}
43. Tab以及HostTab操作
Tab与TabHost
这就是Tab,而盛放Tab的容器就是TabHost
每一个Tab还对应了一个布局,这个就有点好玩了。一个Activity,对应了多个功能布局。
44. 监控应用程序包的安装&删除
方法 一:
public class getBroadcast extendsBroadcastReceiver{
@Override
public voidonReceive(Context context, Intent intent){
If(Intent.ACTION_PACKAGE_ADDED.equels(intent.getAction())){
Toast.makeText(context , “有应用被添加” ,Toast.LENGTH_SHORT ).show();
}elseif(Intent.ACTION_PACKAGE_REMOVED.equels(intent.getAction())){
Toast.makeText(context , “有应用被删除” ,Toast.LENGTH_SHORT ).show();
}elseif(Intent.ACTION_PACKAGE_REPLACED.equels(intent.getAction())){
Toast.makeText(context , “有应用被替换” ,Toast.LENGTH_SHORT ).show();
}elseif(Intent.ACTION_PACKAGE_BUTTON.equels(intent.getAction())){
Toast.makeText(context , “按键” ,Toast.LENGTH_SHORT ).show();
}
}
}
需要声明的权限如下AndroidManifest.xml
<receiver android:name="getBroadcast"android:enabled="true" >
<intent-filter>
<actionandroid:name="android.intent.action.PACKAGE_ADDED"></action>
<!-- <action android:name="android.intent.action.PACKAGE_CHANGED"></action>-->
<actionandroid:name="android.intent.action.PACKAGE_REMOVED"></action>
<actionandroid:name="android.intent.action.PACKAGE_REPLACED"></action>
<!-- <actionandroid:name="android.intent.action.PACKAGE_RESTARTED"></action>-->
<!-- <actionandroid:name="android.intent.action.PACKAGE_INSTALL"></action>-->
<actionandroid:name="android.intent.action.CAMERA_BUTTON"></action>
<dataandroid:scheme="package"></data>
</intent-filter>
</receiver>
方法 二:
通过阅读Android SDK里关于intent.action这部分里面的描述,我们可以找到一些与package相关的系统广播
android.intent.action.PACKAGE_ADDED
android.intent.action.PACKAGE_CHANGED
android.intent.action.PACKAGE_DATA_CLEARED
android.intent.action.PACKAGE_INSTALL
android.intent.action.PACKAGE_REMOVED
android.intent.action.PACKAGE_REPLACED
android.intent.action.PACKAGE_RESTARTED
android.intent.action.PACKAGE_ADDED
android.intent.action.PACKAGE_CHANGED
android.intent.action.PACKAGE_DATA_CLEARED
android.intent.action.PACKAGE_INSTALL
android.intent.action.PACKAGE_REMOVED
android.intent.action.PACKAGE_REPLACED
android.intent.action.PACKAGE_RESTARTED
其中 ACTION_PACKAGE_ADDED 在SDK里的描述是 :
Broadcast Action: A newapplication package has been installed on the device.
ACTION_PACKAGE_REMOVED 在SDK里的描述是 :
Broadcast Action: An existingapplication package has been removed from the device.
ACTION_PACKAGE_REPLACED 在SDK里的描述是 :
Broadcast Action: A new version ofan application package has been installed, replacing an existing version thatwas previously installed.
通过这三个广播消息 我们已经可以监控到Android 应用程序的安装和删除
详细的实现代码如下
package zy.Broadcast;
importandroid.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class getBroadcast extendsBroadcastReceiver {
@Override
public void onReceive(Context context,Intent intent) {
if(Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())){
Toast.makeText(context,"有应用被添加",Toast.LENGTH_LONG).show();
}
else if(Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())){
Toast.makeText(context,"有应用被删除",Toast.LENGTH_LONG).show();
}
/* else if(Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())){
Toast.makeText(context,"有应用被改变",Toast.LENGTH_LONG).show();
}*/
else if(Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())){
Toast.makeText(context, "有应用被替换",Toast.LENGTH_LONG).show();
}
/* else if(Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())){
Toast.makeText(context,"有应用被重启",Toast.LENGTH_LONG).show();
}*/
/* else if(Intent.ACTION_PACKAGE_INSTALL.equals(intent.getAction())){
Toast.makeText(context,"有应用被安装",Toast.LENGTH_LONG).show();
}*/
}
}
然后在AndroidManifest.xml中声明这几个Action的<intent-filter>即可在系统里捕获这些广播消息
具体的源代码如下
<?xml version="1.0"encoding="utf-8"?>
<manifestxmlns:android=""
package="zy.Broadcast"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"android:label="@string/app_name">
<activityandroid:name=".Broadcast"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN" />
<categoryandroid:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiverandroid:name="getBroadcast" android:enabled="true">
<intent-filter>
<actionandroid:name="
更多推荐
android工具代码块儿2
发布评论