我的应用程序与广播接收器和WiFi

时间:2014-03-24 13:50:37

标签: android broadcastreceiver android-wifi

我,这是我的Android应用程序,我试图与硬件通信,因为对我来说这很令人兴奋!

当我禁用wifi或我改变网络....我需要做吐司和振动。什么错了???

我使用galaxy s2 4.1.2测试我的应用程序,但我希望我的应用程序能够在安装了android 2.3.3的旧手机上运行。

的AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dado.wifibc"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.VIBRATE"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <receiver 
        android:name="dado.wifibc.BroadCastReceiver">
        <intent-filter>
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
            <action android:name="android.net.wifi.STATE_CHANGE"/>
        </intent-filter>
    </receiver>
</application>

</manifest>

BroadCastReceiver.java

package dado.wifibc;

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

public class BroadCastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Toast.makeText(context, "blablabla!!!.",Toast.LENGTH_LONG).show();

    // Vibrate the mobile phone
    Vibrator vibrator = (Vibrator)   context.getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(2000);
}

}

1 个答案:

答案 0 :(得分:0)

请从意图过滤器中删除操作并将操作设置为“android.net.conn.CONNECTIVITY_CHANGE”,如,

      <receiver 
    android:name="dado.wifibc.BroadCastReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>

    </intent-filter>

和onReceive(),

           final ConnectivityManager connMgr = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            final android.net.NetworkInfo wifi = connMgr
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                    if (!wifi.isAvailable())
             {

              Toast.makeText(context, "blablabla!!!.",Toast.LENGTH_LONG).show();

        // Vibrate the mobile phone
         Vibrator vibrator = (Vibrator)   context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(2000);
  }