我想在我的应用程序中检查互联网连接,但是此代码在android牛轧糖上不起作用以检查互联网连接
此代码适用于棉花糖和奇巧,但不适用于牛轧糖
请帮我

广播代码:

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    final ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo=connMgr.getActiveNetworkInfo();
    if(networkInfo!=null && networkInfo.isConnectedOrConnecting()){
        Toast.makeText(context, "connected", Toast.LENGTH_SHORT).show();
    }


}
}


清单文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="clicksite.org.testinternetconnection">

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_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=".NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>


</application>

</manifest>

最佳答案

我有相同的问题。我正在考虑创建一项在后台运行并耐心等待广播的服务。

我实际上使用Task Scheduler将其固定在我们的android evernote here job库中,然后

public static void scheduleAdvancedJob() {
    PersistableBundleCompat extras = new PersistableBundleCompat();
    extras.putString("key", "smj");

    int jobId = new JobRequest.Builder(MainConstant.TAG)
            .setExecutionWindow(3_000L, 30_000L)
            .setBackoffCriteria(5_000L, JobRequest.BackoffPolicy.EXPONENTIAL)
            .setRequiresCharging(false)
            .setRequiresDeviceIdle(false)
            .setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
            .setExtras(extras)
            .setRequirementsEnforced(true)
            .setUpdateCurrent(true)
            .build()
            .schedule();
}

关于android - 牛轧糖的互联网连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47858552/

10-12 02:53