Wifi 扫描结果广播接收器不工作

发布于 2024-11-29 04:25:00 字数 1654 浏览 0 评论 0原文

我编写了一个简单的广播接收器,用于在 wifi 扫描完成时显示一条 toast 消息。什么也没有显示。这是我的代码:

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();

    }

}

这是清单文件:

<?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>

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

眼泪也成诗 2024-12-06 04:25:00

好吧,这并不容易;-)
有几件事失踪了......
这是 wifi 扫描的示例 - 原始源代码位于此处 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);
    }
}
}

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);
    }
}
}
も星光 2024-12-06 04:25:00

我在这方面花了一些时间,根据您运行的 Android 版本,这可能会有所帮助。对于 Android M,您似乎必须启用位置服务,因此如果您符合此条件,请尝试将其添加到您的代码中。

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
    }
}

不要忘记将以下内容添加到您的清单中:

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

希望这会有所帮助。

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.

念﹏祤嫣 2024-12-06 04:25:00

我做了 max 和 PVS 所做的事情,但也删除了使用权限,但仍然执行扫描操作。

从清单中删除

查看文档,如果您没有使用权限,那么您的接收者对于谁可以发送没有限制,但似乎如果您使用权限,那么广播必须具有类似的权限。

我在接收器中用很多动作(如下)对此进行了测试并得到它们。但是,一旦我输入任何类型的使用权限,我就不会收到广播,很奇怪。

   <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>   

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>   
递刀给你 2024-12-06 04:25:00

我将上面的代码与我的清单中的以下内容一起使用:

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

请注意接收者元素中的 android:enabled="true" 属性,以及接收消息时应执行的类的完整路径,而不是“.classname”。

祝一切顺利,感谢您的起点,
最大限度。

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.

笨死的猪 2024-12-06 04:25:00

我从上面 Max 的答案开始,当它起作用时,我继续删除 android:enabled="true" ,然后更改 android:name=".MyReceiver" (不是完整路径)。它继续工作(2.2,API 8)!我所说的“工作”是指当我打开和关闭 WiFi 时,MyReceiver 会收到广播(我没有深入了解额外内容等)。我还有 ACCESS_WIFI_STATE 和 CHANGE_WIFI_STATE 权限。

<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>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文