BroadcastReceiver在后台检测互联网 [英] BroadcastReceiver to detect internet on background

查看:86
本文介绍了BroadcastReceiver在后台检测互联网的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个BroadcastReceiver,可以检测互联网可用性变化。该代码正在运行,当互联网可用时,应用说在线,当我打开WIFI或4G时,它说离线。我添加了以下代码行来防止在按下后退按钮时关闭应用程序:

I have a BroadcastReceiver that detects internet availablity changes. The code is working the app says online when internet is available and when I turn of WIFI or 4G it says offline. I have added this line of code to prevent the application from closing when back button is pressed:

@Override
    public void onBackPressed() {
        this.moveTaskToBack(true);
    }

当我按下后退按钮时,应用程序被置于后台,并且BroadcastReceiver表示始终即使有互联网也可以离线。将应用置于后台时为什么不起作用?

When I press back button the application is put on background and the BroadcastReceiver says always offline even if internet is available. Why is it not working when app is put in background?

谢谢。

代码如下:

public class MainActivity extends AppCompatActivity {
    private NetworkReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetworkReceiver();
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    public void onBackPressed() {
        this.moveTaskToBack(true);
    }

}


public class NetworkReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if(isConnected(context)) {
            Toast.makeText(context, "Online", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, "Offline", Toast.LENGTH_LONG).show();
        }
    }

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

}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.e.myapplication">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


推荐答案

您有一个动态注册的 BroadcastReceiver ,当您将应用程序移至后台时,此接收器可能会被Android系统回收,因为此接收器与您活动的生命周期相关,并且该活动很可能会被Android回收因为该活动不应运行任何后台任务。我想这就是为什么即使有时您仍然可以使用此代码进行广播的原因,您在内部使用的东西仍返回错误的结果,因为您使用的某些组件已经被android回收,从而导致无效的结果。

You have a dynamically registered BroadcastReceiver, when you move your app to background, this receiver is likely to be recycled by the Android system since this receiver is bound to the life cycle of your activity and the activity could very likely be recycled by Android since the activity is not supposed to run any background tasks. I suppose that's why even though sometimes you can still get broadcasts with this code, the stuff you are using inside returns false results because some of the components you are using are recycled by android already which results in the invalid result.

如果您想让广播接收器在后台运行,请在 AndroidManifest 中注册广播接收器,并使用相应的意图过滤器和您对接收器服务的实现,一旦接收到广播,该服务就会被触发。

If you want to have a broadcast receiver that works in the background, register the broadcast receiver in the AndroidManifest with the corresponding intent filters and your implementation of a receiver service that will be fired once the broadcast is received.

这篇关于BroadcastReceiver在后台检测互联网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆