如何 运行 仅在连接互联网时提供服务?

How to run a service only when internet is connected?

您好,我是 android 的新手,我几乎完成了我的应用程序。但我现在被这个问题困住了。我想要 运行 一项仅在互联网连接或断开连接时才有效的服务。为此,我使用了 Brodcast 接收器,还在应用程序的 activity 中注册了该广播。但是当我尝试应用程序被杀死时它不起作用,接收者被调用但它显示没有连接互联网。

广播接收器:

public class ImageDownloadReceiver extends BroadcastReceiver {

public static boolean isConnected(Context context){
    ConnectivityManager
            cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();
}


@Override
public void onReceive(Context context, Intent intent) {
    Log.i("Info", "onReceive in ImageDownloadReceiver get called ... ");

    if(isConnected(context)){
        Log.i("Info", "Internet connected !!!...Service starts ... ");
        Intent myService = new Intent(context, ImagesDownloadService.class);
        context.startService(myService);
    }else{
        Log.i("Info", "Internet disconnected !!!...Service stops ... ");
        Intent myService = new Intent(context, ImagesDownloadService.class);
        context.stopService(myService);
    }
}
}

清单:

    <receiver
        android:name=".receiver.ImageDownloadReceiver"
        android:enabled="true"
        android:exported="true"
        android:label="RestartServiceWhenStopped">
        <intent-filter>
            <action android:name="com.example.app.RestartImageDownloadService"/>
            <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>

我建议您更喜欢使用 JobScheduler 来处理您的情况。 JobScheduler 为您提供服务和启动服务的很多条件。当然,这些条件包括互联网连接。 给你:https://developer.android.com/reference/android/app/job/JobScheduler.html