自学内容网 自学内容网

Android 中线程网络超时的处理

Android开发中经常需要调用线程访问网络,而手机的网络信号经常断断续续,容易出现网络超时的情况,这种情况下后台线程往往得不到关闭,浪费系统资源。

在下面的例子中使用了java 中的Timer类,对线程进行了约束,如果线程在一定时间内为响应则终止该线程。

import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity {

    private static final int TIME_OUT = 0;
    private static final int SUCCESS = 1;

    // 超时的时限为5秒
    private static final int TIME_LIMIT = 5000;
    private ProgressDialog proDialog;
    private Timer timer;
    private Thread threadTimeOut;
    private Button btn1, btn2;

@Override  
protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_main);  
    btn1 = (Button) findViewById(R.id.button1);  
    btn2 = (Button) findViewById(R.id.button2);  
    // 测试未超时的线程,为btn1绑定事件  
    btn1.setOnClickListener(new OnClickListener() {  
        @Override  
        public void onClick(View v) {  
            proDialog = ProgressDialog.show(MainActivity.this, "提示",  
                    "线程运行中");  
            // 匿名内部线程  
            threadTimeOut = new Thread() {  
                @Override  
                public void run() {  
                    while (true) {  
                        try {  
                            //线程休眠时间,超时  
                            sleep(10000);  
                        } catch (InterruptedException   e) {  
                            break;  
                        }  
                    }  

                }  
            };  
            thread.start();  
            // 设定定时器  
            timer = new Timer();  
            timer.schedule(new TimerTask() {  
                @Override  
                public void run() {  
                    sendTimeOutMsg();  
                }  
            }, TIME_LIMIT);  

        }  
    });  
    // 测试超时的线程,为btn2绑定事件  
    btn2.setOnClickListener(new OnClickListener() {  
        @Override  
        public void onClick(View v) {  

            proDialog = ProgressDialog.show(MainActivity.this, "提示",  
                    "线程运行中");  
            // 匿名内部线程  
            thread = new Thread() {  
                public void run() {  
                    try {  
                        // 线程休眠时间,未超时  
                        Thread.sleep(3000);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                    Message msgSuc = new Message();  
                    msgSuc.what = SUCCESS;  
                    myHandler.sendMessage(msgSuc);  
                }  
            };  
            thread.start();  
            // 设定定时器  
            timer = new Timer();  
            timer.schedule(new TimerTask() {  
                @Override  
                public void run() {  
                    sendTimeOutMsg();  
                }  
            }, TIME_LIMIT);  
        }  
    });  
} 
private MyHandler myHandler = null;
    //Handler静态内部类
    private static class MyHandler extends Handler {
        //弱引用
        WeakReference<SceneryLightControlSingleFragment> weakReference;

        public MyHandler(SceneryLightControlSingleFragment activity) {
            weakReference = new WeakReference<SceneryLightControlSingleFragment>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SceneryLightControlSingleFragment activity = weakReference.get();
            if (activity != null) {
                switch (msg.what) {
                     case TIME_OUT:  
            //打断线程  
            thread.interrupt();  
            proDialog.dismiss();  
            Toast.makeText(MainActivity.this, "线程超时", Toast.LENGTH_SHORT)  
                    .show();  
            break;  
        case SUCCESS:  
            //取消定时器  
            timer.cancel();  
            proDialog.dismiss();  
            Toast.makeText(MainActivity.this, "线程运行完成", Toast.LENGTH_SHORT)  
                    .show();  
            break;  
        default:  
            break;  
                }
            }
        }
    }
    
//向handler发送超时信息  
private void sendTimeOutMsg() {  
    Message timeOutMsg = new Message();  
    timeOutMsg.what = TIME_OUT;  
    myHandler.sendMessage(timeOutMsg);  
}  
 @Override
    public void onDestroy() {
        if(myHandler!= null) {
            myHandler.removeCallbacksAndMessages(null);
        }
        if(threadTimeOut != null){
            if(threadTimeOut.isAlive()){
                threadTimeOut.interrupt();
            }
        }
        super.onDestroy();
    }
} 

原文地址:https://blog.csdn.net/weixin_38090079/article/details/143799589

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!