BroadcastReceiver 总是与网络断开连接
Posted
技术标签:
【中文标题】BroadcastReceiver 总是与网络断开连接【英文标题】:BroadcastReceiver always get disconnected from network 【发布时间】:2016-09-07 08:21:21 【问题描述】:
我关注了android Developers tutorial
Managing Network Usage。
似乎BroadcastReceiver
总是与网络断开连接。
我尝试通过AVD
和通过ADB
连接的电话运行我的应用程序,但两者都不起作用。
我也下载了示例,只是复制粘贴进行检查,但似乎有一个错误。
我留下了代码,但在网站上是一样的。
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.webkit.WebView;
import android.widget.Toast;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
public class NetworkActivity extends Activity
public static final String WIFI = "Wi-Fi";
public static final String ANY = "Any";
private static final String FEED_URL = "http://formulapassion.it/feed";
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
public static boolean refreshDisplay = true;
public static String sPref = null;
private NetworkReceiver receiver = new NetworkReceiver();
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
// Filter added dinamically
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkReceiver();
this.registerReceiver(receiver, filter);
@Override
public void onStart()
super.onStart();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sPref = sharedPrefs.getString("listPref", "Wi-Fi");
updateConnectedFlags();
if (refreshDisplay)
loadPage();
@Override
public void onDestroy()
super.onDestroy();
if (receiver != null)
this.unregisterReceiver(receiver);
private void updateConnectedFlags()
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected())
wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
else
wifiConnected = false;
mobileConnected = false;
private void loadPage()
if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
|| ((sPref.equals(WIFI)) && (wifiConnected)))
new DownloadXmlTask().execute(FEED_URL);
else
showErrorPage();
private void showErrorPage()
setContentView(R.layout.news_feed_webview);
// The specified network connection is not available. Displays error message.
WebView myWebView = (WebView) findViewById(R.id.main_webview);
myWebView.loadData("Errore! Nessuna connessione",
"text/html", null);
private class DownloadXmlTask extends AsyncTask<String, Void, String>
/* */
private String loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException
/* */
public class NetworkReceiver extends BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent)
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (WIFI.equals(sPref) && networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
refreshDisplay = true;
Toast.makeText(context, "Connesso", Toast.LENGTH_SHORT).show();
else if (ANY.equals(sPref) && networkInfo != null)
refreshDisplay = true;
else
refreshDisplay = false;
Toast.makeText(context, "Disconnesso", Toast.LENGTH_SHORT).show();
还有我的Manifest
:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-sdk xmlns:tools="http://schemas.android.com/tools"
tools:overrideLibrary="android.support.v14.preference,android.support.v7.appcompat,android.support.v7.preference,android.support.graphics.drawable,android.support.compat,android.support.v4,android.support.coreutils,android.support.mediacompat,android.support.coreui,android.support.fragment,android.support.v7.recyclerview" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.MyCustomTheme.Light" >
<!-- android:theme="@style/Theme.AppCompat.Light"> -->
<activity
android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".FirstTimeActivity"
android:theme="@style/Theme.AppCompat.NoActionBar" />
<receiver android:name=".NetworkActivity$NetworkReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<activity
android:name=".SettingsActivity"
android:parentActivityName=".MainActivity" >
<action android:name="android.intent.action.MANAGE_NETWORK_USAGE" />
<category android:name="android.intent.category.DEFAULT" />
</activity>
<activity android:name=".NetworkActivity">
</activity>
</application>
</manifest>
【问题讨论】:
【参考方案1】:如果您连接到 WiFi,则需要添加 WiFi 状态更改侦听器操作,如下所示:
<receiver android:name=".NetworkActivity$NetworkReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
【讨论】:
对不起,还是一样,总是断线。以上是关于BroadcastReceiver 总是与网络断开连接的主要内容,如果未能解决你的问题,请参考以下文章