Connect to an open network with Android (Java) - java

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.

Related

SDK not registering (from non view constructor, not an onCreate()) - No errors

I am making a cleaner version of a research drone android app that utilises DJI SDK/Hardware and attempting to structure the app more appropriately such that it can be expanded later. The application allows user selection of hardware (currently mock/test, DJI and ToDo) from a config pop up in the main display (class UserInterface extends AppCompatActivity). This is to allow the app to be used without registering or check perms when it is not being used for DJI. Previously I registered the DJI SDK when the app first opens, but it was my first real app and was a mess to follow its flow and didn't manage screen real estate very well.
When the DJI option is actioned from the pop up "config" window on the main interface from UI class, the UI class saves the config to a SettingsManager instance and calls the EventsManager instance with method runSettings(). The method actions the relevant SDK by try/catch{new DJI SDK class} and passes both the instances of EventsManager and UI.
The difference of this major version compared to my first version (which functions correctly) is the API key (changed package name, so new key), I am not doing the SDK registration in the first main activity and the SDK registration is not a viewable class, it only forwards strings to run on UI thread for showToast method in the UI class.
App does not return any errors.
showToast for messages in the DJI SDK class appear on the display but nothing inside the
SDKManagerCallback occurs.
Unsure of constructor in a class with extends AppCompatActivity, context methods seem unavailable when
tried with different class extensions.
I have tried creating two DJI developer keys, no difference.
Unsure of DJI class listing in Manifest as it is not an activity started by an intent with bundle but
does require context.
DJI SDK class is extracted from DJISDKDemo (I am fairly new to android app development, not sure I
could write my own version from the limited explanation on DJI dev site).
Thank you greatly for your help and any other tips appreciated.
The SDKRegistration class:
package com.research.droneapp; // mock package name for SO
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import dji.common.error.DJIError;
import dji.common.error.DJISDKError;
import dji.sdk.base.BaseComponent;
import dji.sdk.base.BaseProduct;
import dji.sdk.sdkmanager.DJISDKInitEvent;
import dji.sdk.sdkmanager.DJISDKManager;
public class SoftwareDevelopmentKitDJI extends AppCompatActivity {
private static final String TAG = "SoftwareDevelopmentKit";
public UserInterface userInterface;
public EventsManager eventsManager;
public static final String FLAG_CONNECTION_CHANGE = "dji_sdk_connection_change";
private static BaseProduct mProduct;
private Handler mHandler;
public boolean isConnected = false; // Variable for start up flag
private static final String[] REQUIRED_PERMISSION_LIST = new String[]{
Manifest.permission.VIBRATE,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.WAKE_LOCK,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE,
};
private List<String> missingPermission = new ArrayList<>();
private AtomicBoolean isRegistrationInProgress = new AtomicBoolean(false);
private static final int REQUEST_PERMISSION_CODE = 12345;
public SoftwareDevelopmentKitDJI(UserInterface userInterface, EventsManager eventsManager) {
Log.d(TAG, "SoftwareDevelopmentKitDJI");
this.userInterface = userInterface;
this.eventsManager = eventsManager;
// Permission checked true actions SDK registration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkAndRequestPermissions();
}
// Handle DJI SDK hardware changes in background thread??
// ToDo: Receive hardware changes in EventsManager
mHandler = new Handler(Looper.getMainLooper());
}
/**
* Checks if there is any missing permissions, and
* requests runtime permission if needed.
*/
private void checkAndRequestPermissions() {
Log.d(TAG, "checkAndRequestPermissions: S");
// Check for permissions
for (String eachPermission : REQUIRED_PERMISSION_LIST) {
if (ContextCompat.checkSelfPermission(userInterface, eachPermission) !=
PackageManager.PERMISSION_GRANTED) {
missingPermission.add(eachPermission);
}
}
// Request for missing permissions
if (missingPermission.isEmpty()) {
Log.d(TAG, "notMissingPerms");
startSDKRegistration();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Log.d(TAG, "missingPerms");
passToastToUI("Need permissions!");
ActivityCompat.requestPermissions(userInterface,
missingPermission.toArray(new String[missingPermission.size()]),
REQUEST_PERMISSION_CODE);
}
Log.d(TAG, "checkAndRequestPermissions: E");
}
/**
* Result of runtime permission request
*/
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Check for granted permission and remove from missing list
if (requestCode == REQUEST_PERMISSION_CODE) {
for (int i = grantResults.length - 1; i >= 0; i--) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
missingPermission.remove(permissions[i]);
}
}
}
// If no missing permission, start SDK registration
if (missingPermission.isEmpty()) {
startSDKRegistration();
} else {
passToastToUI("Missing permissions!!!");
}
}
private void startSDKRegistration() {
Log.d(TAG, "startSDKRegistration: S");
if (isRegistrationInProgress.compareAndSet(false, true)) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
passToastToUI("registering, pls wait...");
Log.d(TAG, "startSDKRegistration: run");
// ToDO: Investigate why SDKManagerCallback's don't occur
// (is getApplicationContext() correct?)
DJISDKManager.getInstance().registerApp(getApplicationContext(),
new DJISDKManager.SDKManagerCallback() {
#Override
public void onRegister(DJIError djiError) {
Log.d(TAG, "onRegister: S");
if (djiError == DJISDKError.REGISTRATION_SUCCESS) {
passToastToUI("Register Success");
DJISDKManager.getInstance().startConnectionToProduct();
}
else {
passToastToUI("Register sdk failed!");
}
Log.v(TAG, djiError.getDescription());
Log.d(TAG, "onRegister: E");
}
#Override
public void onProductDisconnect() {
Log.d(TAG, "onProductDisconnect");
passToastToUI("Product Disconnected");
notifyStatusChange();
isConnected = false; // Set hardware connection flag
}
#Override
public void onProductConnect(BaseProduct baseProduct) {
Log.d(TAG, String.format("onProductConnect newProduct:%s", baseProduct));
passToastToUI("Product Connected");
notifyStatusChange();
isConnected = true; // Set hardware connection flag
}
#Override
public void onComponentChange(BaseProduct.ComponentKey componentKey, BaseComponent oldComponent,
BaseComponent newComponent) {
if (newComponent != null) {
newComponent.setComponentListener(new BaseComponent.ComponentListener() {
#Override
public void onConnectivityChange(boolean isConnected) {
Log.d(TAG, "onComponentConnectivityChanged: " + isConnected);
notifyStatusChange();
}
});
}
Log.d(TAG, String.format(
"onComponentChange key:%s, oldComponent:%s, newComponent:%s",
componentKey, oldComponent, newComponent));
}
#Override
public void onInitProcess(DJISDKInitEvent djisdkInitEvent, int i) {
Log.d(TAG, "startSDKRegistration: onInitProcess");
}
#Override
public void onDatabaseDownloadProgress(long l, long l1) {
Log.d(TAG, "startSDKRegistration: onDatabaseDownloadProgress");
}
});
}
});
}
Log.d(TAG, "startSDKRegistration: E");
}
private void notifyStatusChange() {
mHandler.removeCallbacks(updateRunnable);
mHandler.postDelayed(updateRunnable, 500);
}
private Runnable updateRunnable = () -> {
Intent intent = new Intent(FLAG_CONNECTION_CHANGE);
sendBroadcast(intent);
};
private void passToastToUI(String toastMsg) {
runOnUiThread(() -> {
userInterface.showToast(toastMsg);
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.research.droneapp"> <!-- mock package name for SO -->
<!-- Permissions and features -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature
android:name="android.hardware.usb.host"
android:required="false" />
<uses-feature
android:name="android.hardware.usb.accessory"
android:required="true" />
<!-- App Activity Process -->
<application
android:name="com.research.droneapp.MApplication"
android:allowBackup="true"
android:icon="#mipmap/hmu_icon"
android:label="#string/app_name"
android:roundIcon="#mipmap/hmu_icon_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<!-- Main Display -->
<activity android:name="com.research.droneapp.UserInterface" />
<!-- DJI SDK -->
<uses-library android:name="com.android.future.usb.accessory" />
<meta-data
android:name="com.dji.sdk.API_KEY"
android:value="*************" /> <!-- removed for SO -->
<activity
android:name="dji.sdk.sdkmanager.DJIAoaControllerActivity"
android:theme="#android:style/Theme.Translucent">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
android:resource="#xml/accessory_filter" />
</activity>
<service android:name="dji.sdk.sdkmanager.DJIGlobalService">
</service>
<activity android:name="com.research.droneapp.SoftwareDevelopmentKitDJI" />
<!-- Splash Screen at Launch -->
<activity android:name="com.research.droneapp.Splash" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The method that starts the SDK class:
/**
* Settings changes to start relevant classes
*/
public void runSettings() {
Log.d(TAG, "runSettings: S");
// Get hardware selection from settings
int hardwarePosition = settingsManager.getHardwareInt();
/*ToDo: Set Test Environment*/
if (hardwarePosition == 0) { // Operate settings for test environment
Log.d(TAG, "runSettings: hardPos Test");
userInterface.showToast("runSetting: TEST");
}
else if (hardwarePosition == 1) { // Operate settings for DJI
Log.d(TAG, "runSettings: hardPos MavP2");
try {
this.softwareDevelopmentKitDJI = new SoftwareDevelopmentKitDJI(
userInterface, this);
Log.d(TAG, "runSettings: DJI Launched");
userInterface.showToast("runSetting: DJI");
} catch (Exception e) {
Log.d(TAG, "runSettings: DJI Error: "+ e.toString());
userInterface.showToast("runSetting: Error");
}
} // Operate settings for...?
else if (hardwarePosition == 2) { /*ToDo*/
Log.d(TAG, "runSettings: hardPos ToDo");
userInterface.showToast("runSetting: ToDo");
}
else { // Unknown hardware
Log.d(TAG, "runSettings: Error");
userInterface.showToast("runSetting:Error");
}
Log.d(TAG, "runSettings: E");
}
The config window click listener for action changes button, within the method of UI class for config pop up window:
// Action changes
Button btnAction = popupView.findViewById(R.id.btnAction);
btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "displayConfigOverlay: onClick -> configAction");
// Update hardware setting
String hardware =
(btnTest.isChecked())?settingsManager.HARDWARE_OPTIONS[0]:
(btnMavP2.isChecked())?settingsManager.HARDWARE_OPTIONS[1]:
(btnToDo.isChecked())?settingsManager.HARDWARE_OPTIONS[2]:
"NoSelection!";
settingsManager.setHardware(hardware);
// Update port number
String port = serverPortEdit.getText().toString();
settingsManager.setServerPort(port);
// Update WSS launch setting
boolean autoLunchWSS = swAutoWSS.isChecked();
settingsManager.setAutoLaunchWSS(autoLunchWSS);
// Display to user
showToast("Hardware: " + hardware + "\nPort: " + port + "\nAutoWSS: " +
autoLunchWSS);
// Push settings
eventsManager.runSettings();
// Close config pop up
popupConfig.dismiss();
}
});
Apologises for the lack of and mixed commenting styles. Again any tips appreciated, still new to android and java.
Min API23 setting in gradle allowed code to run but did not allow SDK to download. Unsure why errors not returned.
Solved by changing gradle to following:
...
android {
compileSdkVersion 29
buildToolsVersion '28.0.3'
useLibrary 'org.apache.http.legacy'
defaultConfig {
minSdkVersion 19
targetSdkVersion 29
multiDexEnabled true
ndk {
abiFilters 'armeabi-v7a', 'x86', 'arm64-v8a'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
...
Additionally found a potential context issue within layout, tools:context="..." was not set to the Activity interacting with this layout.
...
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mainConstraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".UserInterface" >
...

Writing permission on android filesystems

I should generate a .pdf file inside the android data folder to use the Java code below, with the permissions enabled in the XML manifest file. But when I run the code I have the following exception. The application has different permissions within the manifest, It should all be configured correctly, I state that the application I'm testing on an old Android 4. How can I solve this? and what is it due to?
Exception: error: java. I. FileNotFoundException: /data/my.pdf:
open failed: EACCES (Permission denied)
Code:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE " />
public static Boolean GeneratePDF(String base64) {
Boolean ret = true;
try {
String direttorio=""+Environment.getDataDirectory().getAbsolutePath();
final File dwldsPath = new File(direttorio + "/" + "my.pdf");
byte[] pdfAsBytes = Base64.decode(base64, 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
os.close();
} catch (Exception ex) {
System.out.println("\n Errore Generazione File: "+ex);
ret = false;
}
return ret;
}
you have to give Write permission at run time.
It can be achieved something as following...
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{
private static final int REQUEST_WRITE_PERMISSION = 111;
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
GeneratePDF("your String name");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
} else {
GeneratePDF("your String name");
}
}
}
Replace this line
String direttorio=""+Environment.getDataDirectory().getAbsolutePath();
To:
String direttorio= Environment.getExternalStorageDirectory().getAbsolutePath();
final File dwldsPath = new File(direttorio + "/" + my.pdf");
if you're using Android 6.0 and above,
there could be 2 ways:
1 if you're making only for demo purpose you can manually give permission to app
by going in settings->apps->permissions. Then allow all permission which are
required.
2 you've to implement runtime permissions so that user can allow it runtime.

add new network to android device programsticly

I need to connect to new wifi network programaticly to my device with this code:
`
try
{
String ssid = "\"" + SSID + "\"";
String pass = "\"" + Pass + "\"";
for (ScanResult result : results)
{
if (result.SSID.equals(SSID))
{
String security = getScanResultSecurity(result);
if (security.equals("PSK")) {
WifiConfiguration con = new WifiConfiguration();
con.SSID = ssid;
AlertDialog a = new AlertDialog.Builder(MainActivity.this).create();
a.setMessage("in");
a.show();
con.preSharedKey = pass;
con.hiddenSSID = true;
con.status = WifiConfiguration.Status.ENABLED;
con.allowedGroupCiphers.set(WifiConfiguration.Grou pCipher.TKIP);
con.allowedGroupCiphers.set(WifiConfiguration.Grou pCipher.CCMP);
con.allowedKeyManagement.set(WifiConfiguration.Key Mgmt.WPA_PSK);
con.allowedPairwiseCiphers.set(WifiConfiguration.P airwiseCipher.TKIP);
con.allowedPairwiseCiphers.set(WifiConfiguration.P airwiseCipher.CCMP);
con.allowedKeyManagement.set(WifiConfiguration.Key Mgmt.NONE);
con.allowedProtocols.set(WifiConfiguration.Protoco l.RSN);
con.allowedProtocols.set(WifiConfiguration.Protoco l.WPA);
int ntid = wifimanager.addNetwork(con);
wifimanager.disconnect();
wifimanager.enableNetwork(ntid,true);
wifimanager.reconnect();
boolean b = wifimanager.saveConfiguration();
if (ntid != -1 && b) {
AlertDialog a2 = new AlertDialog.Builder(MainActivity.this).create();
a2.setMessage("saved");
a2.show();
}
}
}
}
catch (Exception ex) {
AlertDialog a = new AlertDialog.Builder(MainActivity.this).create();
a.setMessage(ex.getMessage());
a.show();
}
`
but i can't add network to my device
problem is with network configuration that can't add to networks
I cant understand why doesn't work haven't erorr but no result
help me please
You should add permissions into manifest (and runtime 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.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

Android Wear: Wi-Fi Scan No Results

Whenever I try to use a Wi-Fi Scan for Android Wear, I always get no results from the scan. The code that I use works for my mobile device, but with Android Wear, it always returns an empty list. Code is as follows:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAmbientEnabled();
mContainerView = (BoxInsetLayout) findViewById(R.id.container);
mTextView = (TextView) findViewById(R.id.text);
mClockView = (TextView) findViewById(R.id.clock);
test = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mTextView.setVisibility(View.VISIBLE);
if (test.isWifiEnabled() == false)
{
test.setWifiEnabled(true);
}
registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
Log.w("myApp", "received");
List<ScanResult> results = test.getScanResults();
int j = 0;
int myArray1[] = new int[results.size()];
String myArray2[] = new String[results.size()];
for (ScanResult result : results) {
//toPrint+= " " + result.BSSID + " " + result.level + "\n";
myArray1[j] = result.level;
myArray2[j] = result.BSSID;
j++;
if (j > 20) {
break;
}
}
Button test2;
test2 = (Button) findViewById(R.id.tLight);
test2.setText("Test: " + Integer.toString(results.size()));
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 0x12345);
}
test.startScan();
}
The following permissions are also enabled in the manifest file:
<uses-feature android:name="android.hardware.type.watch" />
<uses-feature android:name="android.hardware.wifi" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

How to enable/disable WiFi from an application?

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

Categories

Resources