您好,我是android新手,几乎可以完成我的应用程序。但是,我现在陷入了困境。我想运行一项仅在连接或断开Internet时有效的服务。我为此使用了Brodcast接收器,并且还在应用程序的活动中注册了该Brodcast。但是当我尝试杀死应用程序,接收到呼叫但没有连接互联网时,它无法正常工作。

Brodcast接收器:

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

关于android - 仅在连接互联网时如何运行服务?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48073156/

10-12 00:18
查看更多