zoukankan      html  css  js  c++  java
  • handler以及AnyscTask处理机制

    1、Handler

    主文件:MainActivity.java

    package com.example.asynctaskdownload;
    
    import java.io.IOException;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.StatusLine;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
     protected static final int SHOW_RESPONSE = 0;
    /** Called when the activity is first created. */
        private TextView textView;
        private String result = "";
        
    /////////////////////////////////////////////////////////    
        private Handler handler = new Handler(){
            
            public void handleMessage(Message msg)
            {
                switch(msg.what){
                case SHOW_RESPONSE:
                    String result = (String)msg.obj;
                    //注意是在此处进行UI操作
                    textView.setText(result);
                }
            }
        };
    /////////////////////////////////////////////////////    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.TextView01);
        Button button = (Button) findViewById(R.id.readWebpage);
        button.setOnClickListener(new OnClickListener()
        {
    
            @Override
            public void onClick(View v) {
                //
                //textView.setText(result);
                if(v.getId() == R.id.readWebpage)
                {
                    sendRequestHttpUrl();
                }
            }
    
            
            
        });
    }
    ////////////////////////////////////////////////////////    
    protected void sendRequestHttpUrl() {
        // TODO Auto-generated method stub
        // 
        new Thread(new Runnable()
        {
    
            @Override
            public void run() {
                // 
                
                try
                {
                    HttpClient client = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet("http://10.0.2.2:8080/mp3/a1.lrc");
                    
                    HttpResponse response = client.execute(httpGet);
                    StatusLine statusLine = response.getStatusLine();
                    int statusCode = statusLine.getStatusCode();
                    if (statusCode == 200) {
                        HttpEntity entity = response.getEntity();
                        //关于此处中文乱码问题解决?文本文件保存时,文本文档默认为ANSI编码格式,另存为时手动改为utf-8格式即可
                        result = EntityUtils.toString(entity, "utf-8");
                    }
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;
                    message.obj = result.toString();
                    handler.sendMessage(message);
                }catch(Exception ex)
                {
                    ex.printStackTrace();
                }
                
            }
            
        }
        ).start();
    }
    }

    activity_main.xml文件

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <Button
            android:id="@+id/readWebpage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:text="Load Webpage" >
        </Button>
        <ScrollView 
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
            android:id="@+id/TextView01"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Placeholder" >
            </TextView>
        </ScrollView>
        
        
    
    </LinearLayout> 

    运行结果:

    2、AnyscTask

    主代码:

    package com.example.asynctaskdownload;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    
    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.Environment;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
      private TextView textView;
      
      private final String fileName = "a1.lrc";
      //private final String fileUrl = "http://10.0.2.2:8080/mp3/a1.lrc";
      private int result = Activity.RESULT_CANCELED;
      private String response = "";
     
    
      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.TextView01);
        Button button = (Button) findViewById(R.id.readWebpage);
        button.setOnClickListener(new OnClickListener()
        {
    
            @Override
            public void onClick(View v) {
                // 
                
                DownloadWebPageTask task = new DownloadWebPageTask();
                //task.execute(new String[] { "http://www.vogella.com" });
                task.execute(new String[] { "http://10.0.2.2:8080/mp3/a1.lrc" });
                Toast.makeText(MainActivity.this, "Download Success!", Toast.LENGTH_LONG).show();
                
    //            textView.setText(response);
            }
            
        });
      }
    
      private class DownloadWebPageTask extends AsyncTask<String, Void, Integer> {
        @Override
        protected Integer doInBackground(String... urls) {
          //获取sdcard的路径,以及设置保存的文件名    
          File output = new File(Environment.getExternalStorageDirectory(), fileName);
          if(output.exists())
          {
              output.delete();//若同名文件已存在则删除
          }
          
    //      String response = "";
          InputStream content = null;
          FileOutputStream fos = null;
          //遍历url数组中的url,采用HttpClient(接口)的方式访问网络
          for (String url : urls) {
            //首先创建一个DefaultHttpClient实例
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);//发起一个GET请求,创建一个HttpGet对象,并传入目标网络地址
            try {
              HttpResponse execute = client.execute(httpGet);//调用execute执行访问请求并返回一个HttpResponse对象
              if(execute.getStatusLine().getStatusCode() == 200)
              {
                  //注:下面两行code只能使用其中一个:content will be consume only once
                  //execute.getEntity()调用了两次
     //             content = execute.getEntity().getContent();//获取服务返回的具体内容
                  //调用EntityUtils.toString该静态方法将HttpEntity转换成字符串,为避免中文字符乱码,添加utf-8字符集参数
    //              response = EntityUtils.toString(execute.getEntity(), "utf-8");
    //////////////////////////////////////////////////////////////////////////////
                  HttpEntity entity = execute.getEntity();
     //             response = EntityUtils.toString(entity, "utf-8");
                  content = entity.getContent();
                  
                  
              }
              
              //利用管道 inputstream-->reader
              InputStreamReader reader = new InputStreamReader(content);
              fos = new FileOutputStream(output.getPath());
              
              int next = -1;
              while ((next = reader.read()) != -1) {
                fos.write(next);
              }
              
              result = Activity.RESULT_OK;
    
    //          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
              
              
    //          String s = "";
    //          while ((s = buffer.readLine()) != null) {
    //            response += s;
    //          }
    
            } catch (Exception e) {
              e.printStackTrace();
            }finally {
                if (content != null) {
                    try {
                      content.close();
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }
                  if (fos != null) {
                    try {
                      fos.close();
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }
          }
        }
        return result;
      }
        
       
        protected void onPostExecute(Integer result) {
        //此处可以根据后台任务完成后返回的结果进行一些UI操作
          
            if(result == Activity.RESULT_OK)
            {
                textView.setText("mp3 file download success!!");
            }
        }
    
     /* public void onClick(View view) {
        DownloadWebPageTask task = new DownloadWebPageTask();
        //task.execute(new String[] { "http://www.vogella.com" });
        task.execute(new String[] { "http://10.0.2.2:8080/mp3/a1.lrc" });
    
      }*/
      
      }
    }

    activity_main.xml文件同上

    运行结果:成功下载文件a1.lrc到sdcard中

  • 相关阅读:
    HTML DOM 12 表格排序
    HTML DOM 10 常用场景
    HTML DOM 10 插入节点
    HTML DOM 09 替换节点
    HTML DOM 08 删除节点
    HTML DOM 07 创建节点
    022 注释
    024 数字类型
    005 基于面向对象设计一个简单的游戏
    021 花式赋值
  • 原文地址:https://www.cnblogs.com/CoolRandy/p/4323952.html
Copyright © 2011-2022 走看看