android - 即使您的应用程序未运行,您如何检测 Nougat 上的网络连接丢失?

标签 android networking background-process connectivity android-jobscheduler

在 Nougat 以下的 API 上,您只需在订阅 CONNECTIVITY_CHANGES 的 list 中声明一个接收器。这使我能够监听网络连接的变化,无论连接是打开还是关闭,并且即使我的应用程序没有运行,我也可以执行任务。

在牛轧糖上,这似乎是不可能的。我知道如果有网络连接,牛轧糖上的 JobScheduler 可用于在后台执行某些任务,但似乎没有监听网络连接丢失的选项。

换句话说,我希望能够在我的手机失去所有连接(Wi-Fi、LTE 等)时听到声音,并在发生这种情况时在后台执行某些操作。这在牛轧糖上可能吗?

最佳答案

您可以使用 NetworkChangeReceiver

public class NetworkChangeReceiver extends BroadcastReceiver {

private static final String LOG_TAG = "NetworkChangeReceiver";
private boolean isConnected = false;
Context mContext;

@Override
public void onReceive(Context context, Intent intent) {
    Log.v(LOG_TAG, "Receieved notification about network status");
    isNetworkAvailable(context);
    mContext=context;

}

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    if (!isConnected) {
                        Log.v(LOG_TAG, "Now you are connected to Internet!");
                        Toast.makeText(context, R.string.internet_available, Toast.LENGTH_SHORT).show();

                        isConnected = true;


                    }
                    return true;
                }
            }
        }
    }
    Log.v(LOG_TAG, "You are not connected to Internet!");
    Toast.makeText(context, R.string.internet_not_available, Toast.LENGTH_SHORT).show();




    isConnected = false;
    return false;
}

关于android - 即使您的应用程序未运行,您如何检测 Nougat 上的网络连接丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40601561/

相关文章:

javascript - vue.js:定期重复后台查询的位置

java - 更新功能

android - addToBackStack 后的 popBackStack() 不起作用

java - 不同编码的 HTTP Post 请求正文(字符集)

swift - 使用 RxSwift 重播最后一个请求

ios - 如何在响应用户交互时运行 NSTimer 或重复的预定进程

android - Camera.translate 和 Matrix.preTranslate 或 Matrix.postTranslate 之间的区别?

c - 是否可以使用跟踪服务器来建立我自己的点对点网络?

c# - 无法从 WinRT 连接到远程服务器

ios - ionic 应用程序恢复和暂停