0
我開發了一款android應用程序,該應用程序會在WiFi或3G網絡發生變化時更新服務器數據庫。我實施了一個BroadcastReceiver
,它收聽WiFi change or a 3G connectivity change
。當WIFI或3G網絡發生變化時,BroadcastReceiver
問題是此代碼在Android版本4.x.x中不起作用。即使網絡已啓用或WiFi已啓用,「互聯網已連接」烤麪包也不會出現。
它在android 2.3.x和3.x.x中完美工作,「互聯網已連接」toast出現,並且數據庫也被更新。
這是MainActivity.java
文件:
public class MainActivity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Integer flag;
flag = 0;
ConnectivityManager check = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info = check.getAllNetworkInfo();
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
Toast.makeText(context, "Internet is connected",
Toast.LENGTH_SHORT).show();
flag = 1;
}
}
if (flag != 0) {
StringBuffer sb = new StringBuffer();
TelephonyManager TelephonyMgr = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
m_deviceId = TelephonyMgr.getDeviceId();
m_androidId = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
String bm = android.os.Build.MANUFACTURER + ","
+ android.os.Build.MODEL;
System.out.println("Device Name: " + bm + "\n");
try {
URL url = new URL(
"http://saslabtech.com/atsdemo/import_vr.php?d="
+ URLEncoder.encode(m_deviceId, "UTF-8") + "&a="
+ URLEncoder.encode(m_androidId, "UTF-8")
+ "&model=" + URLEncoder.encode(bm, "UTF-8")
+ "&ip="
+ URLEncoder.encode(getLocalIpv4Address(), "UTF-8"));
System.out.println(url);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(context, "Updated", Toast.LENGTH_SHORT).show();
}
}
}
這是AndroidManifest.xml
文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.read"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".MainActivity" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
</application>
</manifest>
我想不通我要去哪裏錯了。
謝謝!
請指定*不工作*表示 – TheLostMind 2015-02-09 12:42:50
「網絡連接」網絡啓用後,即使敬酒不出現或無線網絡已啓用。 – 2015-02-09 12:47:54
請不要創建一個名爲'MainActivity'的類,除非它實際上擴展了'Activity'類。另外,除非您有實際的MAIN/LAUNCHER'Activity',否則用戶無法啓動您的應用程序,並且您的'AndroidManifest.xml'中註冊的任何'BroadcastReceiver'永遠不會被激活。 – Squonk 2015-02-09 12:53:36