我的目标是在更改 wi-fi 状态时打印日志。
我使用下面的代码。
MainActivity.java(主活动)
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this,WiFiService.class));
}
@Override
protected void onStart()
{
super.onStart();
Log.d("Start Service", "Start Service");;
startService(new Intent(this,WiFiService.class));
}
}
WiFiService.java(服务)
public class WiFiService extends Service
{
WiFiBroadCasetReceiver brod;
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
brod=new WiFiBroadCasetReceiver();
this.registerReceiver(brod, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
}
@Override
public void onDestroy()
{
super.onDestroy();
}
}
WiFiBroadCasetReceiver.java (BroadcastReceiver)
public class WiFiBroadCasetReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context arg0, Intent arg1)
{
Log.d("on receiver", "receiver");
}
}
AndroidManifest.xml
<application>
........
........
<receiver android:name=".WiFiBroadCasetReceiver" >
<intent-filter>
<action android:name="android.net.wifi.supplicant.STATE_CHANGE" />
</intent-filter>
</receiver>
</application>
问题 :
以上代码在 android 4.0 及更低版本中运行良好。当我改变 wi-fi 的状态时,广播接收器是随机调用的。所以,日志是随机打印的。我只需要一次。它工作正常所有 android 版本仍然是 android 4.1.0。或更高版本(果冻豆)。我使用 android.net.wifi.WIFI_STATE_CHANGED。但仍然发生同样的错误。