BroadcastReceiver
没有在应用程序首次启动时工作的课程。我想在应用启动时同时检查互联网连接。请帮忙解决这个问题。
NetworkchangeListener.Java
public class NetworkChangeListener extends BroadcastReceiver {
public static boolean isNetworkConnected= false ;
@Override
public void onReceive(Context context, Intent intent) {
isNetworkConnected = isNetworkAvailable(context);
if(isNetworkConnected){
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "Not Connected", Toast.LENGTH_SHORT).show();
}
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}
以下是我的Manifest.xml文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dcastalia.clienttest">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".NetworkChangeListener">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
</application>
</manifest>
当我改变网络状态时,它工作正常但是对于第一个运行时它不起作用。
答案 0 :(得分:0)
广播接收器仅在CONNECTIVITY_CHANGE上执行,如在intent-filters中添加。要在应用启动时检查互联网连接,您可以参考以下链接How to check if internet is available or not in app startup in android?