Wifi接收器未触发Android 4.x.x适用于2.2.1



我创建了一个wifi广播接收器来检查wifi状态的变化。

此应用程序在Android 2.2.1设备上

运行良好,但在4.x.x设备上无法接收广播,我已经在4.1.1和android 4.4.2设备上进行了测试,没有运气?我一定在这里错过了一些小东西。提前感谢!

<小时 />

安卓清单.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.wifi.test.testapp">
    <application
            android:allowBackup="true"
            android:label="@string/app_name"
            android:icon="@drawable/ic_launcher"
            android:theme="@style/AppTheme">
        <receiver android:name=".WifiReceiver" android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
                <action android:name="android.net.wifi.STATE_CHANGE"/>
            </intent-filter>
        </receiver>
    </application>
    <!-- wifi -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
</manifest>

<小时 />.无线接收器类

public class WifiReceiver extends BroadcastReceiver {
    private static final String TAG = "WifiReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "WifiReceiver");
        NetworkUtil.getConnectivityStatusString(context);
    }
}

<小时 />build.gradle

apply plugin: 'android'
android {
    compileSdkVersion 19
    buildToolsVersion '19.0.3'
    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 16
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}
dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.android.support:support-v4:+'
}

请使用这个

    <receiver
      android:name=".WifiReceiver"
      android:exported="false" >`enter code here`
    <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
    </receiver>

在 API 3.1 之前,我们可以有一个广播接收器,即使它所属的应用程序处于停止状态,它也可以被隐式意图调用。但这构成了安全威胁。因此,谷歌强制要求任何广播接收器接收意图,应该有一个活动,并且应用程序不应该处于停止状态

当应用程序启动时,它处于停止状态,因此它要求用户激活具有广播接收器的应用程序。如果用户强制停止应用程序,则广播接收器再次无法接收意图。因此,只有广播接收器并在 3.1 之前的版本上开发的 apk 将不再适用于更高版本。但是,可以使用FLAG_INCLUDE_STOPPED_PACKAGES来激活停止应用程序中的组件。这不需要创建另一个活动即可使用广播接收器。<小时 />因此,我只需要添加一个活动即可使广播接收器工作。

最新更新