我想在用户每次连接到互联网时检查特定更新。我尝试了以下代码:
unfortunately app is getting stopped while checking for network
Broadcast receiver for checking internet connection in android app
的Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<receiver android:name=".UpdateReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
爪哇
public class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
if (isConnected)
Log.i("NET", "connecte" +isConnected);
else Log.i("NET", "not connecte" +isConnected);
}
}
我的问题是这些代码只接收一次,如果用户断开wifi并重新连接BroadcastReceiver无法通知。感谢任何帮助。
答案 0 :(得分:0)
在我的应用中实施支票后,查看是否有任何互联网连接。你可以看看这个 -
[SqlExceptionHelper] - ERROR: column "league_id" does not exist
您可以在OnCreate方法中初始化此类的对象。
最后在上传文件之前调用此类的方法。
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context cont){
this.context = cont;
}
public boolean isConnectingToInternet(){
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].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
EDITED ::
Boolean isInternetConnected = cd.isConnectingToInternet();
if (isInternetConnected)
{
//perform your job here.
}
希望这有帮助。