Why android hides bluetooth mac address? - java

i'm trying to get bluetooth mac address in this way:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String address = mBluetoothAdapter.getAddress();
But it always returns:
02:00:00:00:00:00
Why? Is it a kind of security policy?
Thanks.
Giacomo

Maybe you should check out this answer.
Snippet from answer:
private String getBluetoothMac(final Context context) {
String result = null;
if (context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH)
== PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Hardware ID are restricted in Android 6+
// https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-hardware-id
// Getting bluetooth mac via reflection for devices with Android 6+
result = android.provider.Settings.Secure.getString(context.getContentResolver(),
"bluetooth_address");
} else {
BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
result = bta != null ? bta.getAddress() : "";
}
}
return result;
}

Related

How to check if the device is connected to internet and Connection type in Harmony Os

I was trying to check if the device is connected to internet and what is the network type. Here is an example of how we check it in android
public boolean isConnectingToInternet(Activity act){
boolean isthere = false;
TelephonyManager tm = (TelephonyManager) act.getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() != TelephonyManager.SIM_STATE_UNKNOWN){
ConnectivityManager connectivityManager = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED))
isthere = true;
} else {
ConnectivityManager connectivityManager = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED))
isthere = true;
}
return isthere;
}
Add permission ohos.permission.GET_NETWORK_INFO, which is used to obtain network information. Add permission ohos.permission.INTERNET, which is used to access the network.
• Check if network is connected
public static boolean hasInternetConnection(Context context) {
NetManager netManager = NetManager.getInstance(context);
NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED);
}
• Check if WiFi is connected
public static boolean isWifiConnectedInternet(Context context) {
NetManager netManager = NetManager.getInstance(context);
NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED) &&
netCapabilities.hasBearer(NetCapabilities.BEARER_WIFI) ||
netCapabilities.hasBearer(NetCapabilities.BEARER_WIFI_AWARE);
}
• Check if Mobile network is connected
public static boolean isMobileConnectedInternet(Context context) {
NetManager netManager = NetManager.getInstance(context);
NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED) &&
netCapabilities.hasBearer(NetCapabilities.BEARER_CELLULAR);
}
You could refer to this Docs to check the status of the connection to the Internet.
And the TelephonyConstants.NETWORK_TYPE_LTE can determine the network type.
// Obtain the RadioInfoManager object.
RadioInfoManager radioInfoManager = RadioInfoManager.getInstance(context);
// Obtain the signal information.
List<SignalInformation> signalList = radioInfoManager.getSignalInfoList(slotId);
// Check the size of the signal information list.
if (signalList.size() == 0) {
return;
}
// Traverse the signal information list to obtain the signal information of the current network type.
LteSignalInformation lteSignal = null;
for (SignalInformation signal : signalList) {
int signalNetworkType = signal.getNetworkType();
if (signalNetworkType == TelephonyConstants.NETWORK_TYPE_LTE) {
lteSignal = (LteSignalInformation) signal;
}
}
// Obtain the signal strength of the specified RAT (methods in the child class).
int signalLevel = lteSignal != null ? lteSignal.getSignalLevel() : 0;

Connecting to a Hidden Wi-Fi network in Android programmatically?

I am creating an Android application which should connect to a known available Hidden Wi-Fi network.
Which is the proper approach to handle this scenario ?
I have implemented trying to connect to a hidden wifi network. I tried on android devices with OS versions 6.0, 7.0, 7.1.1, 8.0 But couldn't achieve success.
fun initiateWifiConnectivity(mContext: Context, sSID: String, password: String) {
mWifiManager = mContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
if (!mWifiManager!!.isWifiEnabled) {
mWifiManager!!.isWifiEnabled = true
}
mWifiConfiguration = WifiConfiguration()
mWifiConfiguration!!.SSID = convertToQuotedString(sSID)
mWifiConfiguration!!.preSharedKey = password
mWifiConfiguration!!.status = WifiConfiguration.Status.ENABLED
mWifiConfiguration!!.hiddenSSID = true
mWifiConfiguration!!.allowedAuthAlgorithms.
set(WifiConfiguration.AuthAlgorithm.LEAP)
mWifiConfiguration!!.allowedGroupCiphers.
set(WifiConfiguration.GroupCipher.TKIP)
mWifiConfiguration!!.allowedGroupCiphers.
set(WifiConfiguration.GroupCipher.CCMP)
mWifiConfiguration!!.allowedGroupCiphers.
set(WifiConfiguration.GroupCipher.WEP40)
mWifiConfiguration!!.allowedKeyManagement.
set(WifiConfiguration.KeyMgmt.WPA_PSK)
mWifiConfiguration!!.allowedKeyManagement.
set(WifiConfiguration.KeyMgmt.WPA_EAP)
mWifiConfiguration!!.allowedKeyManagement.
set(WifiConfiguration.KeyMgmt.IEEE8021X)
mWifiConfiguration!!.allowedPairwiseCiphers.
set(WifiConfiguration.PairwiseCipher.TKIP)
mWifiConfiguration!!.allowedPairwiseCiphers.
set(WifiConfiguration.PairwiseCipher.CCMP)
mWifiConfiguration!!.allowedPairwiseCiphers.
set(WifiConfiguration.PairwiseCipher.NONE)
mWifiConfiguration!!.allowedProtocols.
set(WifiConfiguration.Protocol.RSN)
mWifiConfiguration!!.allowedProtocols.
set(WifiConfiguration.Protocol.WPA)
mWifiManager!!.addNetwork(mWifiConfiguration!!)
Handler().postDelayed(Runnable {
val list = mWifiManager!!.configuredNetworks
for (i in list) {
if (i.SSID != null && i.SSID ==
convertToQuotedString(sSID)) {
mWifiManager!!.disconnect()
mWifiManager!!.enableNetwork(i.networkId, true)
mWifiManager!!.reconnect()
break
}
}
}, 15000)
}
I connected a hidden WIFI network in Android Studio with a divice Android 7.0. Put the conf.hiddenSSID = true; of the object WifiConfiguration, the configuration to connect a network is similar to a notable network.
public class ShowActivity extends AppCompatActivity {
private WifiManager wifiManager; // Here is defined the instance
WifiConfiguration conf = new WifiConfiguration();
Log.d("Aut", Net + " : " + Pw);
conf.SSID = "\"" + Net + "\"";
conf.preSharedKey = "\"" + Pw + "\"";
conf.hiddenSSID = true; // Put this line to hidden SSID
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
// Connect Network
this.wifiManager =(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
assert wifiManager != null;
int netId = this.wifiManager.addNetwork(conf);
WifiInfo wifi_inf = this.wifiManager.getConnectionInfo();
this.wifiManager.disableNetwork(wifi_inf.getNetworkId());
this.wifiManager.enableNetwork(netId, true);
this.wifiManager.reconnect();
}

How to perform 5 bytes data receive via Bluetooth with Android app on Android device?

I need to receive 5 bytes frame via Bluetooth on Android device. I have no problem with sending the data frame, but i don't know how to receive this properly. I don't need to receive string, only byte values.
Does anyone have code for something like that?
I'm programming in Android Studio 2.2.3
You have to enable notification / indication respected to the characteristics.
After you write the command. You will get callbacks from GATT as bytes.
1) Scan Devices
2) Connect with devices
device.connectGatt(mContext, autoConnect,BluetoothGattCallback, BluetoothDevice.TRANSPORT_LE);
BluetoothGattCallback - Callback
In this callback you have multiple inherited methods. For your purpose use this
Inherit this method , to get a bytes from your peripheral.
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
throw new RuntimeException("Stub!");
}
3) You have to enable the Indication/Notification according to your peripheral requirement.
// For enable Indication - And give your parameter as your charactertics.
private static final UUID CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
public final boolean enableIndications(final BluetoothGattCharacteristic characteristic) {
Log.d("CheckData", "enableIndications");
final BluetoothGatt gatt = mBluetoothGatt;
if (gatt == null || characteristic == null)
return false;
// Check characteristic property
final int properties = characteristic.getProperties();
if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) == 0)
return false;
gatt.setCharacteristicNotification(characteristic, true);
final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
return gatt.writeDescriptor(descriptor);
}
return false;
}
// For enable Notifciation - And give your parameter as your charactertics.
protected final boolean enableNotifications(final BluetoothGattCharacteristic characteristic, boolean enable) {
final BluetoothGatt gatt = mBluetoothGatt;
if (gatt == null || characteristic == null)
return false;
// Check characteristic property
final int properties = characteristic.getProperties();
if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) == 0)
return false;
gatt.setCharacteristicNotification(characteristic, enable);
final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
return gatt.writeDescriptor(descriptor);
}
return false;
}
4) Write values to your respected characteristics.
5) Response will come to your registered callbacks BluetoothGattCallback
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
characteristic.getStringValue(1) // Output Bytes
characteristic.getValue() // Output as Byte Array
Log.d("Values", characteristic.getStringValue(1));
}
characteristic.getStringValue(1) // Output Bytes as string from particular offset
characteristic.getValue() // Output as Byte Array
Hope this answer will help you.
Cheers Up Vote Up
Happy Coding
you can find tutorials on how to set up a bluetooth connection in the offical doc.
https://developer.android.com/guide/topics/connectivity/bluetooth.html

Application crash with android 2.3

I use this code to turn off the wifi connection and data connection
public static class LowBatteryReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent){
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
wifi = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
try {
ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class<?> conmanClass = Class.forName(conman.getClass().getName());
Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
Object iConnectivityManager = iConnectivityManagerField.get(conman);
Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The class will be called in a method to work but this is not important.. I have a nexus 4 with android 4.3 and the code works. Also in android 4.0.3/4, 4.1, 4.1.2, 4.2.1 and .4.2.2.. I use an ActionbarSherlock library so i can use an holo.light anctionbar also with previews android versions. A friend of mine with android 2.3.6 tryied the application and tells me has a crash.. I can't see any logcat for now but i think the problem is the code above. I know that with android 2.3 there was another way to turn the 3g off but i don't know which. How can i detect the android version and make something like : If android >= 4 use the code i posted and if android <=4 use another code (if someone can tell me which is is better thanks).
EDIT:
I found a code for data with android 2.3.. Have i to do something like
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
Method dataConnSwitchmethod;
Class telephonyManagerClass;
Object ITelephonyStub;
Class ITelephonyClass;
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED){
isEnabled = true;
}else{
isEnabled = false;
}
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());
if (isEnabled) {
dataConnSwitchmethod = ITelephonyClass
.getDeclaredMethod("disableDataConnectivity");
} else {
dataConnSwitchmethod = ITelephonyClass
.getDeclaredMethod("enableDataConnectivity");
}
dataConnSwitchmethod.setAccessible(true);
dataConnSwitchmethod.invoke(ITelephonyStub);
}
so if the version is >= gingerbread this will be the code right?
Example how to use it:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
// only for gingerbread and newer versions
}
Also you can check as below for the version 4>= or <=4 android.
if(Build.VERSION.SDK_INT >= 4.0){
//this code will be executed on devices running on DONUT (NOT ICS) or later
}
since constant 4 represents donut: public static final int DONUT = 4;
You can find out the Android version looking at Build.VERSION.

Send MMS from My application in android

I want to send MMS from my application to a specific number. I've searched and found this code but I have no idea if this code what I need or not.
My Questions is :
-can anyone explain this code to me.i am beginner in MMS.
-also, i thought this code is let the user send MMS from my application without move it to the native Messaging inbox (and this is what i want) Am i right?
-also i have a problem ,i do not know how can i put this code in my project.
this is what i found
MMS is just a http-post request. You should perform the request using extra network feature :
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final int result = connMgr.startUsingNetworkFeature( ConnectivityManager.TYPE_MOBILE, Phone.FEATURE_ENABLE_MMS);
If you get back the result with Phone.APN_REQUEST_STARTED value, you have to wait for proper state. Register BroadCastReciver and wait until Phone.APN_ALREADY_ACTIVE appears:
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(reciver, filter);
If background connection is ready, then build content and perform request. If you want to do that using android's internal code, please use this:
final SendReq sendRequest = new SendReq();
final EncodedStringValue[] sub = EncodedStringValue.extract(subject);
if (sub != null && sub.length > 0) {
sendRequest.setSubject(sub[0]);
}
final EncodedStringValue[] phoneNumbers = EncodedStringValue.extract(recipient);
if (phoneNumbers != null && phoneNumbers.length > 0) {
sendRequest.addTo(phoneNumbers[0]);
}
final PduBody pduBody = new PduBody();
if (parts != null) {
for (MMSPart part : parts) {
final PduPart partPdu = new PduPart();
partPdu.setName(part.Name.getBytes());
partPdu.setContentType(part.MimeType.getBytes());
partPdu.setData(part.Data);
pduBody.addPart(partPdu);
}
}
sendRequest.setBody(pduBody);
final PduComposer composer = new PduComposer(this.context, sendRequest);
final byte[] bytesToSend = composer.make();
HttpUtils.httpConnection(context, 4444L, MMSCenterUrl, bytesToSendFromPDU, HttpUtils.HTTP_POST_METHOD, !TextUtils.isEmpty(MMSProxy), MMSProxy, port);
MMSCenterUrl: url from MMS-APNs,
MMSProxy: proxy from MMS-APNs,
port: port from MMS-APNs
Note that some classes are from internal packages. Download from android git is required.
The request should be done with url from user's apn-space code:
public class APNHelper {
public class APN {
public String MMSCenterUrl = "";
public String MMSPort = "";
public String MMSProxy = "";
}
public APNHelper(final Context context) {
this.context = context;
}
public List<APN> getMMSApns() {
final Cursor apnCursor = this.context.getContentResolver().query(Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"), null, null, null, null);
if ( apnCursor == null ) {
return Collections.EMPTY_LIST;
} else {
final List<APN> results = new ArrayList<APN>();
while ( apnCursor.moveToNext() ) {
final String type = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.TYPE));
if ( !TextUtils.isEmpty(type) && ( type.equalsIgnoreCase(Phone.APN_TYPE_ALL) || type.equalsIgnoreCase(Phone.APN_TYPE_MMS) ) ) {
final String mmsc = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSC));
final String mmsProxy = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSPROXY));
final String port = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSPORT));
final APN apn = new APN();
apn.MMSCenterUrl = mmsc;
apn.MMSProxy = mmsProxy;
apn.MMSPort = port;
results.add(apn);
}
}
apnCursor.close();
return results;
}
Please help me
why don't you use the android system functions:
Please have a look on
https://developer.android.com/guide/components/intents-common.html
public void composeMmsMessage(String message, Uri attachment) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("smsto:")); // This ensures only SMS apps respond
intent.putExtra("sms_body", message);
intent.putExtra(Intent.EXTRA_STREAM, attachment);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent); }
}
Cheers
Tom
I found a link in an other thread to a github project that works 100% https://github.com/klinker41/android-smsmms
Notice, that obligatory settings are only
Settings sendSettings = new Settings();
sendSettings.setMmsc(mmsc);
sendSettings.setProxy(proxy);
sendSettings.setPort(port);
you can get them something like (found at Set APN programmatically on Android - answear by vincent091):
Cursor cursor = null;
if (Utils.hasICS()){
cursor =SqliteWrapper.query(activity, activity.getContentResolver(),
Uri.withAppendedPath(Carriers.CONTENT_URI, "current"), APN_PROJECTION, null, null, null);
} else {
cursor = activity.getContentResolver().query(Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"),
null, null, null, null);
}
cursor.moveToLast();
String type = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.TYPE));
String mmsc = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.MMSC));
String proxy = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.MMSPROXY));
String port = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.MMSPORT));

Categories