Afterclicking the button that initiates the download, Android will give your application nomore than a few seconds to respond to that input event. Otherwise, it’ll kill it andraise the previously mentioned ANR exception. For BroadcastReceivers, Android ismore forgiving and waits longer before pulling the plug, but it also monitors their
execution time.

SimpleImageDownload.java uses java.lang.Thread to download an image file:

public class SimpleImageDownload extends Activity {private Runnable imageDownloader=new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubtry {URL url=new URL("http://www.android.com/images/froyo.png");Bitmap image=BitmapFactory.decodeStream(url.openStream());if (image != null) {Log.i("DL", "Successfully retrieved file!");} else {Log.i("DL", "Failed decoding file from stream");}} catch (Exception e) {Log.i("DL", "Failed downloading file!");e.printStackTrace();}}};private void startDownload(){new Thread(imageDownloader,"Download thread").start();TextView statusText=(TextView)findViewById(R.id.status);statusText.setText("Download started...");}    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);    }}

The layout file main.xml defines the button and the status text view

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="center"><Button android:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:text="Download file"android:onClick="startDownload"/><TextView android:id="@+id/status"    android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:text="click to start"/></LinearLayout>

It turns out that a thread lives as long as it takes its run method to terminate.It’s not bound to the component that started it, and can even outlive it. This hasa curious implication: it means that you must be extremely cautious about keeping referencesto things such as an Activity in your thread because the Activity may finishbefore your thread terminates. The runtime will keep the Activity object aroundbecause you hold a strong reference to it, but its lifecycle from the perspective of theframework has ended!


更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. SQLServer 快速备份的十种方法
  2. sql2000 卸载后重新安装时不能安装的解决
  3. sqlserver 无法验证产品密匙的完美解决方
  4. 数据库的一些常用知识
  5. SQLServer 连接异常与解决方法小结
  6. SQLServer 通用的分区增加和删除的算法
  7. SQLServer 批量插入数据的两种方法
  8. SQL Server使用Merge语句当源表数据集为
  9. SQLServer XML数据的五种基本操作
  10. Sql 批量查看字符所在的表及字段