I have made an android app which on startup gets the current wifi network and connects to a different one. At least that is what it is supposed to do:
wifiInfo = wifiManager.getConnectionInfo();
OldNetworkID = wifiInfo.getNetworkId(); //save current network
WDTNetworkID = wifiManager.addNetwork(wificonfiguration); //add new network
wifiManager.disconnect();
wifiManager.enableNetwork(WDTNetworkID, true); //enable new network and disable all others
wifiManager.reconnect();
When I debug I can see wificonfiguration contains the right SSID (the SSID of the new network).
After addNetwork() I see that wifiManager.getConfiguredNetworks() contains this new network with the right SSID and the same networkID as WDTNetworkID. At this point the network is enabled.
But after enableNetwork() instead of WDTNetworkID enabled and the rest disabled I see that OldNetworkID is enabled and the rest is disabled.
Am I doing something wrong?
I have added a picture of a couple of watches while debugging.
You can see here that the old network is enabled and the rest is disabled.
The problem here is that the device the app is running on is android 5.1.1.
As it states in the documentation of enableNetwork():
Note: If an application's target SDK version is LOLLIPOP or newer, network communication may not use Wi-Fi even if Wi-Fi is connected; traffic may instead be sent through another network, such as cellular data, Bluetooth tethering, or Ethernet. For example, traffic will never use a Wi-Fi network that does not provide Internet access (e.g. a wireless printer), if another network that does offer Internet access (e.g. cellular data) is available. Applications that need to ensure that their network traffic uses Wi-Fi should use APIs such as bindSocket(java.net.Socket), openConnection(java.net.URL), or bindProcessToNetwork(Network) to do so.
You just need add this line to your code. i had same problem, adding this line help me.conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
//After sleep a little milliseconds then check exist connection with this code:
try {
Thread.sleep(3000);
Toast.makeText(MyActivity.this, "You are connected to " +
mainWifimanagerObject.getConnectionInfo().getSSID(), Toast.LENGTH_LONG).show();
}
catch (InterruptedException e) {e.printStackTrace();}
Related
Can Always-on VPN switch be on programmatically?
I have added the device admin permission. After that i have set always on in with device admin
mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
mDeviceAdminSample = new ComponentName(this, DeviceAdminReceiver.class);
isAdminApp = mDPM.isAdminActive(mDeviceAdminSample);
if (isAdminApp) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mDPM.setAlwaysOnVpnPackage(mDeviceAdminSample,"", true);
}
} catch (PackageManager.NameNotFoundException namenotfoundexception) {
namenotfoundexception.printStackTrace();
} catch (Exception ex) {
}
}
but it's not enabling the always on.
i have added package name insted of
mDPM.setAlwaysOnVpnPackage(mDeviceAdminSample,"my.app.package.name", true);
but still not enabling the switch.
Then what this code is doing?
How can i enable it programatically?
I want this to be like below image
According to docs, setAlwaysOnVpnPackage can only be used by the profile owner (usually the MDM client on work profile) or device owner (for fully managed devices):
Called by a device or profile owner to configure an always-on VPN connection through a specific application for the current user. This connection is automatically granted and persisted after a reboot.
As a personal profile user - I don't want my VPN to decide for itself when to connect (set always on programmatically will immediately connect the VPN, if implemented correctly).
As a work profile user (wearing the hat of an employee), it's not my decision, but my organization's (via the profile owner app).
So, all in all, this behavior makes sense.
Update:
Instead implementing MDM, which could take a lot of work, you can clone, build and debug Google's Test DPC app, which have everything you need to test toggling always-on VPN programmatically.
It also have million other things, which you don't need so be sure to ignore the rest :)
I haven't looked at their code, but I suggest searching for usages of setAlwaysOnVpnPackage function.
Google's Test DPC app:
Link to Play Store
Link to GitHub repo (to build & debug it yourself)
I have an app that I use to connect to WiFi network that doesn't have connection to the Internet. It has been working fine with versions before Nougat. Since I upgraded my phone to Nougat few weeks ago, I'm not able to connect to the same WiFi network anymore. It connected briefly and disconnected and then rolled back to the previous network that has connection to the Internet. Below is the code that was working fine before Nougat.
WifiManager manager = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
WifiConfiguration selectedConfig = new WifiConfiguration();
selectedConfig.SSID = ssid;
selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
manager.addNetwork(selectedConfig);
List<WifiConfiguration> cofigs = manager.getConfiguredNetworks();
for( WifiConfiguration config : cofigs)
{
if(config.SSID != null && config.SSID.equals(selectedConfig.SSID))
{
manager.disconnect();
manager.enableNetwork(config.networkId, true);
break;
}
}
In the past, setting true in manager.enableNetwork(config.networkId, true) seemed to let the connection stay on with the network that doesn't have connection to the internet. However, since Nougat, this doesn't seem to work anymore.
Does anyone know what's going on and how to make it work?
Thanks.
the boolean parameter from the enableNetwork method is to block the other networks.
Actually, there is no way for you to tell the device to connect to certain network, the only thing that you can do is to block the other networks and that way, the only option that the device has to connect is the one that you didn't disable (the one with the id on the 1st parameter).
I would recommend you to try and check what is returned from the addNetwork and check this google issue Google issue .
If that doesn't solve your problem, check if you are scanning somewhere else. If you scan for the available networks, your device will enable the other networks, so the others won't be disabled anymore and your device will connect to the one that it was in the beginning or the one that has higher priority.
Hope it helped
I'm trying to use ODB Java API (this library) to get the data from ELM327 via Bluetooth from my car, but in returns ? on every request, and library raises MisunderstoodException
Here is my code:
socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
socket.connect();
final CustomRPMCommand engineRpmCommand = new CustomRPMCommand();
final SpeedObdCommand speedObdCommand = new SpeedObdCommand();
while (!Thread.currentThread().isInterrupted()) {
engineRpmCommand.run(socket.getInputStream(), socket.getOutputStream());
speedObdCommand.run(socket.getInputStream(), socket.getOutputStream());
runOnUiThread(new Runnable() {
#Override
public void run() {
speedometerGauge.setSpeed(engineRpmCommand.getRPM(), true);
rpmGauge.setSpeed(speedObdCommand.getMetricSpeed(), true);
}
});
}
What's wrong?
I also used the same library for the first steps into trying out OBD, so I can say at least at the time I used it, it worked fine.
From my experience however, getting ? back can sometimes happen with cheap Bluetooth devices (maybe even with expensive ones? never had one). I guess this happens, if some bits are lost during the transmission, because then command will be misunderstood.
What I did to circumvent this problem is setting up a process where I sent all AT commands up to 10 times until I get the desired response of OK (except for ATZ, which will respond with ELM327). As for value requests like RPM etc. I usually just throw away the erroneous values.
That's the short answer, but since such problems with the devices can annoy a lot, I will guide you into debugging the whole process...
Setting up a terminal on windows
First of all to test the functionality of the ELM device, you can send commands to the serial interface directly. On windows, this is possible using for example TeraTerm and then setting up new Bluetooth connection on your windows as a COM device (search for Bluetooth in start -> search box and then choose Change Bluetooth settings or similar). From there, go to COM connections and then add a new one Outgoing for the Bluetooth OBDII device. Wait a bit for windows to calculate the new COM port number, you will need it.
If you cannot find OBDII in the dropdown box, you have to bond your PC with your Bluetooth device first. This can be done via devices and printers, there you should see the OBDII device, so you only have to connect it (PIN usually is 1234).
If you're on Linux, it might be somewhat easier, but I haven't done it :)
Sending some commands via terminal
Once you have your Bluetooth connection and TeraTerm installed, you can start TeraTerm and connect to the adapter. Choose Serial and then the port you just set up. Ensure, that no other device is connected to the OBD adapter (also not your phone). Only one device can be connected at a time.
If connection was successful, you should be able to type letters. Usually, in default settings you should be able to see the letters you type (Echo mode on), but since this is not certain, just type ATZ and hit <Enter>. The ELM should respond with "ELM327" in the same line now (which for me usually results in odd display if echo mode was on, but you should get any response).
From terminal I usually send these commands in order:
ATZ
E1
L1
010c
This will trigger:
Reset of the OBD device
Make sure that echo is on, so I see what I am typing
Make sure Line feed is on, so we get responses in the next line
Request RPM from the vehicle
Between each command I'll check what is the reply of the device. For all AT commands (1., 2. and 3.) it must be OK. If I get back ?, which can happen, I will repeat the command another time. You will see that in such a case the device indeed did not follow the instructions, e.g. did not set line feed on if it was off. So we really have to send it again.
In programming mode on the other hand, we will set e0 and l0 (echo mode off and line feed off), because we do not want to get sent back what we already sent out.
If I dial
*
#
*
#
8
2
5
5
#
*
#
*
, I get my android device id which starts with android-35c2acdd...
source
If I use Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID) the result starts with a96b4b27...
If I use ((TelephonyManager) Context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId() the result starts with 3538330...
What is the difference between these ID-s? How can I get the result of the
*
#
*
#
8
2
5
5
#
*
#
*
dial?
IMEI
The IMEI is the 'MAC' for the telephony module - the unique ID that the telephone uses when it connects via GSM/GPRS/HSPDA/etc. The GSM network uses it to route calls and data from the phone over the GSM network right up to the gateway into the Internet (which is an IP network).
A telephony module is a chip or circuit board that handles the telephone network, either GSM or CMDA, and often has a slot for a removable SIM card. Some phones have more than one telephony module (active dual- or multi-SIM phones). Each telephony module has its own IMEI.
Manufacturers give each phone (strictly the telephony module) a unique IMEI during manufacturing. However the number can normally be rewritten if you have the right software. This is often done after a phone has been stolen to give the phone a new identity and bipass stolen phone blocking system.
The IMEI can be programmatically obtained using the TelephonyManager.getDeviceId() API.
CDMA phones have a ESN or MEID which are different lengths and formats, even though it is retrieved using the same API.
Android devices without telephony modules - for example many tablets and TV devices - do not have an IMEI. As Schlangi commented, some devices that do not have a telephony module fake the IMEI, so the presence of an IMEI does not (always) guarantee the device has a telephony module.
ANDROID_ID
The ANDROID_ID is another unique number on the phone - this is automatically generated by the OS as it boots for the first time (doing it this way makes it much easier for the manufacturers by removing a step from the production line).
The ANDROID_ID can (and does) change, for example:
Factory reset (including when reflashing the OS)
In software: eg https://play.google.com/store/apps/details?id=com.vcastroi.changeid
It is mainly used by developers (eg identifying and connecting to devices using adb)
ANDROID_ID can be used to identify an Android device given the caveats above, realistically meaning that it uniquely identifies the device over significant portions of the device lifetime, but cannot be relied on.
Also note that there was a bug in Froyo where many devices gave themselves the same ANDROID_ID. This is the bug
Other identifiers
There are a number of other things that can be used identify the device:
MAC address of the WiFi module: WifiManager.getConnectionInfo() -> WifiInfo.getMacAddress(). This can often be changed in software, but generally is constant over the device lifetime. Also it can only be read if the WiFi module is switched on.
MAC address of the BlueTooth module: BluetoothAdaptor.getAddress(). Like WiFi MAC, this can often be changed in software and may be off when you need it
The subscriber's telephone number. This may change if the user requests a new number from the telco, or if the user switches SIMs. It is obtained from TelephonyManager.getLine1Number(). This is only present for Android phone devices with a current SIM installed and a paid service with a telco.
The SIM contains its own identifying number (IMSI). This is obtained from the TelephonyManager.getSubscriberId() API. Obviously the SIM may not be present at any specific time, and it changes when the SIM is changed - and users can upgrade/replace their SIM while keeping the same number, so you can't say that this is one-to-one to a specific phone or user.
Related to the IMSI is the MSISDN. This functions as the identification of a subscription (your contract for a specific telephone number with your mobile provider) and therefore gives the device its telephone number. The MSISDN may be associated with several SIM cards, and therefore several phones. It comes with all the caveats for reading the SIM above. This may be retrieved with TelephonyManager.getSimSerialNumber(). Thanks Schlangi for the corrections and additions
Gingerbread and later has android.os.Build.SERIAL which many manufacturers set (but not all. Bugger).
Other notes
You need specific permissions to access each and every API, so if you try for all of them, your app's permissions in the Google Play store look fairly permissive.
I think this link explains all the other available options also https://android-developers.googleblog.com/2011/03/identifying-app-installations.html
Found on the web:
private static final Uri URI = Uri.parse("content://com.google.android.gsf.gservices");
private static final String ID_KEY = "android_id";
String getAndroidId(Context ctx) {
String[] params = { ID_KEY };
Cursor c = ctx.getContentResolver()
.query(URI, null, null, params, null);
if (!c.moveToFirst() || c.getColumnCount() < 2)
return null;
try {
return Long.toHexString(Long.parseLong(c.getString(1)));
} catch (NumberFormatException e) {
return null;
}
}
Add permission:
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
However, I doubt that is a documented ID and I would be carefull because that might not work if GTalk gets updated.
Source: http://blog.codepainters.com/2012/01/17/how-to-obtain-gtalk-android-id/
Also worth having a look at: http://www.toxicbakery.com/android-development/getting-google-auth-sub-tokens-in-your-android-applications/
There are some approach to get unique identifier on android phone.
Android ID
It is a 64-bit hex string which is generated on the device's first boot.
Generally it won't changed unless is factory reset.
Secure.getString(getContentResolver(), Secure.ANDROID_ID);
The Android ID , considered unreliable because it can sometimes be null.
The documentation states that it "can change upon factory reset".
This string can also be altered on a rooted phone.
String m_szAndroidID = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
Returns: 9774d56d682e549c . No special permissions required.
2. The WLAN MAC Address string, is another unique identifier that you can use as a device id.
Before you read it, you will need to make sure that your project has the android.permission.ACCESS_WIFI_STATE
permission or the WLAN MAC Address will come up as null.
WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
Returns: 00:11:22:33:44:55 (not a real address since this is a custom ROM , as you can see the MAC address can easily be faked).
WLAN doesn't have to be on, to read this value.
3. The BT MAC Address string, available on Android devices with Bluetooth, can be read if your project has the android.permission.BLUETOOTH permission.
BluetoothAdapter m_BluetoothAdapter = null; // Local Bluetooth adapter
m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String m_szBTMAC = m_BluetoothAdapter.getAddress();
Returns: 43:25:78:50:93:38 . BT doesn't have to be on, to read it.
4. IMEI only for Android devices with Phone use:
TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String szImei = TelephonyMgr.getDeviceId(); // Requires READ_PHONE_STATE
This requires adding a permission in AndroidManifest.xml, and users will be notified upon installing
your software: android.permission.READ_PHONE_STATE. The IMEI is unique for your phone
and it looks like this: 359881030314356 (unless you have a pre-production device with an invalid IMEI like 0000000000000).
For more info refer this link.
IMEI
There is a mandatory requirement by the standardization bodies, that mobile devices for public networks may be uniquely identified by the IMEI number
It is the manufacturer's responsibility to set IMEI. In practice, developers sometimes see IMEIs like 000000... or 123456... Sometimes phones with identical IMEI go to production, which of course is a bug that should be fixed...
ANDROID_ID
A 64-bit number (as a hex string) that is randomly generated on the device's first boot and should remain constant for the lifetime of the device. (The value may change if a factory reset is performed on the device.)
It looks like Android does not trust the manufacturers and provides an alternative unique ID.
EDIT:
This is what I get (instead of IMEI) on and Android device that is not a phone:
$ adb shell dumpsys iphonesubinfo
Phone Subscriber Info:
Phone Type = GSM
Device ID = null
I think all the information provided above is well enough to understand the codes.
Yet I think you are still "not able to see the result of the ##8255## dial" (plz excuse if I went wrong somewhere in understanding this)
I assume the reason behind this is one of the latest bug fix against USSD code made in Android.
(you may read more about this and check if your device is on the list. its all over the web)
Finally, if you just want to get the android ID straightaway i suggest you to use this app-
https://play.google.com/store/apps/details?id=com.redphx.deviceid&hl=en
I'm writing a program that speaks with an external accessory over rfcomm.
My problem is that I don't know what the correct way of identifying my device is.
the way I do it now is like this:
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals(MY_DEVICE_NAME)) {
this.myDevice = device;
break;
}
}
This method however relies on the name of the device which to me seems dirty and bad :)
is there a better way to do this?
I tried looking at all the methods of BluetoothDevice but none seemed to help - is the name really the best way to do it?
I saw that in some places people say that I should use UUIDs but that is used to open the socket to the device once I have it:
_socket = myDevice.createRfcommSocketToServiceRecord(MY_UUID);
is there a better way to do it?
Devices of the same kind/functionality and/or brand will usually have a similar name. For example, all RN-41 devices from Roving Networks have the following name:
FireFly-XXXX
where XXXX is the last 4 digits of the device's address. That means you can use the following to connect to any of them:
if (device.getName().startsWith("FireFly-")) {
this.myDevice = device;
break;
}
This is exactly what I do in my app and haven't found any more reliable/consistent way to do it. As a generalization, you should be able to use a regular pattern if the name in the devices you are interested in is any more complex than the example above.
You can use myDevice.getAddress() to get the bluetooth device address and compare, it will always be unique (unlike name)
You can also use BluetoothDevice.getBluetoothClass() for at narrowing down which devices might be relevant.
BluetoothClass.getMajorDeviceClass() will tell you roughly what kind of device it is - a phone, a computer, an audio or video device, or whatever.
BluetoothClass.hasService() further specifies some capabilities of the device.
Within each of the major classes, some minor classes are defined - what kind of computer / audio-video device / phone / health equipment etc. it is.
Also, on recent versions of the Android platform (API level 15+), you can query for the service records of a device, without having to connect to it. See BluetoothDevice.fetchUuidsWithSdp() and BluetoothDevice.getUuids().