Why the number of wifi connections: 0? - java

I want to show Wifi connection list with android studio. There are 2 connections on wifi settings of my phone but my application doesn't see them.
Thanks in advance
When I open debug application i see this sentence:
Number Of Wifi connections : 0
So why It can't see wifi connections?
I tried when wifi is enabled and when it's disabled.
MainActivity.java
import java.util.List;
import android.annotation.SuppressLint;
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.widget.TextView;
public class MainActivity extends Activity {
private StringBuilder sb = new StringBuilder();
private TextView tv;
List<ScanResult> scanList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv= (TextView)findViewById(R.id.txtWifiNetworks);
getWifiNetworksList();
}
private void getWifiNetworksList(){
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
final WifiManager wifiManager =
(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);;
registerReceiver(new BroadcastReceiver(){
#SuppressLint("UseValueOf") #Override
public void onReceive(Context context, Intent intent) {
sb = new StringBuilder();
scanList = wifiManager.getScanResults();
sb.append("\n Number Of Wifi connections :" + " " +scanList.size()+"\n\n");
for(int i = 0; i < scanList.size(); i++){
sb.append(new Integer(i+1).toString() + ". ");
sb.append((scanList.get(i)).toString());
sb.append("\n\n");
}
tv.setText(sb);
}
},filter);
wifiManager.startScan();}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="hacker.wifi.mywifilist.MainActivity"
android:id="#+id/main">
<TextView
android:id="#+id/txtWifiNetworks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</android.support.constraint.ConstraintLayout>

Turn the location toggle of the device. Since Marshmallow it's a must.
Make sure that you have these permissions (you might omit some of them after testing, I took it from a similar project I did):
<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_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

Related

Ble Broadcast receiver not displaying on listview

(DISCLAIMER: SUPER NEW TO ANDROID STUDIO) I'm creating an app to scan for ble devices and display them on the list but it seems like no devices are being discovered and being displayed on the listview. Any help is appreciated. I'm planning to update the Textview with the number of devices that are found. I haven't set up the scanfilters yet since I'm still trying to figure out the UUIDs for the tags that I'm using. I also changed the min sdk to 23 since it was giving me an error while setting the scanmode, callback, and matchmode.
MainActivity.java
package com.example.tygatraxseconddraft;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "TWESBTSCANNER";
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
private ListView listView;
private Button scanningBtn;
private BluetoothAdapter bluetoothAdapter;
private final ArrayList<String> mDeviceList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.device_list);
scanningBtn = findViewById(R.id.scanning_btn);
hasPermissions();
checkBluetoothState();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
listView = findViewById(R.id.device_list);
scanningBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
final ScanCallback scanCallback = new ScanCallback() { //studio made it not private
#Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
// ...do whatever you want with this found device
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
// Ignore for now
}
#Override
public void onScanFailed(int errorCode) {
// Ignore for now
}
};
UUID SERVICE_DATA_UUID = UUID.fromString("00005246-0000-1000-8000-00805f9b34fb");//filter for the Nordic tags
UUID[] serviceUUIDs = new UUID[]{SERVICE_DATA_UUID};
List<ScanFilter> filters = null;
if (serviceUUIDs != null) {
filters = new ArrayList<>();
for (UUID serviceUUID : serviceUUIDs) {
ScanFilter filter = new ScanFilter.Builder()
.setServiceUuid(new ParcelUuid(serviceUUID))
.build();
filters.add(filter);
}
}
ScanSettings scanSettings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
.setReportDelay(0L)
.build();
if (scanner != null) {
scanner.startScan(null, scanSettings, scanCallback); // must set scan settings first
Log.d(TAG, "scan started");
} else {
Log.e(TAG, "could not get scanner object");
}
}
});
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
public final BroadcastReceiver mReceiver = new BroadcastReceiver() { //
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, mDeviceList));
}
}
};
private boolean hasPermissions() { //checks and asks for location permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getApplicationContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION }, REQUEST_ACCESS_COARSE_LOCATION);
return false;
}
}
return true;
}
//ENABLE WHEN TESTING ON PHONE
private void checkBluetoothState() {
//gets the bluetooth adapter
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter.isEnabled()){
Toast.makeText(this,"Bluetooth is enabled", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please turn on Bluetooth", Toast.LENGTH_SHORT).show();
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}//requests permission if bluetooth is not enabled
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tygatraxseconddraft">
<!-- Request legacy Bluetooth permissions on older devices. -->
<uses-permission android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<!-- Needed only if your app looks for Bluetooth devices.
You must add an attribute to this permission, or declare the
ACCESS_FINE_LOCATION permission, depending on the results when you
check location usage in your app. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<!-- Needed only if your app makes the device discoverable to Bluetooth
devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<!-- Needed only if your app communicates with already-paired Bluetooth
devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION_LOCATION"/>
<!--Makes the app show up for only ble enabled devices-->
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true"/>
<application
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/Theme.TygaTraxsecondDraft">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
tools:context=".MainActivity">
<TextView
android:id="#+id/number_devices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="#string/number_of_devices"
android:textColor="#color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/scanning_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="50dp"
android:text="#string/button_text"
android:textColor="#212121"
app:backgroundTint="#color/gray"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<ListView
android:id="#+id/device_list"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="24dp"
app:layout_constraintBottom_toTopOf="#+id/scanning_btn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/number_devices" />
</androidx.constraintlayout.widget.ConstraintLayout>
In case this is needed
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="gray">#7393B3</color>
</resources>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Tyga Trax (second draft)</string>
<string name="button_text">Scan</string>
<string name="number_of_devices">There are </string>
</resources>
New Answer
I just realised you are simply doing nothing with the found devices right now, your ScanCallback is empty. You should add something like this to see the results:
final ScanCallback scanCallback = new ScanCallback() { //studio made it not private
#Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
Log.d(TAG, "BLE scan found Device " + device.getName() + " with MAC " + device.getAddress());
// TODO: add device to ListView
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
// Ignore for now
}
#Override
public void onScanFailed(int errorCode) {
// Ignore for now
}
};
You should see the found devices in your log now
Previous Answer
You are requesting the ACCESS_COARSE_LOCATION permission but your target SDK is 31. The guide for Bluetooth permissions states
ACCESS_FINE_LOCATION is necessary because a Bluetooth scan can gather information about the location of the user. This information may come from the user's own devices, as well as Bluetooth beacons in use at locations such as shops and transit facilities.
and also
Note: If your app targets Android 9 (API level 28) or lower, you can declare the ACCESS_COARSE_LOCATION permission instead of the ACCESS_FINE_LOCATION permission.
It even states to use ACCESS_BACKGROUND_LOCATION for devices with Android 10 or above. But there are new permissions for a target SDK of 31 (Android 12) as stated in this document.
<manifest>
<!-- Request legacy Bluetooth permissions on older devices. -->
<uses-permission android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<!-- Needed only if your app looks for Bluetooth devices.
You must add an attribute to this permission, or declare the
ACCESS_FINE_LOCATION permission, depending on the results when you
check location usage in your app. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<!-- Needed only if your app makes the device discoverable to Bluetooth
devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<!-- Needed only if your app communicates with already-paired Bluetooth
devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
...
</manifest>
As you can see the legacy Bluetooth permissions like BLUETOOTH are added as well, but have the option android:maxSdkVersion="30" set to only work up to Android 11.

Android Internet Connectivity Listener Problem

I would like to put a Network Detector in an Android application, to inform a Screen immediately the Network state even if that state is changing. I have study similar questions in:
Android: Internet connectivity change listener
So my Java code in Main Activity is:
package com.example.netdetector;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
private TextView Screen;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Screen = (TextView) findViewById(R.id.Screen);
Screen.setText("Start!");
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
// network available
Screen.setText("Net On!");
}
#Override
public void onLost(Network network) {
// network unavailable
Screen.setText("Net Off!");
}
};
ConnectivityManager connectivityManager =
(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
NetworkRequest request = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
connectivityManager.registerNetworkCallback(request, networkCallback);
}
}
}
The AndroidManifest.xml is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.netdetector">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
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/Theme.NetDetector">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The Layout activity_main.xml is:
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/Screen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello World!"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.222" />
</androidx.constraintlayout.widget.ConstraintLayout>
There are some issues:
Starting the App with the Network Off, the Screen displays "Start!" instead of "Net Off!"
Starting the App with the Network On, the Screen displays "Net On" that is fine
On changing Internet state while the app is running the Screen displays the right text for a few moments and the app closes immediately.
How can I fix 1 and 3? What went wrong?
Thanks
Nickolas

ListView not getting populated with bluetooth devices

I am trying to build an app to scan bluetooth services that aren't paired with my device around me. However, when I click the scan button, the ListView is not populated with the devices name and android MAC address. I do not get any error when I run my code.
This is what i get in my logcat file:
/? E/e.bluetoothtes: Unknown bits set in runtime_flags: 0x8000
/com.example.bluetoothtest I/Perf: Connecting to perf service.
/com.example.bluetoothtest I/e.bluetoothtes: [GL_OOM] ClampGrowthLimit 268435456
/com.example.bluetoothtest V/Font: Change font:2
/com.example.bluetoothtest V/Font: Default family:android.graphics.Typeface#4cabfbd5
/com.example.bluetoothtest E/Perf: Fail to get file list com.example.bluetoothtest
/com.example.bluetoothtest E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
/com.example.bluetoothtest E/Perf: Fail to get file list com.example.bluetoothtest
/com.example.bluetoothtest E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
/com.example.bluetoothtest V/FlingOptimizerScroller: FlingOptimizerOverScroller Init
The one's in bold show up as red.
Here is my MainActivity.java file:
'''
package com.example.bluetoothtest;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
{
Button ScanButton;
ListView scanListView;
ArrayList<String> stringArrayList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
BluetoothAdapter myAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScanButton = (Button) findViewById(R.id.scanDevices);
scanListView = (ListView) findViewById(R.id.devicesList);
ScanButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
myAdapter.startDiscovery();
}
});
int permissionCheck =
this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck +=
this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0)
{
this.requestPermissions(new String[].
{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
}
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(myReceiver, intentFilter);
arrayAdapter = new ArrayAdapter<>(getApplicationContext(),
android.R.layout.simple_list_item_1, stringArrayList);
scanListView.setAdapter(arrayAdapter);
}
BroadcastReceiver myReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
stringArrayList.add(device.getName() + "\n" + device.getAddress());
arrayAdapter.notifyDataSetChanged();
}
}
};
}
'''
This is my activity_main.xml. I am, using Linear Layout:
'''
<Button
android:id="#+id/scanDevices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="Scan"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"/>
<ListView
android:id="#+id/devicesList"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="70dp"
app:layout_constraintBottom_toTopOf="#+id/scanDevices"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.515"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.579" >
</ListView>
'''
I have added the following permissions to my AndroidManifest file:
'''
<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" />
'''

Can't display list of wifi connected devices in Android

I have issue with this code.I am trying to display all devices that are connected on the same WIFI in the list.
I did debugging and it shows that connection with WIFI was made but it does not detect any devices, even though there are some connected devices for sure. I did pinging with both sides with computer and android and connection was made.
If you guys have any ideas where could be a problem, please let me know, cause I am out of ideas.
MANIFEST FILE.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:required="true" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.NFC"
android:required="true" />
<application
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">
<activity
android:name=".Intro_Activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/title_activity_intro_"
android:theme="#style/FullscreenTheme"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.app.MainActivity">
<ToggleButton
android:id="#+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onToggleClicked"
android:textOff="Wi-Fi Off"
android:textOn="Wi-Fi On" />
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
MainActivity.java
package com.example.app;
import androidx.appcompat.app.AppCompatActivity;
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.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private WifiManager wifiManager;
private BroadcastReceiver wifiReciever;
private ArrayAdapter adapter;
SupplicantState supState;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WiFiScanReceiver();
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();
}
public void onToggleClicked(View view) {
adapter.clear();
ToggleButton button = findViewById(R.id.toggleButton);
if (wifiManager == null) {
//device does not support wifi
Toast.makeText(getApplicationContext(), "Oop! Your device does not support Wi-Fi",
Toast.LENGTH_SHORT).show();
button.setChecked(false);
} else {
if (button.isChecked()) { // to turn on wifi
if (!wifiManager.isWifiEnabled()) {
Toast.makeText(getApplicationContext(), "Wi-Fi is turned on." +
"\n" + "Scanning for access points...",
Toast.LENGTH_SHORT).show();
wifiManager.setWifiEnabled(true);
} else {
Toast.makeText(getApplicationContext(), "Wi-Fi is already turned on." +
"\n" + "Scanning for access points...",
Toast.LENGTH_SHORT).show();
}
wifiManager.startScan();
} else {
Toast.makeText(getApplicationContext(), "Wi-Fi is turned off.",
Toast.LENGTH_SHORT).show();
}
}
}
class WiFiScanReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
List<ScanResult> wifiScanResultList = wifiManager.getScanResults();
for (int i = 0; i < wifiScanResultList.size(); i++) {
ScanResult accessPoint = wifiScanResultList.get(i);
String listItem = accessPoint.SSID + ", " + accessPoint.BSSID;
adapter.add(listItem);
}
}
}
}
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiReciever, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(wifiReciever);
}
}

Querying Bluetooth Devices android

I am new to android and i am stuck. the basic premise for me is, when an app is opened, i need to prompt the user to switch on the bluetooth. and when yes is pressed, i need to begin scanning for nearby devices automatically. one more premise is that i should not use any buttons to start scanning. it should start automatically when the bluetooth is switched on.
The code has no syntax errors. Am i doing something wrong logically?
Because when i run the app, nothing happens. It does prompt to establish bluetooth connection, but after switch on, it should automatically scan and populate the listView in the activity_main file. which is not happening.
the activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.shashineha.mybluetoothapp.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/listView_Bluetooth"/>
</RelativeLayout>
the mainActivity.java :
package com.example.bluetooth.bluetoothApp
import android.support.v7.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.shashineha.mybluetoothapp.R;
public class MainActivity extends AppCompatActivity {
ListView listView;
BluetoothAdapter bluetoothAdapter;
ArrayAdapter mArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
if (!bluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0);
}
}
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(bluetoothAdapter.isEnabled())
{
bluetoothAdapter.startDiscovery();
}
}
// Create a BroadcastReceiver for ACTION_FOUND
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
listView = (ListView)findViewById(R.id.listView_Bluetooth);
String action = intent.getAction();
// When discovery finds a device
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
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
listView.setAdapter(mArrayAdapter);
}
}
};
#Override
protected void onDestroy()
{
super.onDestroy();
unregisterReceiver(mReceiver);
bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.disable();
}
}
the androidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth.mybluetoothapp">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<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>
</manifest>
please make sure you have added these permissions in your manifest.
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
After this, change the condition little bit this way in your onCreate()
if (!bluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0);
} else {
bluetoothAdapter.startDiscovery();
}
if bluetooth is already turned on, it will simple start scanning which is not happening at the moment. Now it should scan. also note the line
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
will create null point exception once some device founds. you can first simply check with log message initially. Bind your adapter as it is null in start. Also make sure that you have some Bluetooth devise which can be scanned.

Categories