Feb 12

由于手机端应用的响应,与当时的无线通信网络状况有很大的关联。而通信网络往往具有不稳定,延迟长的特点。所以,在我们的应用程序中,当我们请求网络的时候,超时机制的应用就显得特别重要。

超时机制主要有:

1、HTTP请求超时机制

2、Socket通信超时机制

HTTP请求超时机制

  1. public static void main(String[] args){   
  2.   
  3. long a=System.currentTimeMillis();   
  4. try{   
  5. URL myurl = new URL(“http://www.linuxidc.com”);   
  6. URLConnection myurlcon = myurl.openConnection();   
  7. myurlcon.setConnectTimeout(1000);   
  8. myurlcon.setReadTimeout(1000);   
  9. BufferedReader in = new BufferedReader(new InputStreamReader(myurlcon.getInputStream(),”UTF-8″));   
  10. String inputLine;   
  11.   
  12. while ((inputLine = in.readLine()) != null){   
  13. System.out.println(inputLine);   
  14. in.close();   
  15. System.out.println(System.currentTimeMillis()-a);   
  16. }   
  17. catch (MalformedURLException e) {   
  18. e.printStackTrace();   
  19. catch (UnsupportedEncodingException e) {   
  20. e.printStackTrace();   
  21. catch (IOException e) {   
  22. e.printStackTrace();   
  23. }   
  24.   
  25. }   
  26.   
  27.   
  28. 如果超时 将 抛出 以下 异常   
  29.   
  30. java.net.SocketTimeoutException: Read timed out   
  31. at java.net.SocketInputStream.socketRead0(Native Method)   
  32. at java.net.SocketInputStream.read(SocketInputStream.java:129)   
  33. at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)   
  34. at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)   
  35. at java.io.BufferedInputStream.read(BufferedInputStream.java:313)   
  36. at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:606)   
  37. at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:554)   
  38. at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:940)   
  39. at com.Test.main(Test.java:52)

补充内容:

Android项目中,如果有用到http请求,就必须也应该加上http请求的超时管理,异常管理,项目中遇到这个需求,google上搜索到了一大堆,但是写的都比较简单,做个demo还行,用在项目中还是不够完善。自己写了一个例子,有不完善之处,欢迎大家指正。

  需要注意的地方:有三个方面

  如何控制超时机制

  如何处理异常

  如何处理请求错误的

  1. private class XmlAsyncLoader extends XmlResourceRequest {   
  2.   
  3.  private boolean mIsCancle = false;   
  4.  private HttpGet mGet;   
  5.  private HttpClient mHttp;   
  6.   
  7.  public XmlAsyncLoader(MxActivity<?> activity, String url)   
  8.  throws MalformedURLException {   
  9.  super(activity, url);   
  10.  }   
  11.   
  12.  @Override  
  13.  protected void doTaskInBackground() {   
  14.  // 请求数据   
  15.  if (mUrl.toLowerCase().startsWith("http://")) {   
  16.  mGet = initHttpGet(mUrl);   
  17.  mHttp = initHttp();   
  18.  try {   
  19.  HttpResponse response = mHttp.execute(mGet);   
  20.  if (mIsCancle) {   
  21.  return;   
  22.  }   
  23.  if (response != null) {   
  24.  if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){   
  25.  onResponseError("network error");   
  26.  Log.v(TAG, "the code is :"+response.getStatusLine().getStatusCode());   
  27.  return;   
  28.  }   
  29.  notifyUpdateProgress(70);   
  30.  Document doc = getDocumet(response);   
  31.  Element root = doc.getDocumentElement();   
  32.  NodeList appList = root   
  33.  .getElementsByTagName(Item_ELEMENT_NAME);   
  34.  final int len = appList.getLength();   
  35.  if (len <= 0) {// 没有items   
  36.  onFoundNoItems();   
  37.  return;   
  38.  }   
  39.  for (int i = 0; i < len; i++) {   
  40.  Element item = (Element) appList.item(i);   
  41.  if (item.getNodeType() == Node.ELEMENT_NODE) {   
  42.  HahaItemInfo info = createHahaItemIno(item);   
  43.  if (mIsCancle){   
  44.  return;   
  45.  }   
  46.  onFoundItem(info, 80 + 20 * (i + 1) / len);   
  47.  addUrlToQueue(info.userIconUrl);   
  48.  }   
  49.  };   
  50.     
  51.  }   
  52.  }catch(ConnectTimeoutException e){   
  53.  onResponseError("time out");   
  54.  } catch (ClientProtocolException e) {   
  55.  --mCurrentPage;   
  56.  e.printStackTrace();   
  57.  } catch (IOException e) {   
  58.  --mCurrentPage;   
  59.  e.printStackTrace();   
  60.  } catch (XmlPullParserException e) {   
  61.  --mCurrentPage;   
  62.  e.printStackTrace();   
  63.  }finally{   
  64.  notifyLoadFinish();   
  65.  notifyLoadImages();   
  66.  mHttp.getConnectionManager().shutdown();   
  67.  }   
  68.   
  69.  }   
  70.  }   
  71.   
  72.   
  73.  private HttpClient initHttp() {   
  74.  HttpClient client = new DefaultHttpClient();   
  75.  client.getParams().setIntParameter(   
  76.  HttpConnectionParams.SO_TIMEOUT, TIME_OUT_DELAY); // 超时设置   
  77.  client.getParams().setIntParameter(   
  78.  HttpConnectionParams.CONNECTION_TIMEOUT, TIME_OUT_DELAY);// 连接超时   
  79.  return client;   
  80.  }   
  81.   
  82.  private HttpGet initHttpGet(String mUrl) {   
  83.  HttpGet get = new HttpGet(mUrl);   
  84.  initHeader(get);   
  85.  return get;   
  86.  }   
  87.   
  88.   
  89.  @Override  
  90.  public boolean tryCancel() {   
  91.  Log.i(TAG, "tryCanle is working");   
  92.  mGet.abort();   
  93.  mIsCancle = true;   
  94.  mHttp.getConnectionManager().shutdown();   
  95.  notifyLoadFinish();   
  96.  return true;   
  97.  }   
  98.   
  99.  }  

这是一个异步任务类,发送get请求请求数据,解析服务器的响应数据,同时通知ui线程更新ui

Android中,互联网交互的写法有很多,可以使用apache提供的包,也可以使用google提供的api,我不知道那种更好,只是习惯于使用

apache的api。

1. 设置超时机制

client.getParams().setIntParameter( HttpConnectionParams.SO_TIMEOUT, TIME_OUT_DELAY); // 超时设置 client.getParams().setIntParameter( HttpConnectionParams.CONNECTION_TIMEOUT, TIME_OUT_DELAY);// 连接超时

这里设置了两种超时,第一种是请求超时,第二种时连接超时。

当向服务器发出请求后,请求和服务器建立socket连接,但是很长时间内都没有建立socket连接,这就时第一种请求超时,这种情况主要发生在请求了

一个不存在的服务器。超时之后,会抛出InterruptedIOException异常。

Timeout for blocking operations. The argument value is specified in milliseconds. An InterruptedIOException is thrown if this timeout expires.

客户端已经与服务器建立了socket连接,但是服务器并没有处理客户端的请求,没有相应服务器,这就是第二种连接超时。这中超时会抛出

ConnectTimeoutException异常,ConnectTimeoutException继承自InterruptedIOException,所以只要捕获ConnectTimeoutException 就可以了。

2. 分析一下请求的过程

 2.1 HttpResponse response = mHttp.execute(mGet);

执行请求方法,获取服务器响应,(这里有个不太成熟的看法,response不可能为null,还有待验证)。

2.2 获取请求响应码

if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){ onResponseError("network error"); Log.v(TAG, "the code is :"+response.getStatusLine().getStatusCode()); return; }

  即使连接上服务器,并且从服务器上获取了数据,也有可能时服务器返回的错误信息,因此也需要特殊处理。

2.3 异常处理

  对于异常,不能简单的捕获就完事,例如上面的代码中,我请求第三页的数据,如果发生异常,请求不成功,那么我就需要让当前页数回滚,

如果成功了就不用回滚了,所以需要对异常进行处理

2.4 finally关键字

  不管是请求成功,还是失败,都需要关闭链接。

Feb 12

写这例子的初衷是想模仿通讯录列表,实现了一些效果,也没法做到100%相像,自己也认为还有一些不足(存在些内存上的浪费)。
这个阶段先这样了,代码量比较大,就不贴代码了,只上效果图。

源码下载地址:

免费下载地址在 http://linux.linuxidc.com/

用户名与密码都是www.linuxidc.com

具体下载目录在 /2012年资料/1月/26日/Android开发教程:仿通讯录ListView小例子/

效果图如下:

    




1.实现根据字母进行分类。
2.实现快速滑动及修改快速滑动条的图标。
3.实现快速滑动时的字母提示。
4.实现快捷操作框及其的动画显示/隐藏,上箭头与下箭头的选择性显示及位置匹配。
5.顺便做了个自定义Dialog和完整的发送邮件的实现(主送、抄送、密送、附件、标题、正文)。

部分实现细节介绍:

1.快速滑动时的字母提示框

      该显示组件为TextView,实例索引名为txtOverlay,执行WindowManager.addView(txtOverlay, layoutParams)后添加于WindowManager上。通过设置ListView.OnScrollListener监听到滚动时则将 txtOverlay设置可见性为View.VISIBLE,当滚动结束时可见性调为View.INVISIBLE。
     为了提升用户体验,避免在短时间内,用户再次拖动时字母提示框又执行显示和隐藏命令,将隐藏的操作设置在DisapearThread线程实例中,通过 handler.postDelayed(disapearThread, 1500)延时1.5秒后再执行字母提示框的隐藏。

2.快速滚动图标的修改

     Android Api并未公开修改图标的接口,本处通过调用Java的反射机制修改了快速滚动的图标。替换代码见MainAct类中的changeFastScrollerDrawable()。
    补充:Android对ListView设置了优化,对于少于4页内容的List即使设置了fastScrollEnabled=true也不会显示FastScroller。
    参考资料查看:<Android_Source>/frameworks/base/core/java/android/widget/FastScroller.java:其中常量MIN_PAGES及其相关。

3.获取List中“咧牙”ImageView在屏幕中的绝对位置

    代码如下:anchor为“咧牙”ImageView。

[java]
  1. int[] location = new int[2];  
  2. anchor.getLocationOnScreen(location);  
  3. Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(),  
  4.         location[1] + anchor.getHeight());  

     这个步骤也是为上箭头与下箭头的自动选择做好铺垫。 

4.为快捷按钮组成的LinearLayout设置反弹动画

      设置LinearLayout沿直线轨迹从从屏幕右边滑动到左边这个部分的动画定义文件是res/anim/anim_actionslayout.xml,代码如下:

[xhtml]
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!-- 本文件指定了actionsLayout的出现动画。 -->  
  3. <!-- translate定义了垂直或水平方向或两者混合的一种运动。 -->  
  4. <!-- formXDelta:赋值为浮点数或百分比。百分号后面'p'表示相对于父控件的相应位置。当只有百分号时表示相对于控件本身的位置。 -->  
  5. <!-- 查看@Android:integer/config_longAnimTime的具体值可于<SDK_PATH>/platforms/<android-level>/data/res/values/config.xml -->  
  6. <translate xmlns:Android="http://schemas.android.com/apk/res/android"  
  7.     Android:fromXDelta="100%p"  
  8.     Android:toXDelta="0"  
  9.     Android:duration="@android:integer/config_longAnimTime"  
  10. ></translate>  

     需要反弹的效果还得对Animation设定Interpolator(插值器),插值器的设定需要一些数学基础了,得找到合适的函数对动画速率进行修正。本例中使用的插值器代码如下:

[xhtml]
  1. package lab.sodino.list_quickaction;  
  2. import Android.util.Log;  
  3. import Android.view.animation.Interpolator;  
  4. /**  
  5.  * @author Sodino E-mail:sodinoopen@hotmail.com  
  6.  * @version Time:2011-5-3 下午08:02:01  
  7.  */  
  8. public class CustomInterpolator implements Interpolator {  
  9.     /**  
  10.      * @param input  
  11.      *            A value between 0 and 1.0 indicating our current point in the  
  12.      *            animation where 0 represents the start and 1.0 represents the  
  13.      *            end  
  14.      * @return Returns The interpolation value. This value can be more than 1.0  
  15.      *         for Interpolators which overshoot their targets, or less than 0  
  16.      *         for Interpolators that undershoot their targets.  
  17.      */  
  18.     public float getInterpolation(float input) {  
  19.         Log.d("Android_LAB", "input=" + input);  
  20.         // 设定动画的加速度变化值。此例的效果是使用actionsLayout超过目标旋转区后再反弹回来。  
  21.         // 插值计算公式: 1.2-((x*1.55f)-1.1)^2  
  22.         // 画出函数图的话即可观察出动画执行过程中越过目标区再反弹的详细过程。  
  23.         // x :0 <= v <= 1.0  
  24.         // (x*1.55f) :0 <= v <= 1.55  
  25.         // ((x*1.55f)-1.1) :-1.1 <= v <= 0.45  
  26.         // ((x*1.55f)-1.1)^2 :0<= v <= 1.21  
  27.         // 1.2-((x*1.55f)-1.1)^2 :-0.1 <= v <= 1.2  
  28.         final float inner = (input * 1.55f) - 1.1f;  
  29.         // 如果返回值为常量1的话,则相当于没有动画效果。  
  30.         return 1.2f - inner * inner;  
  31.     }  
  32. }  
Feb 12
ToggleButton(开关按钮)是Android系统中比较简单的一个组件,是一个具有选中和未选择状态双状态的按钮,并且需要为不同的状态设置不同的显示文本。

    ToggleButton常用的XML属性

  

属性名称

描述

Android:disabledAlpha

设置按钮在禁用时透明度。

 

Android:textOff

未选中时按钮的文本

Android:textOn

选中时按钮的文本

  

下面是具体的例子:

第一个例子是通过Toast显示ToggleButton不同的状态时的信息

MainActivity.java

  1. package com.Android.togglebutton;  
  2.  
  3. import Android.app.Activity;  
  4. import Android.os.Bundle;  
  5. import Android.view.View;  
  6. import Android.view.View.OnClickListener;  
  7. import Android.widget.Toast;  
  8. import Android.widget.ToggleButton;  
  9.  
  10. public class MainActivity extends Activity {  
  11.     //声明ToggleButton  
  12.     private ToggleButton togglebutton;  
  13.     @Override 
  14.     public void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.main);  
  17.           
  18.         togglebutton = (ToggleButton) findViewById(R.id.togglebutton);  
  19.         togglebutton.setOnClickListener(new OnClickListener() {      
  20.             public void onClick(View v) {          
  21.                 // 当按钮第一次被点击时候响应的事件        
  22.                 if (togglebutton.isChecked()) {              
  23.                     Toast.makeText(MainActivity.this"你喜欢球类运动", Toast.LENGTH_SHORT).show();         
  24.                 }   
  25.                 // 当按钮再次被点击时候响应的事件  
  26.                 else {              
  27.                     Toast.makeText(MainActivity.this"你不喜欢球类运动", Toast.LENGTH_SHORT).show();          
  28.                 }      
  29.             }  
  30.           });  
  31.     }  

main.xml

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android" 
  3.     Android:orientation="vertical" 
  4.     Android:layout_width="fill_parent" 
  5.     Android:layout_height="fill_parent" 
  6.     > 
  7.     <TextView    
  8.         Android:layout_width="fill_parent"   
  9.         Android:layout_height="wrap_content"   
  10.         Android:text="@string/hello" 
  11.         /> 
  12.     <ToggleButton   
  13.         Android:id="@+id/togglebutton"          
  14.         Android:layout_width="wrap_content"          
  15.         Android:layout_height="wrap_content"          
  16.         Android:textOn="喜欢"          
  17.         Android:textOff="不喜欢" 
  18.         /> 
  19. </LinearLayout> 

strings.xml

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.     <string name="hello">你喜不喜欢球类运动?</string> 
  4.     <string name="app_name">测试ToggleButton</string> 
  5. </resources> 

效果图:

第二个例子通过图片的变化显示ToggleButton不同的状态时的图片

MainActivity.java

  1. package com.Android.togglebutton;  
  2.  
  3. import Android.app.Activity;  
  4. import Android.os.Bundle;  
  5. import android.widget.CompoundButton;  
  6. import Android.widget.CompoundButton.OnCheckedChangeListener;  
  7. import android.widget.ImageView;  
  8. import Android.widget.ToggleButton;  
  9.  
  10. public class MainActivity extends Activity {  
  11.      //声明ImageView,ToggleButton  
  12.     private ImageView imageView;     
  13.     private ToggleButton toggleButton;   
  14.     @Override 
  15.     public void onCreate(Bundle savedInstanceState) {          
  16.      super.onCreate(savedInstanceState);          
  17.      setContentView(R.layout.main);   
  18.      //通过findViewById获得ImageView,ToggleButton  
  19.      imageView=(ImageView) findViewById(R.id.imageView);          
  20.      toggleButton=(ToggleButton)findViewById(R.id.toggleButton);   
  21.        
  22.      toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener(){              
  23.       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {   
  24.        toggleButton.setChecked(isChecked);  
  25.                 //使用三目运算符来响应按钮变换的事件  
  26.                 imageView.setImageResource(isChecked?R.drawable.pic_on:R.drawable.pic_off);  
  27.          }                      
  28.       });      
  29.     }  
  30. }  

main.xml

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"      
  3.       android:orientation="vertical"      
  4.       Android:layout_width="fill_parent"      
  5.       android:layout_height="fill_parent">      
  6.   <ImageView   
  7.       Android:id="@+id/imageView"          
  8.       Android:layout_width="wrap_content"          
  9.       android:layout_height="wrap_content"          
  10.       Android:src="@drawable/pic_off"           
  11.       android:layout_gravity="center_horizontal"   
  12.       />      
  13.    <ToggleButton   
  14.       Android:id="@+id/toggleButton"          
  15.       android:layout_width="130dip"          
  16.       Android:layout_height="wrap_content"          
  17.       android:textOn="开灯"          
  18.       Android:textOff="关灯"          
  19.       android:layout_gravity="center_horizontal"   
  20.       /> 
  21. </LinearLayout> 

效果图:

 

Feb 12

Intent寻找目标组件的两种方式:

  • 显式Intent:通过指定Intent组件名称来实现的,它一般用在知道目标组件名称的前提下,一般是在相同的应用程序内部实现的。
  • 隐式Intent:通过Intent Filter来实现的,它一般用在没有明确指出目标组件名称的前提下,一般是用于在不同应用程序之间。

一.显式Intent

   一般情况下,一个Android应用程序中需要多个屏幕,即是多个Activity类,并且在这些Activity之间进行切换通过Intent机制来实现的。在同一个应用程序中切换Activity时,我们通常都知道要启动的Activity具体是哪一个,因此常用显式的Intent来实现的。

    下 面的例子是在同一应用程序中MainActivity启动SecondActivity,下面的代码中,主要是为“转到SecondActivity”按 钮添加了OnClickListener,使得按钮被点击时执行onClick()方法,onClick()方法中则利用了Intent机制,来启动 SecondActivity,关键的代码是22~25行。

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
  3.     Android:orientation="vertical"
  4.     Android:layout_width="fill_parent"
  5.     Android:layout_height="fill_parent"
  6.     >
  7.     <TextView    
  8.         Android:layout_width="fill_parent"  
  9.         Android:layout_height="wrap_content"  
  10.         Android:text="@string/hello1"
  11.         />
  12.     <Button  
  13.         Android:id="@+id/btn"
  14.         Android:layout_width="wrap_content"  
  15.         Android:layout_height="wrap_content"  
  16.         Android:text="转到SecondActivity"
  17.         />
  18. </LinearLayout>

second.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
  3.     Android:orientation="vertical"
  4.     Android:layout_width="fill_parent"
  5.     Android:layout_height="fill_parent"
  6.     >
  7.     <TextView    
  8.         Android:layout_width="fill_parent"  
  9.         Android:layout_height="wrap_content"  
  10.         Android:text="@string/hello2"
  11.         />
  12.     <Button  
  13.         Android:id="@+id/secondBtn"
  14.         Android:layout_width="wrap_content"  
  15.         Android:layout_height="wrap_content"  
  16.         Android:text="返回"
  17.         />
  18. </LinearLayout>

MainActivity.java

  1. package com.Android.test.activity;  
  2. import Android.app.Activity;  
  3. import Android.content.Intent;  
  4. import Android.os.Bundle;  
  5. import Android.view.View;  
  6. import Android.view.View.OnClickListener;  
  7. import Android.widget.Button;  
  8. public class MainActivity extends Activity {  
  9.     private Button btn;  
  10.     @Override
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.main);  
  14.           
  15.         btn = (Button)findViewById(R.id.btn);  
  16.         //响应按钮btn事件
  17.         btn.setOnClickListener(new OnClickListener() {        
  18.             @Override
  19.             public void onClick(View v) {  
  20.                 //显示方式声明Intent,直接启动SecondActivity
  21.                 Intent it = new Intent(MainActivity.this,SecondActivity.class);  
  22.                 //启动Activity
  23.                 startActivity(it);            
  24.             }  
  25.         });  
  26.     }  
  27. }

SecondActivity.java

  1. package com.Android.test.activity;  
  2. import Android.app.Activity;  
  3. import Android.content.Intent;  
  4. import Android.os.Bundle;  
  5. import Android.view.View;  
  6. import Android.view.View.OnClickListener;  
  7. import Android.widget.Button;  
  8. public class SecondActivity extends Activity {  
  9.     private Button secondBtn;  
  10.     @Override
  11.     protected void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.second);  
  14.           
  15.         secondBtn=(Button)findViewById(R.id.secondBtn);      
  16.         //响应按钮secondBtn事件
  17.         secondBtn.setOnClickListener(new OnClickListener() {                      
  18.             @Override
  19.             public void onClick(View v) {  
  20.                 //显示方式声明Intent,直接启动MainActivity
  21.                 Intent intent = new Intent(SecondActivity.this,MainActivity.class);  
  22.                 //启动Activity
  23.                 startActivity(intent);                
  24.             }  
  25.         });  
  26.     }  
  27. }

AndroidManifest.xml清单文件,16~18行为SecondActivity在清单文件里的声明

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:Android="http://schemas.android.com/apk/res/android"
  3.       package="com.Android.test.activity"
  4.       Android:versionCode="1"
  5.       Android:versionName="1.0">
  6.     <uses-sdk Android:minSdkVersion="10" />
  7.     <application Android:icon="@drawable/icon" android:label="@string/app_name">
  8.         <activity Android:name=".MainActivity"
  9.                   Android:label="@string/app_name">
  10.             <intent-filter>
  11.                 <action Android:name="android.intent.action.MAIN" />
  12.                 <category Android:name="android.intent.category.LAUNCHER" />
  13.             </intent-filter>
  14.         </activity>
  15.         <activity Android:name=".SecondActivity"
  16.                   Android:label="@string/app_name">
  17.         </activity>
  18.     </application>
  19. </manifest>

效果图:

二.隐式Intent

   下面是同一应用程序中的Activity切换的例子,需要AndroidManifest.xml中增加Activity的声明,并设置对应的Intent Filter和Action,才能被Android的应用程序框架所匹配。

 

MainActivity.java

  1. package com.Android.change.activity;  
  2. import Android.app.Activity;  
  3. import Android.content.Intent;  
  4. import android.os.Bundle;  
  5. import Android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import Android.widget.Button;  
  8. public class MainActivity extends Activity {  
  9.     private Button btn;  
  10.     @Override
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.main);  
  14.         btn = (Button) findViewById(R.id.btn);  
  15.         // 响应按钮btn事件
  16.         btn.setOnClickListener(new OnClickListener() {  
  17.             @Override
  18.             public void onClick(View v) {  
  19.                 // 实例化Intent
  20.                 Intent it = new Intent();  
  21.                 //设置Intent的Action属性
  22.                 it.setAction("com.Android.activity.MY_ACTION");  
  23.                 // 启动Activity
  24.                 startActivity(it);  
  25.             }  
  26.       });    
  27.     }  
  28. }  

SecondActivity.java

  1. package com.Android.change.activity;  
  2. import Android.app.Activity;  
  3. import Android.os.Bundle;  
  4. public class SecondActivity extends Activity {  
  5.     @Override
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.second);  
  9.     }  
  10. }  

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
  3.     android:orientation="vertical"  
  4.     Android:layout_width="fill_parent"
  5.     android:layout_height="fill_parent"
  6.     >
  7.     <TextView  
  8.         Android:layout_width="fill_parent"
  9.         android:layout_height="wrap_content"  
  10.         />
  11.     <Button  
  12.         Android:id="@+id/btn"  
  13.         android:layout_width="wrap_content"
  14.         Android:layout_height="wrap_content"
  15.         android:text="转到SecondActivity"  
  16.         />
  17. </LinearLayout>

seond.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"  
  3.    android:orientation="vertical"  
  4.    Android:layout_width="fill_parent"  
  5.    android:layout_height="fill_parent"  
  6.    >  
  7.    <TextView      
  8.         Android:layout_width="fill_parent"    
  9.         android:layout_height="wrap_content"    
  10.         Android:text="@string/second"  
  11.         />  
  12. </LinearLayout>

    AndroidManifest.xml 文件的18,19行修改了Intent  Filter,这样SecondActivity才能够接收到MainActivity发送的Intent。因为在MainActivity的 Intent发送的动作为"com.android.activity.MY_ACTION",而在18行里,SecondActivity设置的 Action也为"com.android.activity.MY_ACTION",这样就能进行匹配。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:Android="http://schemas.android.com/apk/res/android"
  3.       package="com.android.change.activity"
  4.       Android:versionCode="1"
  5.       android:versionName="1.0">
  6.     <uses-sdk Android:minSdkVersion="10" />
  7.     <application Android:icon="@drawable/icon" android:label="@string/app_name">
  8.         <activity android:name=".MainActivity"
  9.                   Android:label="@string/app_name">
  10.             <intent-filter>
  11.                 <action Android:name="android.intent.action.MAIN" />
  12.                 <category android:name="android.intent.category.LAUNCHER" />
  13.             </intent-filter>
  14.         </activity>
  15.         <activity Android:name=".SecondActivity" >                
  16.         <intent-filter>  
  17.             <action  Android:name = "com.android.activity.MY_ACTION"  />  
  18.             <category android:name = "android.intent.category.DEFAULT"  />  
  19.          </intent-filter>      
  20.         </activity>          
  21.     </application>
  22. </manifest>

效果图:

 

 

    对于显示Intent,Android不 需要再去做解析,因为目标组件很明确。Android需要解析的是隐式Intent,通过解析,将Intent映射给可以处理该Intent的 Activity,Service等。Intent的解析机制主要是通过查找已经注册在AndroidManifest.xml中的所有 IntentFilter以及其中定义的Intent,最终找到匹配的Intent。

Feb 12
一.BroadcastReceiver简介 

   BraodcastReceiver(广播接收器)是为了实现系统广播而提供的一种组件,它和事件处理机制类似,但是事件处理机制是程序组件级别的,而广播事件处理机制是系统级别的。比如,我们可以发出一种广播来测试手机电量的变化,这时候就可以定义一个BraodcastReceiver来接受广播,当手机电量较低时提示用户。我们既可以用Intent来启动一个组件,也可以用sendBroadcast()方法发起一个系统级别的事件广播来传递消息。我们同样可以在自己的应用程序中实现BroadcastReceiver来监听和响应广播的Intent。

   在程序中使用BraodcastReceiver是比较简单的。首先要定义一个类继承BraodcastReceiver,并且覆盖onReceiver()方法来响应事件。然后注册在程序中BraodcastReceiver。最后构建Intent对象调用sendBroadcast()方法将广播发出。

二.BroadcastReceiver的注册方式

 1.静态注册方式

   静态注册方式是在AndroidManifest.xml的application里面定义receiver并设置要接收的action。静态注册方式的特点:不管改应用程序是否处于活动状态,都会进行监听,比如某个程序时监听 内存 的使用情况的,当在手机上安装好后,不管改应用程序是处于什么状态,都会执行改监听方法中的内容。

下面是具体的例子:

MainActivity.java

  1. package com.Android.broadcast;  
  2.  
  3. import Android.app.Activity;  
  4. import Android.content.Intent;  
  5. import Android.os.Bundle;  
  6. import Android.view.View;  
  7. import Android.view.View.OnClickListener;  
  8. import Android.widget.Button;  
  9.  
  10. public class MainActivity extends Activity{  
  11.     //定义action常量  
  12.     protected static final String ACTION = "com.Android.broadcast.RECEIVER_ACTION";  
  13.     //定义Button对象  
  14.     private Button btnBroadcast;  
  15.     @Override 
  16.     public void onCreate(Bundle savedInstanceState){  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.main);  
  19.         btnBroadcast=(Button)findViewById(R.id.btnBroadcast);  
  20.         //为按钮设置单击监听器  
  21.         btnBroadcast.setOnClickListener(new OnClickListener(){  
  22.             @Override 
  23.             public void onClick(View v){  
  24.                 //实例化Intent  
  25.                 Intent intent=new Intent();  
  26.                 //设置Intent的action属性  
  27.                 intent.setAction(ACTION);  
  28.                 //发出广播  
  29.                 sendBroadcast(intent);  
  30.             }  
  31.         });  
  32.     }  

在“com.Android.broadcast”包中定义一个MyReceiver类,继承于BroadcastReceiver,覆盖onReceive()方法。

MyReceiver.java

  1. package com.Android.broadcast;  
  2.  
  3. import Android.content.BroadcastReceiver;  
  4. import Android.content.Context;  
  5. import Android.content.Intent;  
  6. import Android.util.Log;  
  7.  
  8. public class MyReceiver extends BroadcastReceiver{  
  9.    //定义日志标签  
  10.     private static final String TAG = "Test";  
  11.     @Override 
  12.     public void onReceive(Context context, Intent intent){  
  13.         //输出日志信息  
  14.         Log.i(TAG, "MyReceiver onReceive--->");  
  15.     }  
  16. }  

main.xml

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android" 
  3.     Android:orientation="vertical" 
  4.     Android:layout_width="fill_parent" 
  5.     Android:layout_height="fill_parent" 
  6.     > 
  7.     <Button 
  8.         Android:id="@+id/btnBroadcast" 
  9.         Android:layout_width="match_parent" 
  10.         Android:layout_height="wrap_content" 
  11.         Android:text="发送Broadcast" 
  12.         /> 
  13. </LinearLayout> 

AndroidManifest.xml配置文件中16~20行声明receiver

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <manifest xmlns:Android="http://schemas.android.com/apk/res/android" 
  3.       package="com.Android.broadcast" 
  4.       Android:versionCode="1" 
  5.       Android:versionName="1.0"> 
  6.     <uses-sdk Android:minSdkVersion="10" /> 
  7.  
  8.     <application Android:icon="@drawable/icon" android:label="@string/app_name"> 
  9.         <activity Android:name=".MainActivity" 
  10.                   Android:label="@string/app_name"> 
  11.             <intent-filter> 
  12.                 <action Android:name="android.intent.action.MAIN" /> 
  13.                 <category Android:name="android.intent.category.LAUNCHER" /> 
  14.             </intent-filter> 
  15.         </activity> 
  16.         <receiver Android:name="MyReceiver"> 
  17.             <intent-filter> 
  18.                 <action Android:name="com.android.broadcast.RECEIVER_ACTION"/> 
  19.             </intent-filter> 
  20.         </receiver> 
  21.     </application> 
  22. </manifest> 

效果图:

 

 当我们点击按钮的时候,程序会调用onReceive()方法,LogCat输出信息如下:

2.动态注册方式

   动态注册方式在activity里面调用函数来注册,和静态的内容差不多。一个形参是receiver,另一个是IntentFilter,其中里面是要接收的action。动态注册方式特点:在代码中进行注册后,当应用程序关闭后,就不再进行监听。

下面是具体的例子:

 MainActivity.java

  1. package com.Android.broadcast;  
  2.  
  3. import Android.app.Activity;  
  4. import Android.content.Intent;  
  5. import android.content.IntentFilter;  
  6. import Android.os.Bundle;  
  7. import android.view.View;  
  8. import Android.view.View.OnClickListener;  
  9. import android.widget.Button;  
  10.  
  11. public class MainActivity extends Activity{  
  12.     //定义Action常量  
  13.     protected static final String ACTION = "com.Android.broadcast.RECEIVER_ACTION";  
  14.     private Button btnBroadcast;  
  15.     private Button registerReceiver;  
  16.     private Button unregisterReceiver;  
  17.     private MyReceiver receiver;  
  18.     @Override 
  19.     public void onCreate(Bundle savedInstanceState){  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main);  
  22.         btnBroadcast=(Button)findViewById(R.id.btnBroadcast);  
  23.         //创建事件监听器  
  24.         btnBroadcast.setOnClickListener(new OnClickListener(){  
  25.             @Override 
  26.             public void onClick(View v){  
  27.                 Intent intent=new Intent();  
  28.                 intent.setAction(ACTION);  
  29.                 sendBroadcast(intent);  
  30.             }  
  31.         });  
  32.           
  33.         registerReceiver=(Button)findViewById(R.id.btnregisterReceiver);  
  34.         //创建事件监听器  
  35.         registerReceiver.setOnClickListener(new OnClickListener(){  
  36.             @Override 
  37.             public void onClick(View v){  
  38.                 receiver=new MyReceiver();  
  39.                 IntentFilter filter=new IntentFilter();  
  40.                 filter.addAction(ACTION);  
  41.                 //动态注册BroadcastReceiver  
  42.                 registerReceiver(receiver, filter);  
  43.             }  
  44.         });  
  45.           
  46.         unregisterReceiver=(Button)findViewById(R.id.btnunregisterReceiver);  
  47.         //创建事件监听器  
  48.         unregisterReceiver.setOnClickListener(new OnClickListener(){  
  49.             @Override 
  50.             public void onClick(View v){  
  51.                 //注销BroadcastReceiver  
  52.                 unregisterReceiver(receiver);  
  53.             }  
  54.         });  
  55.     }  

 在“com.Android.broadcast”包中定义一个MyReceiver类,继承于BroadcastReceiver,覆盖onReceive()方法。

MyReceiver.java

  1. package com.Android.broadcast;  
  2.  
  3. import Android.content.BroadcastReceiver;  
  4. import Android.content.Context;  
  5. import android.content.Intent;  
  6. import Android.util.Log;  
  7.  
  8. public class MyReceiver extends BroadcastReceiver{  
  9.     //定义日志标签  
  10.     private static final String TAG = "Test";  
  11.     @Override 
  12.     public void onReceive(Context context, Intent intent){  
  13.         //输出日志信息  
  14.         Log.i(TAG, "MyReceiver onReceive--->");  
  15.     }  
  16. }  

main.xml

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android" 
  3.     android:orientation="vertical" 
  4.     Android:layout_width="fill_parent" 
  5.     android:layout_height="fill_parent" 
  6.     > 
  7.     <Button 
  8.         Android:id="@+id/btnBroadcast" 
  9.         android:layout_width="match_parent" 
  10.         Android:layout_height="wrap_content" 
  11.         android:text="发送广播" 
  12.         /> 
  13.     <Button 
  14.         Android:id="@+id/btnregisterReceiver" 
  15.         android:layout_width="match_parent" 
  16.         Android:layout_height="wrap_content" 
  17.         android:text="注册广播接收器" 
  18.         /> 
  19.     <Button 
  20.         Android:id="@+id/btnunregisterReceiver" 
  21.         android:layout_width="match_parent" 
  22.         Android:layout_height="wrap_content" 
  23.         android:text="注销广播接听器" 
  24.         /> 
  25. </LinearLayout> 

效果图:


 

①当我们首先点击按钮的时候,因为程序没有注册BraodcastReceiver,所以LogCat没有输出任何信息。

②当我们先点击再点击按钮的时候,这时程序会动态的注册BraodcastReceiver,之后会调用onReceive()方法,LogCat输出信息如下:

  

 当我们点击按钮的时候,这时程序会注销BraodcastReceiver,再点击,LogCat没有输出任何信息。

三.BroadcastReceiver 的生命周期

   一个BroadcastReceiver 对象只有在被调用onReceive(Context, Intent)的才有效的,当从该函数返回后,该对象就无效的了,结束生命周期。

分页: 2/8 第一页 上页 1 2 3 4 5 6 7 8 下页 最后页 [ 显示模式: 摘要 | 列表 ]