Andorid之Process and Threads

一:AsyncTask(框架)

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

  1. Params, the type of the parameters sent to the task upon execution. //输入参数
  2. Progress, the type of the progress units published during the background computation. //单元参数格式
  3. Result, the type of the result of the background computation.//返回参数

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

private class MyTask extends AsyncTask<Void, Void, Void> { ... }
package com.example.android_asynctask;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.example.android_asynctask.R.string;

import android.R.id;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Entity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
    private Button button;
    private ImageView imageView;
    private ProgressDialog progressDialog;
    private final String image_path="http://www.baidu.com/img/bdlogo.gif";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)this.findViewById(R.id.button1);
        imageView=(ImageView)this.findViewById(R.id.imageView1);
        progressDialog=new ProgressDialog(this);
        progressDialog.setTitle("提示!");
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在下载图片,请耐心等候~~~");
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                new MyTast().execute(image_path);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    class MyTast extends AsyncTask<String, Integer, byte[]>{

        @Override
        protected byte[] doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            HttpClient httpClient=new DefaultHttpClient();
            HttpGet httpGet =new HttpGet(arg0[0]);
            byte[] result=null;
            try {
                HttpResponse httpResponse=httpClient.execute(httpGet);
                if(httpResponse.getStatusLine().getStatusCode()==200){
                    result=EntityUtils.toByteArray(httpResponse.getEntity());
                }
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }finally{
                httpClient.getConnectionManager().shutdown();
            }
            return result;
        }
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            progressDialog.show();
        }
        //更新ui
        @Override
        protected void onPostExecute(byte[] result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Bitmap bitmap=BitmapFactory.decodeByteArray(result, 0,result.length);
            imageView.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }
    }
}

必须要添加访问授权<uses-permission android:name="android.permission.INTERNET"/>

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.android_asynctask.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

跨线程更新UI的方法在onPostExecute中持行

onProgressUpdate使用AsyncTask的单元参数Progress

package com.example.android_asynctask;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.example.android_asynctask.R.string;

import android.R.id;
import android.R.integer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Entity;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
    private Button button;
    private ImageView imageView;
    private ProgressDialog progressDialog;
    private final String image_path="http://www.baidu.com/img/bdlogo.gif";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)this.findViewById(R.id.button1);
        imageView=(ImageView)this.findViewById(R.id.imageView1);
        progressDialog=new ProgressDialog(this);
        progressDialog.setTitle("提示!");
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在下载图片,请耐心等候~~~");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                new MyTast().execute(image_path);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    class MyTast extends AsyncTask<String, Integer, byte[]>{

        @Override
        protected byte[] doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            HttpClient httpClient=new DefaultHttpClient();
            HttpGet httpGet =new HttpGet(arg0[0]);
            byte[] result=null;//图片的所以内容
            InputStream inputStream =null;
            ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
            try {
                HttpResponse httpResponse=httpClient.execute(httpGet);
                long file_length=httpResponse.getEntity().getContentLength();
                int total_length=0;
                byte[] data=new byte[1024];
                int len=0;
                if(httpResponse.getStatusLine().getStatusCode()==200){
                    //result=EntityUtils.toByteArray(httpResponse.getEntity());
                    inputStream=httpResponse.getEntity().getContent();
                    while ((len=inputStream.read(data))!=-1) {
                        total_length+=len;
                        int process_value=(int)((total_length/(float)file_length)*100);
                        publishProgress(process_value);//发布刻度单位
                        outputStream.write(data,0,len);
                    }
                }
                result=outputStream.toByteArray();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }finally{
                httpClient.getConnectionManager().shutdown();
            }
            return result;
        }
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            progressDialog.show();
        }
        //更新ui
        @Override
        protected void onPostExecute(byte[] result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Bitmap bitmap=BitmapFactory.decodeByteArray(result, 0,result.length);
            imageView.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
            progressDialog.setProgress(values[0]);
        }
    }
}
时间: 2024-08-06 16:06:21

Andorid之Process and Threads的相关文章

android sdk Process and Threads 翻译

当一个应用程序刚开始运行,同时这个应用程没有其他的正在运行的组件,android系统将会以一个单独运行的线程方式为这个应用程序开启一个新的linux进程.默认的,一个应用程序上的所有的组件运行在相同的进程和线程(被叫做“main”的线程上)上.如果一个应用程序组件开始运行时,同时为这个应用程序也存在一个进程(因为这个应用程序存在的其他的组件),那么这个组件在这个进程中运行并且使用正在执行的那个线程.然而,您可以安排不同的组件在你的应用程序去运行在单独的进程中,你还可以为任何进程创建额外的线程这篇

2.App Components-Processes and Threads

1. Processes and Threads When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all compone

【Android文档】Processes and Threads

大致翻译一下,记录笔记. 原文地址:Processes and Threads Processes and Threads 当一个app的组件(这里一般指四大组件Activity,Service等)启动时,如果此时系统没有其他组件正在运行,则android系统会为该app启动一个新的linux进程,而且该进程中只有一个线程.默认情况下,app中的所有组件,都运行在同个进程中的同个线程(称为主线程).如果一个app的组件启动时,该app中已经存在一个进程,则该组件将运行在同一个进程中,并且使用同一

Difference between Process and thread?

What are the differences between a process and a thread? How are they similar? How can 2 threads communicate? How can 2 process communicate? Both processes and threads are independent sequences of execution. The main difference is that threads (of th

Android02.常用布局及基本UI控件

一.Android学习API指南:[了解] 1. 应用的组成部分   App Components 1.1. 应用的基本原理    App Fundamentals 1.2. Activity      Activities 1.2.1. 片段    Fragments 1.2.2. 加载器     Loaders 1.2.3. 任务和返回堆    Tasks and Back Stack 1.3. Service服务   Services 1.3.1. 绑定服务     Bound Servi

(C/C++) Interview in English - Threading

Q. What's the process and threads and what's the difference between them? A.  A process is an executing program. One or more threads run in the context of the process.  It has a primary thread. A thread is the basic unit to which the operating system

统计代码执行时间,使用Stopwatch和UserProcessorTime的区别

当我们需要统计一段代码的执行时间,首先想到的可能是Stopwatch类.在这里,先暂不使用Stopwatch,自定义一个统计代码执行时间的类,大致需要考虑到: 1.确保统计的是当前进程.当前线程中代码的执行时间.2.在统计执行过程中,不允许有垃圾回收.即在统计代码执行时间之前,就让GC完成垃圾回收. 举例:统计显示一个数组元素所消耗的时间 class Program { static void Main(string[] args) { int[] arrs = new int[10000];

33、线程与全局解释器锁(GIL)

之前我们学了很多进程间的通信,多进程并发等等,今天我们来学习线程,线程和进程是什么关系,进程和线程有什么相同而又有什么不同今天就来揭晓这个答案. 一.线程概论 1.何为线程 每个进程有一个地址空间,而且默认就有一个控制线程.如果把一个进程比喻为一个车间的工作过程那么线程就是车间里的一个一个流水线. 进程只是用来把资源集中到一起(进程只是一个资源单位,或者说资源集合),而线程才是cpu上的执行单位. 多线程(即多个控制线程)的概念是,在一个进程中存在多个控制线程,多个控制线程共享该进程的地址空间(

WINDOWS操作系统中可以允许最大的线程数

默认情况下,一个线程的栈要预留1M的内存空间 而一个进程中可用的内存空间只有2G,所以理论上一个进程中最多可以开2048个线程 但是内存当然不可能完全拿来作线程的栈,所以实际数目要比这个值要小. 你也可以通过连接时修改默认栈大小,将其改的比较小,这样就可以多开一些线程. 如将默认栈的大小改成512K,这样理论上最多就可以开4096个线程. 即使物理内存再大,一个进程中可以起的线程总要受到2GB这个内存空间的限制. 比方说你的机器装了64GB物理内存,但每个进程的内存空间还是4GB,其中用户态可用