版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/chaoyu168/article/details/79131892
在开发中,遇到服务是24小时定时执行,需要在WiFi条件下上传,需要监听WiFi,在开定时器,持续刷新WiFi状态
WiFi监听:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class iswifi {
public static boolean isWiFiActive(Context inContext) {
Context context = inContext.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {
return true;
}
}
}
}
return false;
}
}
定时器:
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private Runnable runnable;
private Handler handler;
private Runnable runnable1;
private Handler handler1;
private int flag = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//外部定时器
handler1 = new Handler();
runnable1 = new Runnable() {
@Override
public void run() {
init();
handler1.postDelayed(this,1000*60*60);
}
};
handler1.postDelayed(runnable1,1000*5);
}
private void init() {
//内部检查WiFi定时器
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
if (iswifi.isWiFiActive(MyApplication.getContext())){
System.out.println("456");
handler.removeCallbacks(runnable);
}else {
System.out.println("789");
handler.postDelayed(this,1000*5);
}
}
};
handler.postDelayed(runnable,1000);
//利用while实现,不用定时器
// flag = 0;
// while (flag == 0 || flag == 2){
// if (iswifi.isWiFiActive(MyApplication.getContext())){
// System.out.println("456");
// flag = 1;
// }else {
// System.out.println("789");
// flag = 2;
// }
// }
}
}