美文网首页Android笔记
Android线程相关编程

Android线程相关编程

作者: Cedric_h | 来源:发表于2019-07-23 07:09 被阅读0次

    原文:https://blog.csdn.net/uyy203/article/details/51938462

    定时每秒递增,向handler发送消息以刷新UI

    注意:Handler所需导入的相关包为android.os.Handler;

    public class MainActivity extends AppCompatActivity {
    
        private Button button1, button2, button3;
        private TextView Tx1;
        private TextView Tx2;
    
        public Timer mTimer1;
        public TimerTask mTimerTask1;
    
        public Timer mTimer2;
        public TimerTask mTimerTask2;
    
        public int i=0;
        public int j=0;
        public boolean isTimer1Running=false;
        public boolean isTimer2Running=false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
            button1 = (Button) findViewById(R.id.button1);
            button2 = (Button) findViewById(R.id.button2);
            button3 = (Button) findViewById(R.id.button3);
    
    
    
            button1.setOnClickListener(new View.OnClickListener() {//启动或终止每秒+1的线程  
                @Override
                public void onClick(View view) {
    //                Toast.makeText(getBaseContext(),"Button1",Toast.LENGTH_SHORT).show();  
                    manager1();//处理函数1  
                }
            });
    
            button2.setOnClickListener(new View.OnClickListener() {//启动或终止每秒+5的线程  
                @Override
                public void onClick(View view) {
    //                Toast.makeText(getBaseContext(),"button2",Toast.LENGTH_SHORT).show();  
                    manager2();//处理函数2  
                }
            });
    
            button3.setOnClickListener(new View.OnClickListener() {//清零所有数值  
                @Override
                public void onClick(View view) {
                    i=0;
                    j=0;
                    Toast.makeText(getBaseContext(),"清零",Toast.LENGTH_SHORT).show();
                }
            });
    
        }
        
    
        public void manager1(){//向handle1发送刷新UI的消息  
            isTimer1Running=!isTimer1Running;
    
            if(isTimer1Running) {
                mTimer1=new Timer();
                mTimerTask1 = new TimerTask() {
                    @Override
                    public void run() {
                        i++;
    
                        Bundle b1 = new Bundle();
    
                        b1.putString("mes", Integer.toString(i));
    
    
                        Message msg = new Message();
    
                        msg.setData(b1);
    
                        MainActivity.this.myHandler.sendMessage(msg);
                        
                    }
                };
    
                mTimer1.schedule(mTimerTask1, 1000, 1000);
    
                Toast.makeText(getBaseContext(),"每秒+1线程启动",Toast.LENGTH_SHORT).show();
            }
            else {
                mTimer1.cancel();
                mTimerTask1.cancel();
                Toast.makeText(getBaseContext(),"每秒+1线程终止",Toast.LENGTH_SHORT).show();
            }
            
        }
    
    
    
        void manager2(){//向handle1发送刷新UI的消息  
    
            isTimer2Running=!isTimer2Running;
    
            if(isTimer2Running) {
                mTimer2 = new Timer();
                mTimerTask2 = new TimerTask() {
                    @Override
                    public void run() {
                        j += 50;
    
                        Bundle b2 = new Bundle();
                        b2.putString("mes2", Integer.toString(j));
    
                        Message msg = new Message();
                        msg.setData(b2);
    
                        MainActivity.this.myHandler.sendMessage(msg);
    
                    }
                };
    
                mTimer2.schedule(mTimerTask2, 1000, 1000);
    
                Toast.makeText(getBaseContext(),"每秒+50线程启动",Toast.LENGTH_SHORT).show();
            }
            else{
                mTimer2.cancel();
                mTimerTask2.cancel();
    
                Toast.makeText(getBaseContext(),"每秒+50线程终止",Toast.LENGTH_SHORT).show();
    
            }
    
        }
    
        
    
        private final Handler myHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {//收到消息后刷新UI界面  
                super.handleMessage(msg);
    
                Tx1=(TextView)findViewById(R.id.TX1);
                Tx2=(TextView) findViewById(R.id.TX2);
                Bundle b=msg.getData();
    
    
                String mess=b.getString("mes");
                if(mess!=null&&mess!="")
                    Tx1.setText(mess);
    
    
                String mess2=b.getString("mes2");
                if(mess2!=null&&mess2!="")
                    Tx2.setText(mess2);
    
            }
    
        };
        
    }  
    
    

    New Thread

    public void onClick(View view) {
    
        new Thread(new Runnable(){
            @Override
            public void run() {
                i++;
                Bundle b=new Bundle();
                b.putString("mes1",Integer.toString(i));
    
                Message m=new Message();
                m.setData(b);
    
                MainActivity.this.myHandler.sendMessage(m);//向myHandler发送消息,以刷新UI
            }
        }).start();
    

    AsyncTask

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.xyz.test.MainActivity">
    
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="下载"
            android:id="@+id/download"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
        <android.support.v4.widget.ContentLoadingProgressBar
            android:id="@+id/pb"
            android:layout_below="@id/download"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="?android:progressBarStyleHorizontal"
            />
    
        <ImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/pb"
            />
    
    </RelativeLayout>
    

    MainActivity.java

    package com.example.xyz.test;
    
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.ProgressBar;
    import android.widget.Toast;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    
    
    public class MainActivity extends AppCompatActivity {
        private Button download;
        public ImageView image;
        public ProgressBar pb;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            download=(Button)findViewById(R.id.download);
            pb=(ProgressBar) findViewById(R.id.pb);
            image=(ImageView) findViewById(R.id.image);
    
    
            download.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    pb.setProgress(0);//进度条清零
                    DownLoad dt=new DownLoad();//每次调用都需要NEW一次
                    dt.execute("http://avatar.csdn.net/7/0/6/1_uyy203.jpg");//执行异步任务
                }
            });
    
    
        }
    
        class DownLoad extends AsyncTask<String,Integer,Bitmap> {
            Bitmap bm=null;
            byte[] data=new byte[1024];
    
            @Override
            protected void onPreExecute() {//执行处理前执行的函数
                super.onPreExecute();
                image.setImageBitmap(null);
                pb.setProgress(0);//设置进度为0
            }
    
            @Override
            protected Bitmap doInBackground(String... params) {//后台处理,主要完成耗时操作
                publishProgress(0);//将会调用onProgressUpdate(Integer... progress)方法,并向其以整型的形式传递处理进度信息
    
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//字节输出流
                InputStream inputStream=null;//字节输入流
    
                try{
                    HttpClient httpClient=new DefaultHttpClient();
                    HttpGet httpGet=new HttpGet(params[0]);//获取图片
                    HttpResponse httpResponse=httpClient.execute(httpGet);
    
                    if(httpResponse.getStatusLine().getStatusCode()==200){//判断响应是否有效
                        inputStream=httpResponse.getEntity().getContent();
    
                        long file_length=httpResponse.getEntity().getContentLength();//获取文件总长度
                        int len=0;
                        int total_length=0;//已下载文件的长度
                        int value=0;//进度值
    
                        while ((len=inputStream.read(data))!=-1){//当输入流有数据即循环获取数据
                            total_length+=len;
                            value=(int)((total_length/(float)file_length)*100);//计算下载进度
    
                            publishProgress(value);//传递进度值,并刷新UI
                            outputStream.write(data,0,len);//将下载的数据放进输出流中
    
                            bm=BitmapFactory.decodeByteArray(outputStream.toByteArray(),0,outputStream.toByteArray().length);//将输出流字节转为Bitmap
                        }
    
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    return null;//返回空值
                }
                finally {
                    if(inputStream!=null)
                        try{
                            inputStream.close();//输入流关闭
                        }catch (Exception e){
                            e.printStackTrace();
                        }
    
                }
    
                return bm;//图片数据以Bitmap形式返回,以参数形式传入onPostExecute中,作后续处理
            }
    
            @Override
            protected void onProgressUpdate(Integer... values) {//在调用publishProgress之后被调用,在ui线程执行
                super.onProgressUpdate(values);
                pb.setProgress(values[0]);//更新UI进度条
            }
    
            @Override
            protected void onPostExecute(Bitmap bitmap) {//在doInBackground执行后自动执行的处理函数,以参数的形式传入doInBackground的返回值
                super.onPostExecute(bitmap);
                if(bitmap!=null){
                    Toast.makeText(MainActivity.this,"successed!",Toast.LENGTH_SHORT).show();
                    image.setImageBitmap(bitmap);//显示图片
                }
                else {
                    Toast.makeText(MainActivity.this,"failed!",Toast.LENGTH_SHORT).show();
                }
    
            }
    
            protected void onCancelled () {//在ui线程执行
                pb.setProgress(0);//进度条复位
            }
    
        }
    
    
    
    }
    

    AndroidManifest.xml

    在<application></application>外 加入访问互联网权限

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

    相关文章

      网友评论

        本文标题:Android线程相关编程

        本文链接:https://www.haomeiwen.com/subject/injnlctx.html