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