Ble Broadcast receiver not displaying on listview - java

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

Related

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

How can I turn on and off mobile data using toggle button?

Today I have done a task using toggle button. The mobile data needs to be turned on when I press the enable toggle button, and it should be turned off when I press the same button. I had done everything and when I press the enable button, the mobile data remains off. In fact I have added all the manifest permissions. The mobile data should turn on when I press the toggle button. Please help me friends,and also let me know where I committed mistake. I hereby enclosed my XML and Java coding. Please help me friends, Many thanks in advance.
MainActivity.java:
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.os.Bundle;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainActivity extends Activity{
// constants
static final String STATUS_ON = "Mobile Data: Enable";
static final String STATUS_OFF = "Mobile Data: Disable";
static final String TURN_ON = "Enable";
static final String TURN_OFF = "Disable";
// controls
TextView TVMobileData;
ToggleButton tBMobileData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// load controls
TVMobileData=(TextView)findViewById(R.id.TVMobileData);
tBMobileData=(ToggleButton)findViewById(R.id.tBMobileData);
// set click event for button
tBMobileData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// check current state first
boolean state = isMobileDataEnable();
// toggle the state
if(state)toggleMobileDataConnection(false);
else toggleMobileDataConnection(true);
// update UI to new state
updateUI(!state);
}
});
}
public void updateUI(boolean state) {
//set text according to state
if(state) {
TVMobileData.setText(STATUS_ON);
tBMobileData.setText(TURN_OFF);
} else {
TVMobileData.setText(STATUS_OFF);
tBMobileData.setText(TURN_ON);
}
}
public boolean isMobileDataEnable() {
boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API and do whatever error handling you want here
}
return mobileDataEnabled;
}
public boolean toggleMobileDataConnection(boolean ON)
{
try {
//create instance of connectivity manager and get system connectivity service
final ConnectivityManager conman = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
//create instance of class and get name of connectivity manager system service class
final Class conmanClass = Class.forName(conman.getClass().getName());
//create instance of field and get mService Declared field
final Field iConnectivityManagerField= conmanClass.getDeclaredField("mService");
//Attempt to set the value of the accessible flag to true
iConnectivityManagerField.setAccessible(true);
//create instance of object and get the value of field conman
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
//create instance of class and get the name of iConnectivityManager field
final Class iConnectivityManagerClass= Class.forName(iConnectivityManager.getClass().getName());
//create instance of method and get declared method and type
final Method setMobileDataEnabledMethod= iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled",Boolean.TYPE);
//Attempt to set the value of the accessible flag to true
setMobileDataEnabledMethod.setAccessible(true);
//dynamically invoke the iConnectivityManager object according to your need (true/false)
setMobileDataEnabledMethod.invoke(iConnectivityManager, ON);
} catch (Exception e){
}
return true;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="arun.com.togglebuttonexample.MainActivity">
<TextView
android:id="#+id/TVMobileData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="90dp"
android:text="Mobile Data: Disable"
android:textColor="#1BD6E0"
android:textSize="40sp" />
<ToggleButton
android:id="#+id/tBMobileData"
android:layout_width="225dp"
android:layout_height="225dp"
android:layout_centerInParent="true"
android:textSize="30sp"
android:textOff="Enable"
android:textOn="Disable" />
</RelativeLayout>
AndroidManifest.xml:
<?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="arun.com.togglebuttonexample">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You can access mobile data on / off programmaticaly below android 4.4 but not above 4.4 as It's require MODIFY_PHONE_STATE permission check. This permission is only given to system or signature apps. so It wont work on non-rooted phone.

Why the number of wifi connections: 0?

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

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.

Android GoogleMaps API v2 auth error, i do not get the error when running on an AVD but on my nexus 7 i get an auth error

I am developing an Android application which uses Google maps for android v2. The problem i having is that when i run it using the AVD in Eclipse i recieve no authentication error in the log cat output.
I am now testing my application on an Android tablet (nexus 7 2013) and i recieve this error when executing the application:
12-12 01:09:13.968: E/Google Maps Android API(14759): Authorization failure. Please see https://developers.google.com/maps/documentation/android/start for how to correctly set up the map.
12-12 01:09:13.968: E/Google Maps Android API(14759): Ensure that the following correspond to what is in the API Console: Package Name: dcs.aber.ac.uk.cs211.group02, API Key: AIzaSyDcnzt6cdjEbCXSCRSTezmUHbaPW679if8, Certificate Fingerprint: 52FDB9ABBBAA062226834E35BF6A39FA2A3E27A7
I have tried to regen the API key, the one in the logcat matches the one provided in the google API console.
I have tried a clean project/clean install on the device several times, still no luck. The reast of the application works fine, only the map does not.
Here is my manifest.xml al the permissions seem ok.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dcs.aber.ac.uk.cs211.group02"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<permission
android:name="dcs.aber.ac.uk.cs211.group02.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<!-- Accessing camera hardware -->
<!-- putting android.hardware.camera prevents non-camera devices using this app -->
<uses-feature android:name="android.hardware.camera" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="dcs.aber.ac.uk.cs211.group02.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:logo="#drawable/ic_launcher"
android:theme="#style/AppTheme" >
<uses-library
android:name="com.google.android.maps"
android:required="true" />
<activity
android:name="dcs.aber.ac.uk.cs211.group02.StartScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="dcs.aber.ac.uk.cs211.group02.CreateWalkActivity"
android:label="#string/title_activity_create_walk" >
</activity>
<activity
android:name="dcs.aber.ac.uk.cs211.group02.HelpScreen"
android:label="#string/title_activity_help_screen" >
</activity>
<activity
android:name="dcs.aber.ac.uk.cs211.group02.WalkRecording"
android:label="#string/title_activity_walk_recording" >
</activity>
<activity
android:name="dcs.aber.ac.uk.cs211.group02.CreateNewPOIActivity"
android:label="#string/title_activity_create_new_poi" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDcnzt6cdjEbCXSCRSTezmUHbaPW679if8" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="dcs.aber.ac.uk.cs211.group02.ConfrimUploadActivity"
android:label="#string/title_activity_confrim_upload" >
</activity>
<activity
android:name="dcs.aber.ac.uk.cs211.group02.ServerResponse"
android:label="#string/title_activity_server_response" >
</activity>
</application>
</manifest>
This is the xml where the map is located:
<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:background="#color/black"
tools:context=".WalkRecording" >
<fragment
android:id="#+id/mapView"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="400dp" />
<ImageButton
android:id="#+id/walkRecordingHelpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="16dp"
android:background="#color/transparent"
android:contentDescription="#string/helpIconAltText"
android:src="#drawable/help" />
<Button
android:id="#+id/walkRecordingNewPOIButton"
style="#android:style/TextAppearance.Small"
android:layout_width="85dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_below="#+id/mapView"
android:layout_marginBottom="8dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="8dp"
android:text="#string/walkRecordingNewPOIButtonText"
android:textColor="#color/light_gray" />
<Button
android:id="#+id/walkRecordingUploadButton"
style="#android:style/TextAppearance.Small"
android:layout_width="85dp"
android:layout_height="50dp"
android:layout_alignBaseline="#+id/walkRecordingNewPOIButton"
android:layout_alignBottom="#+id/walkRecordingNewPOIButton"
android:layout_alignParentRight="true"
android:layout_marginBottom="8dp"
android:layout_marginRight="15dp"
android:layout_marginTop="8dp"
android:text="#string/walkRecordingUploadButtonText"
android:textColor="#color/light_gray" />
</RelativeLayout>
And the code:
package dcs.aber.ac.uk.cs211.group02;
import java.util.Vector;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.maps.GeoPoint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class WalkRecording extends FragmentActivity {
private static String walkName, walkSDesc, walkLdesc;
private GoogleMap map;
private Context context;
private Button newPOIButton, uploadButton;
private ImageButton helpButton;
private static Vector<PointOfInterest> pois = new Vector<PointOfInterest>();
private CreateNewPOIActivity POIAct;
private final static int NEW_POI_REQ = 0;
private final static int EDIT_WALK_DETAILS = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walk_recording);
context = this;
Bundle bundle = getIntent().getBundleExtra("Walk info");
if(bundle != null){
walkName = bundle.getString("walkTitle");
walkSDesc = bundle.getString("walkSdesc");
walkLdesc = bundle.getString("walkLDesc");
}
map=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapView)).getMap();
map.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(52.4140,4.0810) , 14.0f));
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
POIAct = new CreateNewPOIActivity();
addOnClickListeners();
}
public void addOnClickListeners(){
helpButton = (ImageButton) findViewById(R.id.walkRecordingHelpButton);
helpButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, HelpScreen.class);
startActivity(intent);
}
});
newPOIButton = (Button) findViewById(R.id.walkRecordingNewPOIButton);
newPOIButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CreateNewPOIActivity.class);
startActivityForResult(intent, NEW_POI_REQ);
}
});
uploadButton = (Button) findViewById(R.id.walkRecordingUploadButton);
uploadButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
Intent intent = new Intent(context, ConfrimUploadActivity.class);
Bundle b = new Bundle();
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.walk_recording, menu);
return true;
}
public void uploadTosever() {
}
public void deleteWalk() {
}
public double getLongitude() {
return 0;
}
public double getLattitude() {
return 0;
}
public static Vector<PointOfInterest> getPois() {
return pois;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == NEW_POI_REQ){
if( resultCode == RESULT_OK ) {
PointOfInterest p = data.getExtras().getParcelable("POIObject");
Toast lol = Toast.makeText(context, p.getName(), Toast.LENGTH_LONG);
lol.show();
pois.add(p);
Toast x = Toast.makeText(context, "POIS SIZE " + pois.size() , Toast.LENGTH_LONG);
x.show();
}
}
else if(requestCode == EDIT_WALK_DETAILS){
if( resultCode == RESULT_OK ) {
}
}
}
public static String getWalkName() {
return walkName;
}
public static void setWalkName(String walkName) {
WalkRecording.walkName = walkName;
}
public static String getWalkSDesc() {
return walkSDesc;
}
public static void setWalkSDesc(String walkSDesc) {
WalkRecording.walkSDesc = walkSDesc;
}
public static String getWalkLdesc() {
return walkLdesc;
}
public static void setWalkLdesc(String walkLdesc) {
WalkRecording.walkLdesc = walkLdesc;
}
}
Any ideas?
Resolved. alls it took was a device reset...

Categories