2015-03-13 4 views
1

Я пытаюсь определить, подключен ли WiFi или нет, прослушивая «SUPPLICANT_CONNECTION_CHANGE_ACTION», как показано ниже в коде. Но проблема в том, что , когда я запускаю приложение, я не получаю никаких уведомлений от широкого получателя Cast, на который я зарегистрирован!BroadCast Receiver никогда не называется

Почему это происходит и как его решить?

код:

IntentFilter intentFilter2 = new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION); 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    ConnectivityModule(); 
} 

protected void ConnectivityModule() { 
    // TODO Auto-generated method stub 
    Log.d(TAG, "@interNetConnectivityModule: called"); 
    registerReceiver(SupplicantReceiver, intentFilter2); 
} 

BroadcastReceiver SupplicantReceiver = new BroadcastReceiver() { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 

     final String action = intent.getAction(); 

     if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) { 
      SupplicantState supplicantState = (SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE); 

      if (supplicantState == (SupplicantState.COMPLETED)) { 
       Log.d(TAG, "@SupplicantReceiver: connected"); 
      } 

      if (supplicantState == (SupplicantState.DISCONNECTED)) { 
       Log.d(TAG, "@SupplicantReceiver: not connected"); 
      } 
     } 
    } 
}; 
+1

все разрешения установлены в манифесте? – Opiatefuchs

+0

да все установленные разрешения, а во время выполнения я не получаю никаких ошибок в logcat – rmaik

+0

Также вы зарегистрировали свой приемник в своем манифесте? –

ответ

0

Вот пример:

Основная деятельность

import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.content.Intent; 
import android.view.View; 

public class MainActivity extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 
    // broadcast a custom intent. 
    public void broadcastIntent(View view) 
    { 
     Intent intent = new Intent(); 
     intent.setAction("com.tutorialspoint.CUSTOM_INTENT"); 
     sendBroadcast(intent); 
    } 
} 

Мои Broadcast Receiver:

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.widget.Toast; 

public class MyReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show(); 
    } 

} 

Это, как вы должны объявить вещательный приемник в манифесте:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.helloworld" 
    android:versionCode="1" 
    android:versionName="1.0" > 
    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="15" /> 
    <application 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/title_activity_main" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER"/> 
      </intent-filter> 
     </activity> 
     <receiver android:name="MyReceiver"> 
      <intent-filter> 
      <action android:name="com.tutorialspoint.CUSTOM_INTENT"> 
      </action> 
      </intent-filter> 
     </receiver> 
    </application> 
</manifest> 

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <Button android:id="@+id/btnStartService" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/broadcast_intent" 
    android:onClick="broadcastIntent"/> 

</LinearLayout> 
0

Ваш приемник выглядит правильно зарегистрирован (во время выполнения, а не на основе манифеста, но независимо от того, должно быть хорошо так или иначе).

Я предполагаю .. вы пробовали положить журналы в onReceive метод как

@Override 
public void onReceive(Context context, Intent intent) { 
    // TODO Auto-generated method stub 

    Log.d(TAG, "Reached this point, receiver is working"); 
    final String action = intent.getAction(); 

    if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) { 
     SupplicantState supplicantState = (SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE); 

     if (supplicantState == (SupplicantState.COMPLETED)) { 
      Log.d(TAG, "@SupplicantReceiver: connected"); 
     } 

     if (supplicantState == (SupplicantState.DISCONNECTED)) { 
      Log.d(TAG, "@SupplicantReceiver: not connected"); 
     } 

     Log.d(TAG, "Checking for an error in retrieving data!"); 
     boolean myTest = intent.getBooleanExtra(EXTRA_SUPPLICANT_CONNECTED, false); 

     if (myTest) Log.d(TAG, "This way it worked!"); 
      else Log.d(TAG, "This does not mean it didn't work at all! Might just be the correct value as a DISCONNECTED status"); 

    } else Log.d(TAG, "Bizzarre error, action received was different from the one receiver was registered to! [ " + action + " ] "); 

} 

Я предполагаю, что вы, возможно, пытается получить информацию в неправильном направлении, и с бревнами так строго определенные вами не может видеть, что происходит, но приемник отлично работает

+0

спасибо, я попробовал ваш ответ, но снова повторяю то же самое , когда я включаю и выключаю Wi-Fi, я не получаю уведомления – rmaik

+0

Я попытался создать новый Android-проект с указанным кодом плюс мои расширенные журналы. никаких разрешений, установленных в манифесте. результат заключается в том, что приемник работает, но журналы, которые вы изначально использовали (SupplicantState.COMPLETED и DISCONNECTED), никогда не запускаются, потому что requesticState всегда имеет значение null. , каждый из моих журналов запускается правильно – FrancescoC

Смежные вопросы