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

时间:2018-01-03 07:43:43

标签: android broadcastreceiver android-broadcastreceiver

您好我是Android的新手,我几乎完成了我的应用程序。但我现在坚持这个问题。我想运行一项仅在互联网连接或断开连接时才能运行的服务。我使用了Brodcast接收器,并在应用程序的活动中注册了brodcast。但是,当我尝试app被杀时它不起作用,接收器被调用,但它显示没有连接互联网。

Brodcast Receiver:

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>

1 个答案:

答案 0 :(得分:0)

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