Wifi scan results broadcast receiver not working

心已入冬 提交于 2019-11-27 06:54:52

问题


I have written a simple broadcast receiver to show a toast message when wifi scan is completed. Nothing is showing. Here is my code:

package com.wifi;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.widget.Toast;

public class wifiReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"Scan completed", Toast.LENGTH_LONG).show();

    }

}

Here is the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.wifi"
      android:versionCode="1"
      android:versionName="1.0">


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".wifi" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    <receiver android:name=".wifiReceiver">
        <intent-filter>
            <action android:name="android.net.wifi.SCAN_RESULTS"></action>
        </intent-filter>
    </receiver>
    </application>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
</manifest>

回答1:


well, it's not that easy ;-)
there are couple of things missing... here is an example of a wifi scan - the original source code is located here http://www.androidsnippets.com/scan-for-wireless-networks

package com.android.wifitester;

import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class WifiTester extends Activity {
TextView mainText;
WifiManager mainWifi;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   mainText = (TextView) findViewById(R.id.mainText);
   mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
   receiverWifi = new WifiReceiver();
   registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
   mainWifi.startScan();
   mainText.setText("\\nStarting Scan...\\n");
}

public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 0, 0, "Refresh");
    return super.onCreateOptionsMenu(menu);
}

public boolean onMenuItemSelected(int featureId, MenuItem item) {
    mainWifi.startScan();
    mainText.setText("Starting Scan");
    return super.onMenuItemSelected(featureId, item);
}

protected void onPause() {
    unregisterReceiver(receiverWifi);
    super.onPause();
}

protected void onResume() {
    registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    super.onResume();
}

class WifiReceiver extends BroadcastReceiver {
    public void onReceive(Context c, Intent intent) {
        sb = new StringBuilder();
        wifiList = mainWifi.getScanResults();
        for(int i = 0; i < wifiList.size(); i++){
            sb.append(new Integer(i+1).toString() + ".");
            sb.append((wifiList.get(i)).toString());
            sb.append("\\n");
        }
        mainText.setText(sb);
    }
}
}



回答2:


I spent some time on this, and depending on what version of Android you are running this might help. For Android M, it appears that you have to enable location services, so try to add this to your code if you fall under this criteria.

private static final int PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION = 1001;

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION); 
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                       int[] grantResults) {
    if (requestCode == PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // TODO: What you want to do when it works or maybe .PERMISSION_DENIED if it works better
    }
}

Don't forget to add the following to your manifest:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Hopefully this helps.




回答3:


I did what max and PVS did but also removed the uses-permissions and still go the scan action.

Removed from manifest

Looking at the docs if you have no uses-permissions then your receiver is unrestricted as to whom can send but seems if you us uses permissions then the broadcast must have similar permissions.

I tested this with a lot of actions (below) in a receiver and get them. But once I put in uses-permissions of any kind I get no broadcasts,weird.

   <receiver android:name=".myReceiver" android:enabled="true">
        <intent-filter android:priority="99999999999">
            <action android:name="android.intent.action.FOUND" />
            <action android:name="android.location.PROVIDERS_CHANGED" />            
            <action android:name="android.hardware.action.NEW_PICTURE" />
            <action android:name="android.hardware.action.NEW_VIDEO" />
            <action android:name="android.net.wifi.STATE_CHANGE" />
            <action android:name="android.net.wifi.NETWORK_IDS_CHANGED" />
            <action android:name="android.net.wifi.SCAN_RESULTS" />
            <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
            <action android:name="android.net.wifi.supplicant.STATE_CHANGE" />
            <action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
            <category android:name="android.intent.category.DEFAULT" />         
        </intent-filter>            
    </receiver>   



回答4:


I got the above code working with the following in my manifest:

<receiver android:name="com.mumfordmedia.trackify.WifiReceiver" android:enabled="true">
<intent-filter>
    <action android:name="android.net.wifi.SCAN_RESULTS"></action>
</intent-filter>

Notice both the android:enabled="true" attribute in the receiver element, and the full path to the class that should be executed when the message is received as opposed to ".classname".

All the best and thanks for a starting point, Max.




回答5:


I started with Max's answer above, and when that worked, I proceeded to remove android:enabled="true" and then changed the android:name=".MyReceiver" (not the full path). It continued to work (2.2, API 8)! By "work" I mean MyReceiver received broadcasts when I turned WiFi on and off (I didn't poke into the extras etc). I also have ACCESS_WIFI_STATE and CHANGE_WIFI_STATE permissions.

<receiver android:name=".MyReceiver">
<intent-filter>
<!--  
<action android:name="android.net.wifi.STATE_CHANGED"/>
-->
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.SCAN_RESULTS"/>
</intent-filter>


来源:https://stackoverflow.com/questions/7050101/wifi-scan-results-broadcast-receiver-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!