Android checking Wifi on every onRestart - android

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

Related

Android BroadcastReciever BOOT_COMPLETED SecurityException

I search on internet 2 days but find nothing this is my
adb command
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
and``
this is my error code
Broadcasting: Intent { act=android.intent.action.BOOT_COMPLETED flg=0x400000 }
Security exception: Permission Denial: not allowed to send broadcast android.intent.action.BOOT_COMPLETED from pid=20913, uid=2000
java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.BOOT_COMPLETED from pid=20913, uid=2000
at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:20474)
at com.android.server.am.HwActivityManagerService.broadcastIntentLocked(HwActivityManagerService.java:4226)
at com.android.server.am.ActivityManagerService.broadcastIntent(ActivityManagerService.java:21189)
at com.android.server.am.ActivityManagerShellCommand.runSendBroadcast(ActivityManagerShellCommand.java:614)
at com.android.server.am.ActivityManagerShellCommand.onCommand(ActivityManagerShellCommand.java:154)
at android.os.ShellCommand.exec(ShellCommand.java:96)
at com.android.server.am.ActivityManagerService.onShellCommand(ActivityManagerService.java:16149)
at android.os.Binder.shellCommand(Binder.java:574)
at android.os.Binder.onTransact(Binder.java:474)
at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:4285)
at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3286)
at com.android.server.am.HwActivityManagerService.onTransact(HwActivityManagerService.java:837)
at android.os.Binder.execTransact(Binder.java:675)
AND
THİS İS MY MANİFEST FİLE
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mir.kitapkurdu"
>
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="com.huawei.permission.external_app_settings.USE_COMPONENT"/>`
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<permission android:name="android.permission.NET_ADMIN"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="signature">
</permission>
<application
android:installLocation="internalOnly"
android:name=".App"
android:persistent="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true">
<activity android:name=".Gonderici" />
<activity android:name=".Register" />
<activity android:name=".BookComplate" />
<activity android:name=".SpeechGame" />
<activity android:name=".BooksActvty" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Categories" />
<activity android:name=".PageComplete" />
<activity android:name=".Membership" />
<receiver
android:name=".SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.REBOOT" />
<action android:name="android.permission.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED"/>
<action android:name="android.intent.action.ACTION_USER_PRESENT" />
<action android:name="com.mir.kitapkurdu.AN_INTENT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
<service android:name=".services.BootUpService"
android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
</manifest>
Mainactvity.class
package com.mir.kitapkurdu;
import android.Manifest;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.speech.SpeechRecognizer;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import com.mir.kitapkurdu.objects.User;
import com.mir.kitapkurdu.services.BootUpService;
import com.mir.kitapkurdu.services.Database;
import com.mir.kitapkurdu.services.NotificaionService;
public class MainActivity extends AppCompatActivity {
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private String space = " ";
private Button ileri;
private TextView ekranayazdir;
private TextView startVoiceInput;
private Database db;
public BroadcastReceiver br = new SensorRestarterBroadcastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db= new Database(MainActivity.this);
User user=new User();
user = db.getLastAddedUser();
if (user.user_name==null)
{
serviceControl();
/* BootUpService mBootUpService = new BootUpService();
Intent mServiceIntent = new Intent(getApplicationContext(), mBootUpService.getClass());
startService(mServiceIntent);*/
broadcastIntent();
Intent intent = new Intent(this, Membership.class);
// intent.putExtra("category_id", 59);
startActivity(intent);
finish();
}else{
serviceControl();
/* BootUpService mBootUpService = new BootUpService();
Intent mServiceIntent = new Intent(getApplicationContext(), mBootUpService.getClass());
startService(mServiceIntent);*/
broadcastIntent();
Intent intent = new Intent(this, Gonderici.class);
intent.putExtra("user_id", user.user_id);
startActivity(intent);
finish();
}
}
private void serviceControl(){
NotificaionService mSensorService = new NotificaionService(getApplicationContext());
Intent mServiceIntent = new Intent(getApplicationContext(), mSensorService.getClass());
if (!isMyServiceRunning(mSensorService.getClass())) {
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("isMyServiceRunning?", true+"");
return true;
}
}
Log.i ("isMyServiceRunning?", false+"");
return false;
}
#Override
protected void onResume() {
super.onResume();
}
public void broadcastIntent() {
ComponentName receiver = new ComponentName(getPackageName(), "com.mir.kitapkurdu.SensorRestarterBroadcastReceiver");
PackageManager pm = MainActivity.this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent = new Intent();
intent.setComponent(receiver);
sendBroadcast(intent);
}
#Override
protected void onStop() {
super.onStop();
}
}
please help me I try everything on internet but There are no results I think this problem about permission what can I do in manifest file help me I want it this broadcast recieve to work at startup :(
The docs say:
This is a protected intent that can only be sent by the system.
https://developer.android.com/reference/android/content/Intent#ACTION_BOOT_COMPLETED
Which means that you cant send this intent.
You currently have <action android:name="android.permission.BOOT_COMPLETED" /> set as an intent filter, which won't work.
Add <action android:name="android.intent.action.BOOT_COMPLETED" /> to the intent filter of your SensorRestarterBroadcastReceiver, then reboot your device.

Autostart on BOOT_COMPLETED for flutter application based on Android example not working

There are quite a few examples of using BOOT_COMPLETED to start an application when the device boots..
I have attempted to use these example against my Flutter application. Having it start the App. This is for a simply signage app that shows images. Basically similar to a picture frame.
In the example code below, the application is compiling, however, when I reboot a simulator, for example, the code does not appear to have any effect.
My guess is that I am not calling the right code to actually start the application.. I am not a Android developer, so am having issues figuring what is exactly going on.
Manifest follows..
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="au.net.digitall.cmplayer">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name="io.flutter.app.FlutterApplication"
android:label="cm_player"
android:icon="#mipmap/ic_launcher"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/cmTheme2"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver
android:enabled="true"
android:name=".StartCmPlayerServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
Then the StartCmPlayerServiceAtBootReceiver class to start the APP..
package au.net.digitall.cmplayer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class StartCmPlayerServiceAtBootReceiver extends BroadcastReceiver {
private static final String TAG = StartCmPlayerServiceAtBootReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "BOOT detected");
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, MainActivity.class);
context.startService(serviceIntent);
}
}
}
This all compiles and runs, but nothing happens on reboot.
Appreciate the help..
Thank to very much to Mike M.
His suggestion and pointing at the other android based discussion gave me enough info to archive autostart on boot. The code change to the above example follows..
In the StartCmPlayerServiceAtBootReceiver class,
Change to
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent mIntent = new Intent(context, MainActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);
}
}
Thanks again, and I hope other flutter devs find this useful.
Create receiver class on kotlin path project_name/android/app/src/main/kotlin/com/example/app/
package com.example.app
import android.content.BroadcastReceiver
import android.content.Context;
import android.content.Intent;
class BootReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
val i = Intent(context, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
}
}
}
Add permission on your manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Add receiver tag inside application tag on your manifest
<receiver
android:enabled="true"
android:exported="true"
android:name="com.example.app.BootReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Add code to open your app after booting was completed on your MainActivity.kt, you can find it on project_name/android/app/src/main/kotlin/com/example/app/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var REQUEST_OVERLAY_PERMISSIONS = 100
if (!Settings.canDrawOverlays(getApplicationContext())) {
val myIntent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
val uri: Uri = Uri.fromParts("package", getPackageName(), null)
myIntent.setData(uri)
startActivityForResult(myIntent, REQUEST_OVERLAY_PERMISSIONS)
return
}
}
don't forget to import this code below on your MainActivity.kt because you need Bundle and Settings package
import android.os.Bundle
import android.provider.Settings
Works on my flutter app, tested on android 11.

start my service on phone restart in android

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

Constantly check for wireless network change [duplicate]

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

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

Categories

Resources