2014-03-07 58 views
4

我試圖將一些連接狀態感知添加到我的應用程序。 在這裏使用示例和谷歌的文檔iv'e拿出一個接收器,當連接狀態改變時正確顯示一個警報,但是當創建活動時也會不必要地顯示它。連接更改接收器在Android中獲取虛假意圖

的ConnectStatusReceiver:

package com.zivtaller.placefinder.receivers; 

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.util.Log; 
import android.widget.Toast; 

    public class ConnectStatusReceiver extends BroadcastReceiver { 

private String TAG = "netReceiver"; 

public ConnectStatusReceiver() { 
    super(); 
} 

@Override 
public void onReceive(Context context, Intent arg1) { 
    ConnectivityManager cm = (ConnectivityManager) context 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 
    boolean isConnected = activeNetwork != null 
      && activeNetwork.isConnectedOrConnecting(); 
    if (isConnected) { 
     Log.d(TAG, "Data connected"); 
     Toast.makeText(context, "Data connected", Toast.LENGTH_SHORT) 
       .show(); 
    } else { 
     Log.d(TAG, "Data not connected"); 
     Toast.makeText(context, "Data not connected", Toast.LENGTH_SHORT) 
       .show(); 
    } 

} 

}

其初始化和註冊在活動的的onResume():

 netReceiver = new ConnectStatusReceiver(); 
    IntentFilter netFilter = new IntentFilter(); 
    netFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); 
    registerReceiver(netReceiver, netFilter); 

回答

5

該系統可能產生廣播android.net.conn.CONNECTIVITY_CHANGE意圖。粘性廣播在發送後會留在附近。每當您註冊BroadcastReceiver以監聽粘性廣播時,最近廣播的意圖將在調用registerReceiver()時立即傳遞給接收方。

一個簡單的方法來測試android.net.conn.CONNECTIVITY_CHANGE廣播是否是粘性將檢查onResume()

netReceiver = new ConnectStatusReceiver(); 
IntentFilter netFilter = new IntentFilter(); 
netFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); 
Intent intent = registerReceiver(netReceiver, netFilter); 
if (intent != null) { 
    // broadcast is sticky 
} 

registerReceiver()調用的返回值,如果你能夠確定的是,廣播確實是粘性的,那麼你正在經歷的是意向行爲。

請參閱what is the difference between sendStickyBroadcast and sendBroadcast in Android

+0

粘性打電話isInitialStickyBroadcast()似乎已經問題。 通過保存每次更改的狀態並使用保存的狀態在onResume中啓動和註冊偵聽器時得到解決。 – Kepedizer

2

請做,

unregisterReceiver(netReceiver); 

在您onPause()方法。

+0

我忘了提及我做到了 – Kepedizer