I want to enable/disable wifi from my Android application. How can I do that?
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false); // true or false to activate/deactivate wifi
You also need to request the permission in your AndroidManifest.xml :
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
To enable/disable WiFi in your application you need to use WiFiManager class. Create an Object of WiFiManager class to get the services of WiFi.
WifiManager wifi;
wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);//Turn off Wifi
wifi.setWifiEnabled(true);//Turn on Wifi
And you have to put the following permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
To get the whole sample code of enable/disable Wifi in android with UI visit this website
try this code
Intent gpsOptionsIntent = new Intent( android.provider.Settings.ACTION_WIFI_SETTINGS);
startActivityForResult(gpsOptionsIntent,0);
To enable/disable wifi from an app in Android Q (Android 10) use Settings Panel:
val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
startActivityForResult(panelIntent, 0)
On previous versions of Android this should work (appropriate permissions should be added to AndroidManifest file, see answers above):
(context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }
Resulting code might look something like this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
startActivityForResult(panelIntent, 0)
} else {
(context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }
}
Where context is a reference to android.content.Context object.
try this
public void disableWifi(Context context, Boolean bool) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if(bool)
wifi.setWifiEnabled(false);
else
wifi.setWifiEnabled(true);
}
public class MainActivity extends AppCompatActivity {
Switch btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Switch) findViewById(R.id.switch1);
btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
toggleWiFi(true);
Toast.makeText(getApplicationContext(), "Wi-Fi Enabled!", Toast.LENGTH_LONG).show();
} else {
toggleWiFi(false);
Toast.makeText(getApplicationContext(), "Wi-Fi Disabled!", Toast.LENGTH_LONG).show();
}
}
});
}
public void toggleWiFi(boolean status){
WifiManager wifiManager = (WifiManager)this.getSystemService(WIFI_SERVICE);
if (status && !wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
} else if (!status && wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
}
}
Add User Permission in Manifest Files
Related
I'm trying to connect to a bluetooth headset to record audio from device , the issue is that it shows that it is connected but right after it goes to disconnected for some reason , i'm debugging the code but could not figure out the problem , i would appreciate anyone giving some help , Thank you
Manifest File
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<uses-permission android:name="android.permission.BLUETOOTH" android:required="false" />
Registering receiver
public void onCreate() {
super.onCreate();
recorder = new Recorder(getApplicationContext());
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
nm = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
settings = Core.getInstance().getCache().getPrefs();
self = this;
// register new receiver for bluetooth headset
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter.isEnabled()){
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); // API 11
intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED); // API 8
intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED); // API 14
registerReceiver(broadcastReceiver,intentFilter);
audioManager.startBluetoothSco();
}
}
Receiver code
// when the call starts it executed CONNECTED then right after it goes to DISCONNECTED
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,-1);
if(AudioManager.SCO_AUDIO_STATE_CONNECTED == state){
Log.d("TAG","Connected");
audioManager.setSpeakerphoneOn(false);
audioManager.setBluetoothScoOn(true);
} else if (AudioManager.SCO_AUDIO_STATE_DISCONNECTED == state){
Log.d("TAG","Disconnected");
}
}
};
This is my first app in Android. I am very new to Android and Java. I am kind of expert in iOS/ObjC though. I am learning by doing. So I jumped straight into making an app to connect to a bluetooth device. First step is of course to get a list of the bluetooth device available in range.
Here is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest...>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application ...
Here is my Activity code:
private BluetoothAdapter btAdapter;
#Override
public void onDestroy() {
super.onDestroy();
// Unregister broadcast listeners
unregisterReceiver(mReceiver);
}
/*------------- ON CREATE ------------------------------*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null) {
System.out.println ("Bluetooth non support");
} else {
System.out.println ("Bluetooth initialized");
}
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
IntentFilter filterDevice = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filterDevice);
if (btAdapter.isEnabled()) {
String mydeviceaddress = btAdapter.getAddress();
String mydevicename = btAdapter.getName();
String status = mydevicename + " : " + mydeviceaddress;
System.out.println(status);
System.out.println ("Start discover");
btAdapter.startDiscovery();
} else {
System.out.println ("Not enabled");
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, 1);
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
System.out.println("1");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
System.out.println("2");
break;
case BluetoothAdapter.STATE_ON:
System.out.println("3");
// SCAN HERE
btAdapter.startDiscovery();
break;
case BluetoothAdapter.STATE_TURNING_ON:
System.out.println("4");
break;
}
}
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
System.out.println(device.getName() + "\n" + device.getAddress());
} else {
System.out.println("What de fuq");
}
}
};
I turned on bluetooth on my android phone, and then running the app shows that log:
Bluetooth initialized
Start discover
And thats all. Other logs are not printing out. Any idea why? My code seems perfect idk.
EDIT: Screenshot of the Bluetooth module HC-05 being detected by Android.
The other devices may not be in discoverable mode. Make sure they are discoverable.
If your other device is a bluetooth module, in your case Arduino, right?
If so, check this tutorial describing connection between Android device and HC05 module.
bthc-05 to android tutorial
Also, based on this official sample: google sample - bluetooth chat
Alternatively, you could also have the following method that makes your device discoverable. And install it on two phones. Then you should be able to discover the phones on each other atleast.
protected void makeDiscoverable(){
// Make local device discoverable
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}
Maybe these help!
I am developing an App to check Wifi points.
I am getting error "java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results" at wifiManager.getScanResults() even though I already declared those permissions.
main activity
public class MainActivity extends AppCompatActivity {
WifiManager wifiManager;
String[] wifis;
WifiReceiver wifiReceiver;
ListView wifiListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wifiListView = (ListView) findViewById(R.id.wifi_list);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiReceiver = new WifiReceiver();
wifiManager.startScan();
}
protected void onPause() {
unregisterReceiver(wifiReceiver);
super.onPause();
}
protected void onResume() {
registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
private class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> wifiScanList = wifiManager.getScanResults();
wifis = new String[wifiScanList.size()];
for (int i = 0; i < wifiScanList.size(); i++) {
wifis[i] = wifiScanList.get(i).toString();
}
wifiListView.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, wifis));
}
}
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sample">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I am on SDK 6.0
I observed similar question, but solution does not apply since I already declared permission.
Anyone know what might be problem? Thank you.
In Android M, you need to ask for the permission which is defined as dangerous in PermissionModel to the user before start using each time, it as such:
private boolean mayRequestLocation() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
Snackbar.make(mView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
}
});
} else {
requestPermissions(new String[]{ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
}
return false;
}
Add this to your Activity:
private static final int REQUEST_FINE_LOCATION=0
and load it during runtime with:
loadPermissions(Manifest.permission.ACCESS_FINE_LOCATION,REQUEST_FINE_LOCATION);
To evaluate the results of your permission request, you can override onRequestPermissionsResult method:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// The requested permission is granted.
}
else{
// The user disallowed the requested permission.
}
return;
}
}
MADAO is right: you should turn on GPS to get the WIFI access point list.
But I'm not sure about PEERS_MAC_ADDRESS. If you look at the source code (line 957):
/**
* Return the results of the most recent access point scan, in the form of
* a list of {#link ScanResult} objects.
* #return the list of results
*/
public List<ScanResult> getScanResults(String callingPackage) {
enforceAccessPermission();
int userId = UserHandle.getCallingUserId();
int uid = Binder.getCallingUid();
boolean canReadPeerMacAddresses = checkPeersMacAddress();
boolean isActiveNetworkScorer =
NetworkScorerAppManager.isCallerActiveScorer(mContext, uid);
boolean hasInteractUsersFull = checkInteractAcrossUsersFull();
long ident = Binder.clearCallingIdentity();
try {
if (!canReadPeerMacAddresses && !isActiveNetworkScorer
&& !isLocationEnabled()) {
return new ArrayList<ScanResult>();
}
if (!canReadPeerMacAddresses && !isActiveNetworkScorer
&& !checkCallerCanAccessScanResults(callingPackage, uid)) {
return new ArrayList<ScanResult>();
}
if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
!= AppOpsManager.MODE_ALLOWED) {
return new ArrayList<ScanResult>();
}
if (!isCurrentProfile(userId) && !hasInteractUsersFull) {
return new ArrayList<ScanResult>();
}
return mWifiStateMachine.syncGetScanResultsList();
} finally {
Binder.restoreCallingIdentity(ident);
}
}
The first if is checking canReadPeerMacAddresses which the code for checkPeersMacAddress() is:
/**
* Returns true if the caller holds PEERS_MAC_ADDRESS.
*/
private boolean checkPeersMacAddress() {
return mContext.checkCallingOrSelfPermission(
android.Manifest.permission.PEERS_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
}
If you add the permission you can bypass if (!canReadPeerMacAddresses && !isActiveNetworkScorer && !isLocationEnabled()) {. I've tested but I cannot get WIFI MAC list by just using the permission and disabling location.
ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION is necessary. To get a valid result, you also have to turn on GPS or get a PEERS_MAC_ADDRESS permission like Setting.
Im developing an android app. For this app to work the Wi-Fi needs to be enabled all the time. Because the Wi-Fi is enabled it will keep on scanning for available networks.
I want some function to be called as soon as the Wi-Fi connects to a particular network.
How do I achieve this?
I have written the following code but this works only once, how do I make this scan for networks continuously?
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifi.isConnected()){
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) {
String ssid = connectionInfo.getSSID();
}
Log.i("wifi", "connected");
}
else{
Log.i("wifi", "not connected");
}
Follow the steps and do a trick
1) Create NetworkChangeReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
public static boolean isWifiConnected = true;
public static final String tag = "NETWORKCHANGERECEIVER";
#Override
public void onReceive(final Context context, final Intent intent) {
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifi.isConnected()) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) {
String ssid = connectionInfo.getSSID();
}
isWifiConnected = true;
Log.i("wifi", "connected");
} else {
Log.i("wifi", "not connected");
isWifiConnected = false;
}
}
}
2) Add this line to Manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<receiver android:name="com.df.src.NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
You should use a BroadcastReceiver in your application to get instant notifications about connectivity changes.
Some reference that may help you:
http://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/
http://developerandro.blogspot.com/2013/09/check-internet-connection-using.html?m=1
http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
I looked into different posts or sites to help me to do an app which can connect to an open wifi network (name: OpenWrt). I can't connect with the app unless I manually do it before. Could someone please look into this and help me? :) I should maybe add the network to the networks list on the phone, but I'm not sure how to do it, if it is the problem.
Thank you!
package com.example.wificonnect;
import java.util.List;
import android.app.Activity;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.content.Context;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Définition du réseau wifi auquel on se connecte
String networkSSID = "\"OpenWrt\"";
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Configuration des paramètres de connexion
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = networkSSID;
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
// Activation du wifi si pas encore activé
if(wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
else {
wifiManager.setWifiEnabled(true);
}
int netId = wifiManager.addNetwork(conf);
wifiManager.enableNetwork(netId, true);
wifiManager.setWifiEnabled(true);
}
}
I also add permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
EDIT:
Should I add something like this just after the wifi activation?
int networkId = -1;
if(wifiManager.getConfiguredNetworks() != null) {
for (WifiConfiguration configuredNetwork : wifiManager.getConfiguredNetworks()) {
if (conf.SSID.equals(configuredNetwork.SSID)) {
networkId = configuredNetwork.networkId;
Log.i(LOG_TAG, "Network already registered : " + networkId);
}
}
}
if (networkId == -1) {
networkId = wifiManager.addNetwork(conf);
Log.i(LOG_TAG, "Network registered : " + networkId);
} else {
wifiManager.updateNetwork(conf);
}
wifiManager.enableNetwork(networkId, true);
First get the ScanResult object for the open network.
Then you can use this method. That I have created for you.
public void connect(Context context, ScanResult scanResult){
WifiManagersingletonWifiManager = (WifiManager)context
.getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
configuration = new WifiConfiguration();
configuration.SSID = scanResult.SSID;
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
int networkId = singletonWifiManager.addNetwork(configuration);
if(!singletonWifiManager.isWifiEnabled())
singletonWifiManager.setWifiEnabled(true);
singletonWifiManager.disconnect();
singletonWifiManager.enableNetwork(networkId,true);
singletonWifiManager.reconnect();
}
Also dont forget to declare permissions in the Manifest file.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Useful Resource:
You can check out my Repository on Github for more related code.