AndoridのProcess and Threads

21826 ワード

一: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 .
  • Params , the type of the parameters sent to the task upon execution.//入力パラメータ
  • Progress , the type of the progress units published during the background computation.//セルパラメータフォーマット
  • 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"/>
    
        <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]);
            }
        }
    }