作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我是 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/
我是一名优秀的程序员,十分优秀!