This question already has an answer here:
How can I monitor the network connection status in Android?
(1 answer)
Closed 10 years ago.
I would like to constantly check whether the phone is connected to a specific wireless network. I thought of a service and the SSID of the network of course, but how?
You'll want
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
In your receiver tag.
Or if you want more control over it, before registering BroadcastReceiver set these up:
final IntentFilter filters = new IntentFilter();
filters.addAction("android.net.wifi.WIFI_STATE_CHANGED");
filters.addAction("android.net.wifi.STATE_CHANGE");
super.registerReceiver(yourReceiver, filters);
WIFI_STATE_CHANGED
Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown. One extra provides this state as an int. Another extra provides the previous state, if available.
STATE_CHANGE
Broadcast intent action indicating that the state of Wi-Fi connectivity has changed. One extra provides the new state in the form of a NetworkInfo object. If the new state is CONNECTED, additional extras may provide the BSSID and WifiInfo of the access point. as a String
Also, you'll need to specify the right permissions:
<user-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<user-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Whole Source Code: Download
AndroidManifest.xml
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.temp.MainActivity"
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="com.example.temp.MyWiFiStateListener">
<intent-filter >
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
</receiver>
</application>
MainActivity.java
package com.example.temp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Broadcast Receiver:
package com.example.temp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
public class MyWiFiStateListener extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
Log.d("TEMP", action);
if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(info.getType() == ConnectivityManager.TYPE_WIFI){
WifiManager myWifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = myWifiManager.getConnectionInfo();
Log.d("TEMP","BSSID :: " + wifiInfo.getBSSID() + "SSID :: " + wifiInfo.getSSID());
}
}
}
}
Related
I am making app which tracks user location continuously, so far i have been able to make a successful receiving of its ordinate on location change, but if he is restarting the phone than i am not able to start my service without user again opening the app.
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aa.gpsdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.aa.gpsdemo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" android:label="My Service">
<intent-filter>
<action android:name="com.aa.gpsdemo.StartMyServiceAtBootReciever" />
</intent-filter>
</service>
<receiver
android:name=".receiver.StartMyServiceAtBootReceiver"
android:enabled="true"
android:exported="true"
android:label="StartMyServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
StartMyServiceAtBootReciever.java
package com.aa.gpsdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartMyServiceAtBootReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceIntent = new Intent("com.aa.gpsdemo.BackgroundService");
context.startService(serviceIntent);
}
}
}
BackgroundService.java
package com.aa.gpsdemo;
import android.app.Service;
import android.content.Intent;
import android.content.Context;
import android.os.IBinder;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;
import android.location.Criteria;
public class BackgroundService extends Service {
private static NewLocationListener mylistner=null;
private final static String TAG = "MainActivity";
private Context context = null;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
mylistner = new NewLocationListener(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
criteria.setCostAllowed(true);
LocationManager locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
String bestProvider=locManager.getBestProvider(criteria, true);
locManager.requestLocationUpdates(bestProvider,1000, 5, mylistner);
}
}
where i am going wrong any help would be highly appreciated on restart of a phone i get demoapp has stopped i tried putting toast on reciever but that toast also are not coming at present
Make Sure u have the permission in AndroidManifest File :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Change this to :
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context,BackgroundService.class);
startService(serviceIntent);
}
RECEIVE_BOOT_COMPLETED: Broadcast Action: This is broadcast once, after the system has finished booting. It can be used to perform application-specific initialization, such as installing alarms. You must hold the RECEIVE_BOOT_COMPLETED permission in order to receive this broadcast.
Refrence
Stackoverflow Question
I am trying to generate some log and put up a toast on screen after power button click.
But it doesn't seem to work. Here's the code:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.pbtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACTION_SHUTDOWN" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.test.pbtest.MainActivity"
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="com.test.pbtest.MyReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
</receiver>
</application>
</manifest>
MyReceiver.java class:
package com.test.pbtest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.v("Hurray!", "Power button was clicked!");
Toast.makeText(arg0, "power button clicked",Toast.LENGTH_LONG).show();
}
}
MainActivity.java class:
package com.test.pbtest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
As per my knowledge, i need not register my receiver explicitly as i have used it in manifest file. Please guide me where i am going wrong.
you will need to add ACTION_SHUTDOWN permission in AndroidManifest.xml :
<uses-permission android:name="android.permission.ACTION_SHUTDOWN" />
for some reason you have to register your receiver on runtime.. you can register it via service
I want my app to check whether the device is connecting to a specific Wifi and auto connect to the Wifi whenever the app is navigated to. I know that I can do it in onRestart(). But it only handles one activity's state.
My question is if there any method to handle the state of the app instead of adding onRestart() on every activity to do what i want?
try the following code:
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
public class AutostartService extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("in broad....");
ConnectivityManager manager = (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
if(!is3g && !isWifi){
}else{
if ((intent.getAction() != null) && (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")))
{
System.out.println("in broadcast receiver.....");
Intent i = new Intent(context, Splash.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
}
dont forget to add this in your manifest file:
<receiver android:name=".AutostartService" android:enabled="true" android:exported="true">
- <intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
and the following permissions in manifest file:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
I am writing an Android application which can enable and disable the Network Data packet connection. I am also using one broadcast receiver to check the Network Data packet connection. I have registered broadcast receiver and provided required permission in Manifest file. But when I run this application it changes the connection state and after that it crashes. But when I don't include this broadcast receiver it works fine. I am not able to see any kind of log which can provide some clue.
Here is my code for broadcast receiver.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rakesh.simplewidget"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<!-- Permissions -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".SimpleWidgetExampleActivity"
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=".ExampleAppWidgetProvider"
android:label="Widget ErrorBuster" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget1_info" />
</receiver>
-->
<receiver android:name=".ConnectivityReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>
My Broadcast receiver class is as following.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class ConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(info.getType() == ConnectivityManager.TYPE_MOBILE){
if(info.isConnectedOrConnecting()){
Log.e("RK","Mobile data is connected");
}else{
Log.e("RK","Mobile data is disconnected");
}
}
}
}
my Main activity file.
package com.rakesh.simplewidget;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class SimpleWidgetExampleActivity extends Activity {
private Button btNetworkSetting;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btNetworkSetting = (Button)findViewById(R.id.btNetworkSetting);
if(checkConnectivityState(getApplicationContext())){
btNetworkSetting.setBackgroundColor(Color.GREEN);
}else{
btNetworkSetting.setBackgroundColor(Color.GRAY);
}
}
public void openNetworkSetting(View view){
Method dataConnSwitchmethod;
Class telephonyManagerClass;
Object ITelephonyStub;
Class ITelephonyClass;
Context context = view.getContext();
boolean enabled = !checkConnectivityState(context);
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try{
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
if(enabled){
Toast.makeText(view.getContext(), "Enabled Network Data", Toast.LENGTH_LONG).show();
view.setBackgroundColor(Color.GREEN);
}
else{
Toast.makeText(view.getContext(), "Disabled Network Data", Toast.LENGTH_LONG).show();
view.setBackgroundColor(Color.LTGRAY);
}
}catch(Exception e){
Log.e("Error", "some error");
Toast.makeText(view.getContext(), "It didn't work", Toast.LENGTH_LONG).show();
}
}
private boolean checkConnectivityState(Context context){
final TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
ConnectivityManager af ;
return telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED;
}
}
Log file:
java.lang.RuntimeException: Unable to instantiate receiver com.rakesh.simplewidget.ConnectivityReceiver: java.lang.ClassNotFoundException: com.rakesh.simplewidget.ConnectivityReceiver in loader dalvik.system.PathClassLoader[/data/app/com.rakesh.simplewidget-2.apk]
E/AndroidRuntime(26094): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1777)
E/AndroidRuntime(26094): at android.app.ActivityThread.access$2400(ActivityThread.java:117)
E/AndroidRuntime(26094): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
E/AndroidRuntime(26094): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(26094): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime(26094): at android.app.ActivityThread.main(ActivityThread.java:3691)
E/AndroidRuntime(26094): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(26094): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(26094): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
E/AndroidRuntime(26094): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
E/AndroidRuntime(26094): at dalvik.system.NativeStart.main(Native Method)
It seems Android is not able to recognize file Broadcast Receiver class. Any idea why I am getting this error?
PS: Some information about Android environment and platform.
- Android API 10.
- Running on Samsung Galaxy II which has android 2.3.6
Edit:
my broadcast receiver file ConnectivityReceiver.java was present in default package and it was not being recognized by Android. Android was looking for this file in current package i.e com.rakesh.simplewidget; I just moved connectivityReciever.java file to com.rakesh.simplewidget package and problem was solved.
My Broadcast receiver file ConnectivityReceiver.java was present in default package by mistake. And Android was not able to recognized this file because it was searching ConnectivityReceiver in the current package. i.e com.rakesh.simplewidget;
It was simple unnoticeable mistake which caused me half an hour to debug this.
Thank you guys for taking time reading my question and providing your comments.
Updated the main post.
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>
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);
}
}
}
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.
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>
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.
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>