我有一個廣播接收器可以檢測應用程序是否連接到互聯網,併發送帶有額外字符串的意圖。但是,我得到一個空超:當從BroadCast發送意圖時沒有額外的空格
這是廣播接收器
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
context.sendBroadcast(new Intent().putExtra("cnx","yes"));
}
else{
context.sendBroadcast(new Intent().putExtra("cnx","no"));
}
}
}
,這我的活動代碼:
networkChangeReceiver=new NetworkChangeReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String val=intent.getStringExtra("cnx");
Snackbar snackbar = Snackbar
.make(layoutLauncher, "Pas de connexion Internet!"+val, Snackbar.LENGTH_LONG);
snackbar.show();
/* if (val.equals("internet")){
isNetworkAvailable(false);
}
else{
isNetworkAvailable(true);
}*/
}
};
,這是註冊碼
private void registerNetworkBroadcast() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(networkChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerReceiver(networkChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
這是清單的一部分
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tn.formation.mdsoft.bulletinimmobilier">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application.....
<activity android:name=".ui.activities.LauncherActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".services.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".services.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<receiver android:name=".tools.NetworkChangeReceiver" >
</receiver>
意圖是爲了LauncherActivity。
編輯
的情況是無論如何故障,所以我忽略了它的實現,但在這種情況下,更好的驗證密鑰。
你可以分享你的Androidmanifest.xml文件嗎 –
所以你傳遞的關鍵'cnx的數據和獲取'internet'。當然它將會是空的。 –
這就是我搞砸了幾個更正後,即使使用正確的密鑰它仍然爲空 – MeknessiHamida