package com.comit.broadcast;
import com.comit.util.AppHpler;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
/**
* @ClassName: NetworkConnectReceiver
* @Description:网络监控广播
* @author: RockeyCai
* @date: 2015-11-05 上午14:14:59
*
*/
public class NetworkConnectReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AppHpler.setAutoUploadImgTask(context, true);
//不自动上传
if (!AppHpler.getAutoUploadImgTask(context)) {
return;
}
// 这个监听网络连接的设置,包括wifi和移动数据 的打开和关闭
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null) {
// 判断是wifi连接
if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d(NetworkConnectReceiver.class.getCanonicalName(), "wifi连接:" + activeNetInfo.getState());
// 连接成功
if (NetworkInfo.State.CONNECTED == activeNetInfo.getState()) {
//启动开始上传图片服务
uploadService(context, intent, UploadService.UPLOAD_SERVICE_DO_UPLOAD_TRUE);
return;
}
// else if (activeNetInfo.getType() == 1) {
// if (NetworkInfo.State.DISCONNECTING == activeNetInfo.getState()) {
// // 未连接成功
// uploadService(context, intent, true);
// }
// }
}
}
// 网络无效 停止上传服务
uploadService(context, intent, UploadService.UPLOAD_SERVICE_DO_UPLOAD_FALSE);
}
}
/**
* 上传服务
* @param mContext
* @param intent
* @param isUpload
*/
private void uploadService(Context mContext, Intent intent, boolean doUpload) {
Intent serviceIntent = new Intent(mContext, UploadService.class);
serviceIntent.putExtra(UploadService.UPLOAD_SERVICE_DO_UPLOAD_FLAG, doUpload);
mContext.startService(serviceIntent);
}
/**
* 是否为wifi连接
*
* @param mContext
* @return
*/
public static boolean isWifi(Context mContext) {
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return false;
}
}
<!-- 网络广播监听 start -->
<receiver android:name="com.comit.broadcast.NetworkConnectReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
<service
android:name="com.comit.broadcast.UploadService"
android:enabled="true" >
<intent-filter>
<action android:name="com.comit.broadcast.UploadService" />
</intent-filter>
</service>
<!-- 网络广播监听 end -->
Android 监听wifi广播的两种方式
点赞
收藏