gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:11:20 24 4
gpt4 key购买 nike

您好,我是 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);
}
}
}

list :

    <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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com