the application i'm currently working on is mobile network dependant,
so my question is, is it possible to get the current mobile network which being used on the device (e.g. 3 UK, T-Mobile)?
also, is there anyway of getting the user's mobile number?
thanks for any help (:
Phone Number:
final TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
final String phoneNumber = tm.getLine1Number();
Network Type:
// Check each connection type
boolean connectionAvailable = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
/**
* WIFI
*/
/** Check the connection **/
NetworkInfo network = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
// Make sure the network is available
if(network != null && network.isAvailable() && network.isConnectedOrConnecting()) {
connectionAvailable = true;
}
/**
* 2G/3G
*/
/** Check the connection **/
network = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// Show the right icon
if(network != null &&
(network.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS ||
network.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE)) {
// 2G
}
else {
// 3G
}
// Make sure the network is available
if(network.isAvailable() && network.isConnectedOrConnecting()) {
connectionAvailable = true;
}
/**
* 4G
*/
/** Check the connection **/
network = cm.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);
// Make sure the network is available
if(network != null && network.isAvailable() && network.isConnectedOrConnecting()) {
connectionAvailable = true;
}
Everything you are looking for is in the TelephonyManager. Example usage:
final TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
final String phoneNumber = tm.getLine1Number();
if (this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String msisdn = telephonyManager.getLine1Number();
String carrier = telephonyManager.getNetworkOperatorName();
}
Related
This is my code below:
#SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
When I run the above code, I am getting a Deprecated warning saying that getActiveNetworkInfo and isConnected methods are deprecated.
I don't want to continue this code for any longer. What are some of the alternatives of the above code?
Can someone please help me? Thanks in Advance
Below is my code which I use in my application to check if device is connected to network. It does not contain any deprecated code as of now.
Kotlin
private fun isInternetAvailable(): Boolean {
var result = false
val connectivityManager = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
connectivityManager?.let {
it.getNetworkCapabilities(connectivityManager.activeNetwork)?.apply {
result = when {
hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
else -> false
}
}
}
return result
}
Java
public static boolean isInternetAvailable(Context context) {
boolean result = false;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (networkCapabilities != null) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = true;
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = true;
} else {
result = false;
}
}
}
return result;
}
Read more about Connectivity Manager and Network Capabilities here.
I'm building an app in android studio to read barcodes and store them into SQL Database. But I want the device to read only certain barcodes and return a false Toast message if the wrong barcode is read. The device I'm using is Symbol TC70. Basically the barcodes that I want the app to read are the SSCC barcodes and if they start with "K02" that would be the wrong barcode, the one that needs to be read starts with "K00" and has 18 digits. I've tried multiple code lines with no success. This is the main code that i started with.
private String getSerialnumber() {
String serialNumber;
serialNumber = "";
if (Build.VERSION.SDK_INT >= 26) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
serialNumber = android.os.Build.getSerial();
} else {
serialNumber = "Unknown barcode!";
}
} else {
serialNumber = android.os.Build.SERIAL;
}
return serialNumber;
}
did you try check the return serial number as string like these?
private String getSerialnumber() {
String serialNumber;
serialNumber = "";
if (Build.VERSION.SDK_INT >= 26) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
serialNumber = android.os.Build.getSerial();
if(!serialNumber.substring(0,4).quals('SSCC'))
serialNumber = "wrong barcode";
} else {
serialNumber = "Unknown barcode!";
}
} else {
serialNumber = android.os.Build.SERIAL;
}
return serialNumber;
}
I'm trying to get the renamed bluetooth device using this:
#Override
public void onDeviceDiscovered(BluetoothDevice device, int rssi) {
device.getName();
}
But the problem is that i'm getting the wrong name or let say the device manufacturer name
Look at this :
/**
* Get the friendly Bluetooth name of the remote device.
*
* <p>The local adapter will automatically retrieve remote names when
* performing a device scan, and will cache them. This method just returns
* the name for this device from the cache.
*
* #return the Bluetooth name, or null if there was a problem.
*/
#RequiresPermission(Manifest.permission.BLUETOOTH)
public String getName() {
final IBluetooth service = sService;
if (service == null) {
Log.e(TAG, "BT not enabled. Cannot get Remote Device name");
return null;
}
try {
String name = service.getRemoteName(this);
if (name != null) {
return name.replaceAll("[\\t\\n\\r]+", " ");
}
return null;
} catch (RemoteException e) {
Log.e(TAG, "", e);
}
return null;
}
My question is how to return only the Bluetooth name and nothing else please help.
need your help again :
I want to establish a connection to a obd2-bluetooth-adapter. For that reason i had a look at the BluetoothChat-Example from the AndroidSDK. I am able to establish a connection to my computer, but i am not able to pair my android tablet with my odb2-bluetooth-adapter (elm327). Found some hints, for instance :
myRemoteBluetoothDevice.setPassKey(....);
First, i can not use the function on 'myRemoteBluetoothDevice' - and then i don't know where to use this function. Within the connect-Thread ?
public synchronized void connect(BluetoothDevice device, boolean secure) {
if (D) Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
setState(STATE_CONNECTING);
}
I think a possible solution would be to implement a event-listener or something like this, which is called when the remote device needs a passcode ? But where i have to implement it ? And where i have to use it ?
Can somebody help me out there ?
Thanks in advance !!!
PS : My App is based on the following example :
https://android.googlesource.com/platform/development/+/25b6aed7b2e01ce7bdc0dfa1a79eaf009ad178fe/samples/BluetoothChat/src/com/example/android/BluetoothChat/BluetoothChatService.java
Greetings.
EDIT :
Tried to implement the first answer :
My BroadcastReceiver :
private final BroadcastReceiver mReceiverRequiresPin = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
try {
BluetoothDevice newDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Class<?> btDeviceInstance = Class.forName(BluetoothDevice.class.getCanonicalName());
Method convert = btDeviceInstance.getMethod("convertPinToBytes", String.class);
byte[] pin = (byte[]) convert.invoke(newDevice, "1234");
Method setPin = btDeviceInstance.getMethod("setPin", byte[].class);
boolean success = (Boolean) setPin.invoke(newDevice, pin);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
And my connect-method, where i register the broadcastReceiver :
private void connect(CordovaArgs args, boolean secure,
CallbackContext callbackContext) throws JSONException {
final String actionPinRequested = "android.bluetooth.device.action.PAIRING_REQUEST";
IntentFilter intentFilterPinRequested = new IntentFilter(actionPinRequested);
cordova.getActivity().registerReceiver(mReceiverRequiresPin, intentFilterPinRequested);
String macAddress = args.getString(0);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(macAddress);
if (device != null) {
connectCallback = callbackContext;
bluetoothSerialService.connect(device, secure);
PluginResult result = new PluginResult(
PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
} else {
callbackContext.error("Could not connect to " + macAddress);
}
}
Would really appreciate your help !
Thanks in advance.
No one has a hint ??
Register a broadcast listener for: android.bluetooth.device.action.PAIRING_REQUEST.
In the onrecieve:
BluetoothDevice newDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Class<?> btDeviceInstance = Class.forName(BluetoothDevice.class.getCanonicalName());
Method convert = btDeviceInstance.getMethod("convertPinToBytes", String.class);
byte[] pin = (byte[]) convert.invoke(newDevice, "1234");
Method setPin = btDeviceInstance.getMethod("setPin", byte[].class);
success = (Boolean) setPin.invoke(newDevice, pin);
I am developing an Android application.
I want my application to notify me whether Android has internet connection or not. How do I check it?
#Carlo: The simplest way is first to add ACCESS_NETWORK_STATE permission to your application manifest file and write a function like this
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
if the return value is true means internet is working or false means show an alert box :)
You need to create a broadcast receiver for android.net.conn.CONNECTIVITY_CHANGE intent in your application.
Here is the documentation http://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION
Hope, it help you!
//this will check for the wifi, 3G/EDGE and all network availability
public boolean networkStatus() {
boolean status = false;
int i = 0;
try {
String service = context.CONNECTIVITY_SERVICE;
ConnectivityManager connectivity = (ConnectivityManager) BackupSettings.this.context.getSystemService(service);
connectivity.setNetworkPreference(1);
NetworkInfo networkInfo[] = connectivity.getAllNetworkInfo();
int cnt = networkInfo.length;
for (i = 0; i < cnt; i++) {
if (networkInfo[i].isConnected() == true) {
status = true;
}
}
} catch (Exception ee) {
Log.e(getClass().getSimpleName(), " Error at networkStatus() :=" + ee.toString());
}
Log.e(getClass().getSimpleName(),"End of networkStatus() fun " + status);
return status;
}