How to get a RSSI of bluetooth - android

I am trying to get the RSSI of the bluetooth connection. First i thought to display the RSSI of all nearby devices, so i checked the internet - got some information of the bluetooth classes and checked some examples. I tried a lot of thing, but with no success. I am at stage that I cant understand where exactly is the problem.
The target SDK is 29 and min SDK is 19. I am testing it on Android 10 (SDK 29)
MainActivity.java
package com.example.myapplication;
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.graphics.BlendMode;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
BluetoothAdapter BA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
BA = BluetoothAdapter.getDefaultAdapter();
BA.startDiscovery();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private final BroadcastReceiver receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
TextView rssi_msg = (TextView) findViewById(R.id.textView1);
rssi_msg.setText(rssi_msg.getText() + "" + rssi + "dBm\n");
}
}
};
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<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:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Main2Activity"></activity>
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings"
android:parentActivityName=".MainActivity" />
<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>

I found a "work around answer" but still can't do it properly. So the things that helped me and now it is working are: I made the targetSdkVersion to 26 (it was 29 before), minSdkVersion is still 19 (like before) and compileSdkVersion is still 29 (like before). This was in the gradle. And after I changed the target SDK I added this in my onCreate() method on the MainActivity
if (ActivityCompat.checkSelfPermission((Activity)this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity)this, new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
}, 10);
}
and now it is working on android 10, but I still can't do it for target SDK 29

Related

Reading Array/Payload on NFC Tag?

I've edited my Manifest code and my Activity code again to reflect appropriate intent filter requirements. However, I'm still getting the same results. I'm unable to read my external record, and I don't know why? When I scan my tags with the NFC Tools app, I can see everything as I would expect. My code produces a NullPointer when it attempts to "read" my array and I have no idea why?
--------------BEGIN MANIFEST--------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bmt_01">
<uses-permission android:name="android.permission.NFC"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-sdk android:minSdkVersion="15"/> ///must be changed in build.gradle.
<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>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data
android:scheme="vnd.android.nfc"
android:host="ext"
android:pathPrefix="/com.example.bmt_01:externaltype"
/>
</intent-filter>
</activity>
</application>
</manifest>
--------------END MANIFEST--------------------
--------------BEGIN MAIN ACTIVITY-------------
package com.example.bmt_01;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
String currentPayload = "";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onNewIntent(Intent intent)
{
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
//added the below lines, can delete if they don't work.
NdefRecord payload = ((NdefMessage)rawMsgs[0]).getRecords()[0];
String currentPayload = new String(payload.getPayload());
if (currentPayload.equals("1"))
{
Toast.makeText(this, "NFC Scan1: " + currentPayload, Toast.LENGTH_SHORT).show();
String url = "http://www.google.com";
Intent l = new Intent(Intent.ACTION_VIEW);
l.setData(Uri.parse(url));
startActivity(l);
}
///else
///{
if (currentPayload.equals("2"))
{
Toast.makeText(this, "NFC Scan2: " + currentPayload, Toast.LENGTH_SHORT).show();
String url = "http://www.yahoo.com";
Intent l = new Intent(Intent.ACTION_VIEW);
l.setData(Uri.parse(url));
startActivity(l);
}
///}
}
protected void onResume()
{
super.onResume();
Toast.makeText(this, "NFC Scan3: ", Toast.LENGTH_SHORT).show();
enableForegroundDispatchSystem();
}
#Override
protected void onPause()
{
super.onPause();
disableForegroundDispatchSystem();
}
private void enableForegroundDispatchSystem() {
Toast.makeText(this, "NFC Scan4: ", Toast.LENGTH_SHORT).show();
}
private void disableForegroundDispatchSystem() {
Toast.makeText(this, "NFC Scan5: ", Toast.LENGTH_SHORT).show();
onNewIntent(getIntent());
}
}
--------------END MAIN ACTIVITY---------------
UPDATE*
I should add that my AAR functions correctly. When I have the above app installed on my phone, but do not have it open, my AAR automatically opens and launches the application when I scan my test tag. So, I'm able to "see" the AAR in the array, but NOT the external record.
I'm still unable to read the external record on my tag. Obviously I'm doing something wrong, but I have no idea.
You mix togerthe message and record in your for loop. However there is only one NDEF message, but this message can hold several records. You must use only rawMsgs[0]. Then your for loop can iterate over all records of that message.
I've created a library which lets you parse NDEF records.
You're on the right track - wrapping binary paylod with using the external type - the library supports plugging in your own external type parser/record type(s), if you so prefer.

Getting the data of near wifi networks ( error in the code)

I'm trying to have an application that gets the specifications of near wifi networks to combine it with another application but I have an error in the AndroidManifest.xml file that I do not know how to fix. The error is in the line android:label="#string/title_activity_list_wifi" shown below. Regards
// AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wifi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.wifi.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.wifi.ListWifiActivity"
android:label="#string/title_activity_list_wifi">
</activity>
</application>
</manifest>
// src/com.example.wifi/MainActivity.java
package com.example.wifi;
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.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
WifiManager mainWifiObj;
WifiScanReceiver wifiReciever;
ListView list;
String wifis[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listView1);
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WifiScanReceiver();
mainWifiObj.startScan();
}
protected void onPause() {
unregisterReceiver(wifiReciever);
super.onPause();
}
protected void onResume() {
registerReceiver(wifiReciever, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
class WifiScanReceiver extends BroadcastReceiver {
#SuppressLint("UseValueOf")
public void onReceive(Context c, Intent intent) {
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
wifis = new String[wifiScanList.size()];
for(int i = 0; i < wifiScanList.size(); i++){
wifis[i] = ((wifiScanList.get(i)).toString());
}
list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1,wifis));
}
}
}
android:label="#string/title_activity_list_wifi" Is referring to the string title_activity_list_wifi in your strings.xml file (more about string resources: http://developer.android.com/guide/topics/resources/string-resource.html), which apparently doesn't exist.
There are 2 things you can do to solve this:
-Use a hardcoded string instead of a reference:
android:label="This activity has a list of wifi networks"
-Add the string to the strings.xml file (res/values):
<string name="title_activity_list_wifi">This activity has a list of wifi networks</string>

Apache Commons Net Lib and min-/targetsdkversion

I am making my first Android App, but my code produces a very strange behaviour i can't understand. And i used Google for three days now with no solution.
If i write in my AndroidManifest.xml a minSdkVersion other than "8", i can't connect to my FTP Server. Also if i use minSdkVersion "8" and targetSdkVersion other than "8". If i don't use minSdkVersion and targetSdkVersion everything works fine. In short:
min 8, target 8 = ok
min 8, no target = ok
no min, no target = ok
min 8, target 17 = failure
min 10, target 10 = failure
and so on...
Here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.package"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.package.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.examplepackage.Settings"></activity>
<activity android:name="com.schmidgroup.sgfax.Tools"></activity>
<activity android:name="com.schmidgroup.sgfax.MyFTP"></activity>
<activity android:name="com.schmidgroup.sgfax.Printing"></activity>
<activity android:name="com.schmidgroup.sgfax.Listings"></activity>
<activity android:name="com.schmidgroup.sgfax.Blue"></activity>
</application>
</manifest>
My MainActivity.Java:
package com.example.package;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Button for Bluetooth-Connection
Button verbinden = (Button) findViewById(R.id.button1);
verbinden.setText(R.string.select_device);
verbinden.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent start = new Intent(getApplicationContext(), Blue.class);
startActivity(start);
}
} );
}
}
My class Blue.Java does some Bluetooth stuff and then starts Listings.Java:
package com.example.package;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
public class Listings extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listings);
// Connect zum FTP-Server
MyFTP conn = new MyFTP();
conn.ftpConnect(host, user, pass, 21);
[... some more FTP stuff which don't work in cause of failing Ftp Connection...]
}
}
And finally the MyFTP.Java:
package com.example.package;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.*;
import android.content.Context;
import android.util.Log;
public class MyFTP {
private static void showServerReply(FTPClient FTPClient) {
String[] replies = FTPClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
//Now, declare a public FTP client object.
private static final String TAG = "MyFTPClient";
public FTPClient mFTPClient = null;
//Method to connect to FTP server:
public boolean ftpConnect(String host, String username,
String password, int port)
{
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
showServerReply(mFTPClient);
Log.i(TAG, "Successful conntected to " + host);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
Log.i(TAG, "Succesful logged in to " + host);
/* Set File Transfer Mode
*
* To avoid corruption issue you must specified a correct
* transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
* EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE
* for transferring text, image, and compressed files.
*/
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
[...and some more stuff...]
Can anyone see what i've doing wrong?
Thank you!
You shouldn't make any network operations on your main UI thread. watch this question about StrictMode Policy in Android 3.0 and higher.

Android vibrator app force close

my app force closes I do not know why. All it should do is vibrating when it is in the foreground and stop if it is not but when I start it on my phone it force closes. I added lines about vibrator usage into the manifest by hand. Maybe this is the problem. I have to anything else with it to be valid for the app?
My manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kevinboonemidi"
android:versionCode="1"
android:versionName="1.0" >
<permission android:name="android.permission.VIBRATE" ></permission>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.haptic.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My code:
package com.example.haptic_sof;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.example.kevinboonemidi.R;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
public class MainActivity extends Activity
{
protected Vibrator v = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long pwmCycles[];
pwmCycles = new long[4];
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = { 0, 200, 10 };
v.vibrate(pattern, 0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected void onPause(){
super.onPause();
v.cancel();
}
protected void onStop()
{
super.onStop();
v.cancel();
}
}
Your packages are a mess.
You define com.example.kevinboonemidi as your package in the manifest, declare your Activity to be in com.example.haptic and actually put your Activity in com.example.haptic_sof.
Change android:name="com.example.haptic.MainActivity" to android:name="com.example.haptic_sof.MainActivity" and your app should run, though you may need to end up using one package entirely at least to start with.

to get cdma dbm on android device

I had tried this one to show my evdo dbm.
it could run on my emulator but couldnt on my real device, why?
is there somethinh wrong ?
this my source code :
package com.cdbmsof2;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class CdBmSOF2MainActivity extends Activity implements OnClickListener {
TextView dateAndTimeLabel;
private Button closeButton;
private int signalDBM = 0;
public class GetParams extends PhoneStateListener
{
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength)
{
super.onSignalStrengthsChanged(signalStrength);
signalDBM = signalStrength.getEvdoDbm();
}
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_cd_bm_sof2_main);
GetParams listener = new GetParams();
TelephonyManager TelManager = ( TelephonyManager )getSystemService(Context.TELEPHONY_SERVICE);
TelManager.listen(listener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
Button btn=(Button)findViewById(R.id.start);
btn.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
Toast.makeText(this, "CDMA signal strength is " + this.signalDBM , Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_cd_bm_sof2_main, menu);
return true;
}
}
this my manifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cdbmsof2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".CdBmSOF2MainActivity"
android:label="#string/title_activity_cd_bm_sof2_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
</manifest>
any one would help me please? best regards.
You may want to change the MODIFY permission into a READ permission as you're not modifying phone state, but trying to read it:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
I tried your code but the value of the signalDBM will not change. It will stay the same even if there is no internet connection at all. I am trying to do something similar and your code was of good help for me but now I face that problem. Does that program changes the values for you? Please let me know..

Categories

Resources