广播与线程问题通过广播监测网络连接从而控制手机自动重启时,连接上网络后无法取消重启

移动开发 码拜 5年前 (2016-06-09) 616次浏览
需求:手机没有网络后,延时30秒,假如手机还没有网络那么立即重启,30秒过程中一旦连上网络则取消重启。
思路1:通过广播监控网络连接状态,手机网络断开之后启动IntentService,通过子线程来延时30秒,之后重启。此方法需要在广播中将网络连接参数传入service,本人只知道通过intent然后startService传给service,但是由于联网与断网需要传两次,因此使用两次startService会新建单独的子线程,经过实验,第一个子线程30秒重启完毕之后才会新建第二条子线程,因此这个方法没有成功。
思路2:在service中接收广播,但是不知道什么原因,由联网切换到断网或由断网切换到联网的时候,切换后的状态并不会执行,例如断网30秒的时候会重启,但是30秒内连上网络,联网的代码并不会得到执行。
思路3:舍弃service,在activity中接收广播,通过断网设定断网变量,联网设置联网变量,通过判断变量的值来重启或取消。可惜本人在断网延时30秒然后重启,在30秒未到的时候联网,然而断网状态下的代码会执行完毕,不能取消重启

package com.riying.introduce.testo;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity{
    private static String TAG="##################";
   /* private NetworkChangeReceiver networkChangeReceiver;*/
    private Dialog dialog;
    private Intent startservice=null;
    private int batteryChange;
    private int netChange;
    private int noNetChange;
    private int a;
    private IntentFilter intentFilter;
    private NetworkChangeReceiver networkChangeReceiver;
    private BatteryChangeReceiver batteryChangeReceiver;
    int level;
    int scale;
    int total;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
           /*充电状态检测*/
        batteryChangeReceiver=new BatteryChangeReceiver();
        registerReceiver(batteryChangeReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
             /*网络监测*/
        intentFilter=new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver=new NetworkChangeReceiver();
        registerReceiver(networkChangeReceiver,intentFilter);
        
    }
    @Override
    protected void onDestroy() {
        unregisterReceiver(networkChangeReceiver);
        unregisterReceiver(batteryChangeReceiver);
        super.onDestroy();
        /*unregisterReceiver(networkChangeReceiver);*/
    }
    class BatteryChangeReceiver extends BroadcastReceiver{
        private static final String TAG = "##";
        /*   private PowerManager pm=null;
           private PowerManager.WakeLock wakeLock=null;*/
        @Override
        public void onReceive(final Context context, Intent intent) {
            String action=intent.getAction();
            level=intent.getIntExtra("level",0);
            scale=intent.getIntExtra("scale",0);
            total=(level*100)/scale;
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)){
                int status=intent.getIntExtra("status", BatteryManager.BATTERY_HEALTH_UNKNOWN);
                if (status==BatteryManager.BATTERY_STATUS_CHARGING||total==100){
                    Log.e(TAG,"--正在充电");
                    batteryChange=1;
                }else {
                    Log.e(TAG,"电源已断开");
                    batteryChange=0;
                }
            }
        }
    }
    class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager=(ConnectivityManager)context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
            /*根据网络状态弹出对话框*/
            if (networkInfo!=null&&networkInfo.isAvailable()){
                noNetChange=1;
                if (batteryChange==0){
                    Log.e("无电有网","休眠"+"\t网络状态"+noNetChange+"\t电池状态"+batteryChange+"\t"+total+"\t"+level+"\t"+scale);
                }else{
                    Log.e("有电有网","休眠"+"\t网络状态"+noNetChange+"\t电池状态"+batteryChange+"\t"+total+"\t"+level+"\t"+scale);
                }
            }else {
                noNetChange=0;
                if (batteryChange==1){
                    Log.e("有电无网","重启"+"\t网络状态"+noNetChange+"\t电池状态"+batteryChange+"\t"+total+"\t"+level+"\t"+scale);
                    reStart();
                }else {
                    Log.e("无电无网","休眠"+"\t网络状态"+noNetChange+"\t电池状态"+batteryChange+"\t"+total+"\t"+level+"\t"+scale);
                }
            }
            Log.e("#######","\t网络状态"+noNetChange+"\t电池状态"+batteryChange);
        }
    }
    private void reStart(){
        long time= SystemClock.currentThreadTimeMillis();
        while (SystemClock.currentThreadTimeMillis()-time<=20000){
            Log.e("时间差",SystemClock.currentThreadTimeMillis()-time+"\t网络状态"+noNetChange+"\t电池状态"+batteryChange);
            if (SystemClock.currentThreadTimeMillis()-time==10000){
                Log.e("时间差为10秒",SystemClock.currentThreadTimeMillis()-time+"--10秒");
                Log.e("reStart","网络状态"+noNetChange+"电池状态"+batteryChange);
                try {
                    Log.e(TAG,"broadcast->shutdown");
                    java.lang.Process process=Runtime.getRuntime().exec(new String[]{"su","-c","reboot"});
                    process.wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
}
解决方案

100

用handler   发送延时消息 。
private Handler mHandler = new Handler() {

public void dispatchMessage(Message msg) {
if (1 == msg.what) {
//重启方法
}
};
};
断网后发送延时消息
removeMessages(1);//先取消上一次的消息(假如还没发出去),保证只发一个30的延时消息
mHandler.sendMessageDelayed(1, 30000);
30秒内联网了
removeMessages(1);//取消发送


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明广播与线程问题通过广播监测网络连接从而控制手机自动重启时,连接上网络后无法取消重启
喜欢 (0)
[1034331897@qq.com]
分享 (0)