Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wifi scan results broadcast receiver not working

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>
like image 915
Nikud Avatar asked Aug 13 '11 11:08

Nikud


People also ask

How do I know if my broadcast receiver is running?

A simple solution to this problem is to call the registerReceiver() in your Custom Application Class. This will ensure that your Broadcast receiver will be called only one in your entire Application lifecycle. Show activity on this post.

What is broadcast Receivers?

A broadcast receiver is an Android component that allows an application to respond to messages (an Android Intent ) that are broadcast by the Android operating system or by an application.

What is the time limit of broadcast Receiver in Android?

As a general rule, broadcast receivers are allowed to run for up to 10 seconds before they system will consider them non-responsive and ANR the app.


3 Answers

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);
    }
}
}
like image 75
DonGru Avatar answered Oct 15 '22 21:10

DonGru


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.

like image 27
af001 Avatar answered Oct 15 '22 20:10

af001


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>   
like image 20
captfrank Avatar answered Oct 15 '22 22:10

captfrank