How to get current network signal strength in android? [duplicate] - android

I am working on a little app to check the signal strength of various network operators in my area. My current operators signal is quite unstable and I want to look into the strength of other GSM operators.
Sofar I've been using the TelephonyManager and a PhoneStateListener with the onSignalStrengthsChanged call back to get the GSM Signal strength of the current network operator, but it seems that this class only gives me info on the signal strength of the network attached to my SIM card.
I'm interested in measurement of GSM signal strength of ALL available operators. Searching the net has given vague hints on using internal android classes, but I've not yet found any good examples on this.
Any answer that can move me on to get a list of all available network operators and their signal strength are appreaciated.

Maybe these quotes and links can help you code your own solution:
1.- To get a list of available network providers (quoting How to get a list of available network providers? in full):
Since Android is open source I had a look at the sources and finally
found something called INetworkQueryService. I guess you can do the
same as the android settings implementation and interact with this
service. Some guidance through NetworkSettings.java:
onCreate starts the NetworkQueryService and binds it.
loadNetworksList() tells the service to query for network operators.
INetworkQueryServiceCallback is evaluated and if the event "EVENT_NETWORK_SCAN_COMPLETED" was raised, networksListLoaded will be
called to iterate over the available Networks.
2.- Even a quick read to NetworkSetting.java and INetworkQueryService interface, gives us an idea to achieve your goal.
Connect the service in declaration.
/**
* Service connection code for the NetworkQueryService.
* Handles the work of binding to a local object so that we can make
* the appropriate service calls.
*/
/** Local service interface */
private INetworkQueryService mNetworkQueryService = null;
/** Service connection */
private final ServiceConnection mNetworkQueryServiceConnection = new ServiceConnection() {
/** Handle the task of binding the local object to the service */
public void onServiceConnected(ComponentName className, IBinder service) {
if (DBG) log("connection created, binding local service.");
mNetworkQueryService = ((NetworkQueryService.LocalBinder) service).getService();
// as soon as it is bound, run a query.
loadNetworksList();
}
/** Handle the task of cleaning up the local binding */
public void onServiceDisconnected(ComponentName className) {
if (DBG) log("connection disconnected, cleaning local binding.");
mNetworkQueryService = null;
}
};
onCreate starts the NetworkQueryService and binds it.
Intent intent = new Intent(this, NetworkQueryService.class);
...
startService (intent);
bindService (new Intent(this, NetworkQueryService.class), mNetworkQueryServiceConnection,
Context.BIND_AUTO_CREATE);
loadNetworksList() tells the service to query for network operators.
private void loadNetworksList() {
...
// delegate query request to the service.
try {
mNetworkQueryService.startNetworkQuery(mCallback);
} catch (RemoteException e) {
}
displayEmptyNetworkList(false);
}
INetworkQueryServiceCallback is evaluated:
/**
* This implementation of INetworkQueryServiceCallback is used to receive
* callback notifications from the network query service.
*/
private final INetworkQueryServiceCallback mCallback = new INetworkQueryServiceCallback.Stub() {
/** place the message on the looper queue upon query completion. */
public void onQueryComplete(List<OperatorInfo> networkInfoArray, int status) {
if (DBG) log("notifying message loop of query completion.");
Message msg = mHandler.obtainMessage(EVENT_NETWORK_SCAN_COMPLETED,
status, 0, networkInfoArray);
msg.sendToTarget();
}
};
If the event "EVENT_NETWORK_SCAN_COMPLETED" was raised, networksListLoaded will be called to iterate over the available Networks.
private void networksListLoaded(List<OperatorInfo> result, int status) {
...
if (status != NetworkQueryService.QUERY_OK) {
...
displayNetworkQueryFailed(status);
displayEmptyNetworkList(true);
} else {
if (result != null){
displayEmptyNetworkList(false);
...
} else {
displayEmptyNetworkList(true);
}
}
}
I hope it helps. I think it's an interesting challenge so maybe I'll give it a try next time I have some spare time. Good luck!

private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallForwardingIndicatorChanged(boolean cfi) {
super.onCallForwardingIndicatorChanged(cfi);
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
//checkInternetConnection();
String callState = "UNKNOWN";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
callState = "IDLE";
break;
case TelephonyManager.CALL_STATE_RINGING:
callState = "Ringing (" + incomingNumber + ")";
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
callState = "Offhook";
break;
}
Log.i("Phone Stats", "onCallStateChanged " + callState);
super.onCallStateChanged(state, incomingNumber);
}
#Override
public void onCellLocationChanged(CellLocation location) {
String cellLocationString = location.toString();
super.onCellLocationChanged(location);
}
#Override
public void onDataActivity(int direction) {
String directionString = "none";
switch (direction) {
case TelephonyManager.DATA_ACTIVITY_IN:
directionString = "IN";
break;
case TelephonyManager.DATA_ACTIVITY_OUT:
directionString = "OUT";
break;
case TelephonyManager.DATA_ACTIVITY_INOUT:
directionString = "INOUT";
break;
case TelephonyManager.DATA_ACTIVITY_NONE:
directionString = "NONE";
break;
default:
directionString = "UNKNOWN: " + direction;
break;
}
Log.i("Phone Stats", "onDataActivity " + directionString);
super.onDataActivity(direction);
}
#Override
public void onDataConnectionStateChanged(int state,int networktype) {
String connectionState = "Unknown";
switch (state ) {
case TelephonyManager.DATA_CONNECTED :
connectionState = "Connected";
break;
case TelephonyManager.DATA_CONNECTING:
connectionState = "Connecting";
break;
case TelephonyManager.DATA_DISCONNECTED:
connectionState = "Disconnected";
break;
case TelephonyManager.DATA_SUSPENDED:
connectionState = "Suspended";
break;
default:
connectionState = "Unknown: " + state;
break;
}
super.onDataConnectionStateChanged(state);
Log.i("Phone Stats", "onDataConnectionStateChanged "
+ connectionState);
}
#Override
public void onMessageWaitingIndicatorChanged(boolean mwi) {
super.onMessageWaitingIndicatorChanged(mwi);
}
#Override
public void onServiceStateChanged(ServiceState serviceState) {
String serviceStateString = "UNKNOWN";
switch (serviceState.getState()) {
case ServiceState.STATE_IN_SERVICE:
serviceStateString = "IN SERVICE";
break;
case ServiceState.STATE_EMERGENCY_ONLY:
serviceStateString = "EMERGENCY ONLY";
break;
case ServiceState.STATE_OUT_OF_SERVICE:
serviceStateString = "OUT OF SERVICE";
break;
case ServiceState.STATE_POWER_OFF:
serviceStateString = "POWER OFF";
break;
default:
serviceStateString = "UNKNOWN";
break;
}
Log.i("Phone Stats", "onServiceStateChanged " + serviceStateString);
super.onServiceStateChanged(serviceState);
}
#Override
public void onSignalStrengthChanged(int asu) {
Log.i("Phone Stats", "onSignalStrengthChanged " + asu);
setSignalLevel( asu);
super.onSignalStrengthChanged(asu);
}
private void setSignalLevel(int level) {
int sLevel = (int) ((level / 31.0) * 100);
Log.i("signalLevel ", "" + sLevel);
}
};

As I have no 50 reputation points, here is the result of my searches about the subject :
The solution of Alejandro Colorado seems to be the good one. But the problem is that the classes used to achieve it are reserved for android system applications, i.e. apps which are signed with the same signature key as the system.
How could it be possible? I found two way to achieve this.
The first one is to ask a job at any manufacturer compagny, and sign their NDA, but eh, that's not a really good solution. Especially as the app implemented and signed with this key will only work on devices from the compagny...
The second one, much more enjoyable, but i warn you, it's not gonna be easy, is to make your own ROM. You'll have to create your application, insert it in the /system/app/ directory of your ROM and recompile it to flash your device with your new system. But there's a question i've not answered yet, is the problem of unrecognised ROM signature.
I think the best way to avoid this problem is to add your ROM signing key in the Recovery you'll be using.
That's where i am at this point, maybe you could find these research usefull, i hope so!
I'll come back later if i find some more informations for you guys. Bye.

create a PhoneStateListener and handle the onSignalStrengthChanged callback. When your app is initialized, it should give you an initial notification. This is in 1.x. in 2.x, there's an open issueabout this.

Related

isGestureDetectionAvailable() always returns 'FALSE' on android 28

I have built an app which lets the user control their scrolling action using the fingerprint sensor.
It used to work earlier until some weeks back, where I found that method: isGestureDetectionAvailable() always returns 'False' after starting 'accessibility service'
Since I am getting 'isGestureDetectionAvailable()' as always 'False',
my 'registerFingerprintGestureCallback' doesn't work and hence all my functionality of swiping gestures.
Can Someone please help and point out what I am doing wrong.
Here is my code.
protected void onServiceConnected() {
super.onServiceConnected();
FingerprintGestureController gestureController = getFingerprintGestureController();
Log.e(TAG, "Is available: " + gestureController.isGestureDetectionAvailable());
FingerprintGestureController.FingerprintGestureCallback callback = new
FingerprintGestureController.FingerprintGestureCallback() {
public void onGestureDetectionAvailabilityChanged(boolean available) {
super.onGestureDetectionAvailabilityChanged(available);
Log.d(TAG, "onGestureDetectionAvailabilityChanged " + available);
}
public void onGestureDetected(int gesture) {
switch (gesture) {
case FINGERPRINT_GESTURE_SWIPE_UP:
scrollDown();
break;
case FINGERPRINT_GESTURE_SWIPE_DOWN:
scrollUp();
break;
case FINGERPRINT_GESTURE_SWIPE_RIGHT:
execute_swipe_right_functionality();
break;
case FINGERPRINT_GESTURE_SWIPE_LEFT:
execute_swipe_left_functionality();
break;
default:
Log.e("My Service",
"Error: Unknown gesture type detected!");
break;
}
}
};
gestureController.registerFingerprintGestureCallback(callback, new Handler());
}

How to restrict bound service to be called by particular packages

I have written a bound service and I would like this service to be only called from particular app. I do not want other apps to be able to make calls to this service.
The options I know so far are:
Use a permission. There seems to be 3 secured permission, dangerous, signature and signatureOrSystem. Unfortunately, none of these permissions will work for me as I don't want users to accept this permission also both app does not have same signature and these are not system app.
Get app name on service bind or when making a call to service. I looked up a way to do this on stackoverflow here. This unfortunately does not works for me as it always returns the app ID in which the service resides.
Is there any other option for me or I can use the above mentioned options with some change to achieve the desired requirement.
Bound Service Code
public class SampleCommsService extends Service {
private static Messenger messanger;
#Override
public IBinder onBind(Intent intent) {
Log.e("TEST", "package intent: " + intent.getPackage());
String callingApp = MyApplication.getAppContext().getPackageManager().getNameForUid(Binder.getCallingUid());
Log.e("TEST", "onBind - package name: " + callingApp);
return getMyBinder();
}
private synchronized IBinder getMyBinder() {
if (messanger == null) {
messanger = new Messenger(new SettingsProcessor());
}
return messanger.getBinder();
}
class SettingsProcessor extends Handler {
private static final int GET_SETTINGS_REQUEST = 1;
private static final int UPDATE_SETTINGS_RESPONSE = 2;
private static final String SETTINGS = "settings";
#Override
public void handleMessage(Message msg) {
String callingApp = MyApplication.getAppContext().getPackageManager().getNameForUid(Binder.getCallingUid());
Log.e("TEST", "handle message - package name: " + callingApp);
switch (msg.what) {
case GET_SETTINGS_REQUEST:
sendSettingsValue(msg);
break;
default:
super.handleMessage(msg);
}
}
private void sendSettingsValue(Message msg) {
try {
Message resp = Message.obtain(null, UPDATE_SETTINGS_RESPONSE);
Bundle bundle = new Bundle();
bundle.putBoolean(SETTINGS, MyApplication.isSettingsEnabled());
resp.setData(bundle);
msg.replyTo.send(resp);
} catch (RemoteException e) {
// ignore
}
}
}
}
Output on calling api:
02-01 15:21:03.138 7704-7704/my.service.package E/TEST: package intent: null
02-01 15:21:03.139 7704-7704/my.service.package E/TEST: onBind - package name: my.service.package
02-01 15:21:12.429 7704-7704/my.service.package E/TEST: handle message - package name: my.service.package
OK, I was able to solve this problem based on a given answer here. The answer given in the link obviously does not works, but you can get the app ID from the Handler used for the bound service.
class SettingsProcessor extends Handler {
#Override
public void handleMessage(Message msg) {
String callingApp = MyApplication.getAppContext().getPackageManager().getNameForUid(msg.sendingUid);
Log.e("TEST", "handle message - package name: " + callingApp);
}
}
Instead of Binder.getCallingUid(), I am using msg.sendingUid and it works fine for me.

Programmatically pairing with a BLE device on Android 4.4+

Does anyone have a complete working example of how to programmatically pair with a BLE (not Bluetooth Classic) device that uses passkey entry (i.e. a 6-digit PIN) or Numeric Comparison on Android 4.4 or later? By 'programmatically' I mean I tell Android the PIN - the user isn't prompted.
There are many similar questions about this on SO but they are either a) about Bluetooth Classic, b) old (before setPin() and createBond() were public), or c) unanswered.
My understanding is as follows.
You connect to the device and discover its services.
You try to read a 'protected' characteristic.
The device returns an authentication error.
Android somehow initiates pairing and you tell it the PIN.
You can now read the characteristic.
I have created a device using mBed running on the nRF51-DK and given it a single characteristic.
I set up the security parameters like so:
ble.securityManager().init(
true, // Enable bonding (though I don't really need this)
true, // Require MitM protection. I assume you don't get a PIN prompt without this, though I'm not 100% sure.
SecurityManager::IO_CAPS_DISPLAY_ONLY, // This makes it us the Passkey Entry (PIN) pairing method.
"123456"); // Static PIN
And then in the characteristic I used
requireSecurity(SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM);
Now when I try to read it with the Nordic Master Control Panel, I get a pairing request notification like this:
And I can put this PIN in, and then MCP says I'm bonded, and can read the characteristic.
However, in my app I would like to avoid having the user enter the PIN, since I know it already. Does anyone have a complete recent example of how to do this?
Edit: By the way this is the most relevant question I found on SO, but the answer there doesn't seem to work.
I almost have it working. It pairs programmatically but I can't get rid of the "Pairing request" notification. Some answers to this question claim to be able to hide it just after it is shown using the hidden method cancelPairingUserInput() but that doesn't seem to work for me.
Edit: Success!
I eventually resorted to reading the source code of BluetoothPairingRequest and the code that sends the pairing request broadcast and realised I should be intercepting the ACTION_PAIRING_REQUEST. Fortunately it is an ordered intent broadcast so you can intercept it before the system does.
Here's the procedure.
Register to receive BluetoothDevice.ACTION_PAIRING_REQUEST changed broadcast intents. Use a high priority!
Connect to the device.
Discover services.
If you have disconnected by now, it's probably because the bond information is incorrect (e.g. the peripheral purged it). In that case, delete the bond information using a hidden method (seriously Google), and reconnect.
Try to read a characteristic that requires encryption MitM protection.
In the ACTION_PAIRING_REQUEST broadcast receiver, check that the pairing type is BluetoothDevice.PAIRING_VARIANT_PIN and if so, call setPin() and abortBroadcast(). Otherwise you can just let the system handle it, or show an error or whatever.
Here is the code.
/* This implements the BLE connection logic. Things to watch out for:
1. If the bond information is wrong (e.g. it has been deleted on the peripheral) then
discoverServices() will cause a disconnect. You need to delete the bonding information and reconnect.
2. If the user ignores the PIN request, you get the undocumented GATT_AUTH_FAILED code.
*/
public class ConnectActivityLogic extends Fragment
{
// The connection to the device, if we are connected.
private BluetoothGatt mGatt;
// This is used to allow GUI fragments to subscribe to state change notifications.
public static class StateObservable extends Observable
{
private void notifyChanged() {
setChanged();
notifyObservers();
}
};
// When the logic state changes, State.notifyObservers(this) is called.
public final StateObservable State = new StateObservable();
public ConnectActivityLogic()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Tell the framework to try to keep this fragment around
// during a configuration change.
setRetainInstance(true);
// Actually set it in response to ACTION_PAIRING_REQUEST.
final IntentFilter pairingRequestFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
pairingRequestFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 1);
getActivity().getApplicationContext().registerReceiver(mPairingRequestRecevier, pairingRequestFilter);
// Update the UI.
State.notifyChanged();
// Note that we don't actually need to request permission - all apps get BLUETOOTH and BLUETOOTH_ADMIN permissions.
// LOCATION_COARSE is only used for scanning which I don't need (MAC is hard-coded).
// Connect to the device.
connectGatt();
}
#Override
public void onDestroy()
{
super.onDestroy();
// Disconnect from the device if we're still connected.
disconnectGatt();
// Unregister the broadcast receiver.
getActivity().getApplicationContext().unregisterReceiver(mPairingRequestRecevier);
}
// The state used by the UI to show connection progress.
public ConnectionState getConnectionState()
{
return mState;
}
// Internal state machine.
public enum ConnectionState
{
IDLE,
CONNECT_GATT,
DISCOVER_SERVICES,
READ_CHARACTERISTIC,
FAILED,
SUCCEEDED,
}
private ConnectionState mState = ConnectionState.IDLE;
// When this fragment is created it is given the MAC address and PIN to connect to.
public byte[] macAddress()
{
return getArguments().getByteArray("mac");
}
public int pinCode()
{
return getArguments().getInt("pin", -1);
}
// Start the connection process.
private void connectGatt()
{
// Disconnect if we are already connected.
disconnectGatt();
// Update state.
mState = ConnectionState.CONNECT_GATT;
State.notifyChanged();
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(macAddress());
// Connect!
mGatt = device.connectGatt(getActivity(), false, mBleCallback);
}
private void disconnectGatt()
{
if (mGatt != null)
{
mGatt.disconnect();
mGatt.close();
mGatt = null;
}
}
// See https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/master/stack/include/gatt_api.h
private static final int GATT_ERROR = 0x85;
private static final int GATT_AUTH_FAIL = 0x89;
private android.bluetooth.BluetoothGattCallback mBleCallback = new BluetoothGattCallback()
{
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
super.onConnectionStateChange(gatt, status, newState);
switch (newState)
{
case BluetoothProfile.STATE_CONNECTED:
// Connected to the device. Try to discover services.
if (gatt.discoverServices())
{
// Update state.
mState = ConnectionState.DISCOVER_SERVICES;
State.notifyChanged();
}
else
{
// Couldn't discover services for some reason. Fail.
disconnectGatt();
mState = ConnectionState.FAILED;
State.notifyChanged();
}
break;
case BluetoothProfile.STATE_DISCONNECTED:
// If we try to discover services while bonded it seems to disconnect.
// We need to debond and rebond...
switch (mState)
{
case IDLE:
// Do nothing in this case.
break;
case CONNECT_GATT:
// This can happen if the bond information is incorrect. Delete it and reconnect.
deleteBondInformation(gatt.getDevice());
connectGatt();
break;
case DISCOVER_SERVICES:
// This can also happen if the bond information is incorrect. Delete it and reconnect.
deleteBondInformation(gatt.getDevice());
connectGatt();
break;
case READ_CHARACTERISTIC:
// Disconnected while reading the characteristic. Probably just a link failure.
gatt.close();
mState = ConnectionState.FAILED;
State.notifyChanged();
break;
case FAILED:
case SUCCEEDED:
// Normal disconnection.
break;
}
break;
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status)
{
super.onServicesDiscovered(gatt, status);
// Services have been discovered. Now I try to read a characteristic that requires MitM protection.
// This triggers pairing and bonding.
BluetoothGattService nameService = gatt.getService(UUIDs.NAME_SERVICE);
if (nameService == null)
{
// Service not found.
disconnectGatt();
mState = ConnectionState.FAILED;
State.notifyChanged();
return;
}
BluetoothGattCharacteristic characteristic = nameService.getCharacteristic(UUIDs.NAME_CHARACTERISTIC);
if (characteristic == null)
{
// Characteristic not found.
disconnectGatt();
mState = ConnectionState.FAILED;
State.notifyChanged();
return;
}
// Read the characteristic.
gatt.readCharacteristic(characteristic);
mState = ConnectionState.READ_CHARACTERISTIC;
State.notifyChanged();
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
super.onCharacteristicRead(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS)
{
// Characteristic read. Check it is the right one.
if (!UUIDs.NAME_CHARACTERISTIC.equals(characteristic.getUuid()))
{
// Read the wrong characteristic. This shouldn't happen.
disconnectGatt();
mState = ConnectionState.FAILED;
State.notifyChanged();
return;
}
// Get the name (the characteristic I am reading just contains the device name).
byte[] value = characteristic.getValue();
if (value == null)
{
// Hmm...
}
disconnectGatt();
mState = ConnectionState.SUCCEEDED;
State.notifyChanged();
// Success! Save it to the database or whatever...
}
else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION)
{
// This is where the tricky part comes
if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE)
{
// Bonding required.
// The broadcast receiver should be called.
}
else
{
// ?
}
}
else if (status == GATT_AUTH_FAIL)
{
// This can happen because the user ignored the pairing request notification for too long.
// Or presumably if they put the wrong PIN in.
disconnectGatt();
mState = ConnectionState.FAILED;
State.notifyChanged();
}
else if (status == GATT_ERROR)
{
// I thought this happened if the bond information was wrong, but now I'm not sure.
disconnectGatt();
mState = ConnectionState.FAILED;
State.notifyChanged();
}
else
{
// That's weird.
disconnectGatt();
mState = ConnectionState.FAILED;
State.notifyChanged();
}
}
};
private final BroadcastReceiver mPairingRequestRecevier = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(intent.getAction()))
{
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);
if (type == BluetoothDevice.PAIRING_VARIANT_PIN)
{
device.setPin(Util.IntToPasskey(pinCode()));
abortBroadcast();
}
else
{
L.w("Unexpected pairing type: " + type);
}
}
}
};
public static void deleteBondInformation(BluetoothDevice device)
{
try
{
// FFS Google, just unhide the method.
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
}
catch (Exception e)
{
L.e(e.getMessage());
}
}
}
I also faced the same problem and after all the research, I figured out the below solution to pair to a BLE without any manual intervention.
(Tested and working!!!)
I am basically looking for a particular Bluetooth device (I know MAC address) and pair with it once found. The first thing to do is to create pair request using a broadcast receiver and handle the request as below.
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
registerReceiver(broadCastReceiver,intentFilter);
You need to write the broadcastReceiver and handle it as below.
String BLE_PIN = "1234"
private BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action))
{
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
bluetoothDevice.setPin(BLE_PIN.getBytes());
Log.e(TAG,"Auto-entering pin: " + BLE_PIN);
bluetoothDevice.createBond();
Log.e(TAG,"pin entered and request sent...");
}
}
};
Voila! You should be able to pair to Bluetooth device without ANY MANUAL INTERVENTION.
Hope this helps :-) Please make it right answer if it works for you.

Android Accessibility API: Fill up multiple EditText or move to next EditText

I'm making an auto-fill type accessibility service for android. I read the documentation and did some googling and it's still confusing to me. I got only one edittext to fill up the text. Whenever I try to move to the next edittext, it doesn't work. Is there a way to access all the edit text a once? Anyone has a solution for this?
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
final int eventType = event.getEventType();
String eventText = null;
switch(eventType) {
case AccessibilityEvent.TYPE_VIEW_CLICKED:
eventText = "Clicked: ";
break;
case AccessibilityEvent.TYPE_VIEW_FOCUSED:
eventText = "Focused " + event.getItemCount() +":";
break;
}
eventText = eventText + event.getContentDescription();
System.out.println("Accessibility On Accessibility Event");
Log.i("Test", "Custom Accessibility On Accessibility Event");
// Do something nifty with this text, like speak the composed string
// back to the user.
Toast.makeText(getApplicationContext(), eventText, Toast.LENGTH_LONG).show();
//let's try this
AccessibilityNodeInfo nodeInfo = event.getSource();
if(event.getClassName().equals("android.widget.EditText")) {
Bundle arguments = new Bundle();
arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, "Howdy");
nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
nodeInfo.performAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
// event.setAction(AccessibilityEvent.TYPE_TOUCH_INTERACTION_START);
}
}
#Override
public void onInterrupt() {
System.out.println("CustomAccessibility On Interrupt");
Log.i("Custom", "CustomAccessibility On Interrupt");
}
#Override
protected void onServiceConnected() {
//super.onServiceConnected();
Toast.makeText(getApplication(), "onServiceConnected", Toast.LENGTH_SHORT).show();
System.out.println("CustomAccessibility On Service Connected");
Log.i("Custom", "CustomAccessibility On Service Connected");
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
// Set the type of events that this service wants to listen to. Others
// won't be passed to this service.
info.eventTypes = AccessibilityEvent.TYPE_VIEW_CLICKED |
AccessibilityEvent.TYPE_VIEW_FOCUSED;
// If you only want this service to work with specific applications, set their
// package names here. Otherwise, when the service is activated, it will listen
// to events from all applications.
// Set the type of feedback your service will provide.
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_VISUAL;
// Default services are invoked only if no package-specific ones are present
// for the type of AccessibilityEvent generated. This service *is*
// application-specific, so the flag isn't necessary. If this was a
// general-purpose service, it would be worth considering setting the
// DEFAULT flag.
// info.flags = AccessibilityServiceInfo.DEFAULT;
info.notificationTimeout = 100;
this.setServiceInfo(info);
}
Thanks for the help!

Android: How do I get GSM signal strength for all available network operators

I am working on a little app to check the signal strength of various network operators in my area. My current operators signal is quite unstable and I want to look into the strength of other GSM operators.
Sofar I've been using the TelephonyManager and a PhoneStateListener with the onSignalStrengthsChanged call back to get the GSM Signal strength of the current network operator, but it seems that this class only gives me info on the signal strength of the network attached to my SIM card.
I'm interested in measurement of GSM signal strength of ALL available operators. Searching the net has given vague hints on using internal android classes, but I've not yet found any good examples on this.
Any answer that can move me on to get a list of all available network operators and their signal strength are appreaciated.
Maybe these quotes and links can help you code your own solution:
1.- To get a list of available network providers (quoting How to get a list of available network providers? in full):
Since Android is open source I had a look at the sources and finally
found something called INetworkQueryService. I guess you can do the
same as the android settings implementation and interact with this
service. Some guidance through NetworkSettings.java:
onCreate starts the NetworkQueryService and binds it.
loadNetworksList() tells the service to query for network operators.
INetworkQueryServiceCallback is evaluated and if the event "EVENT_NETWORK_SCAN_COMPLETED" was raised, networksListLoaded will be
called to iterate over the available Networks.
2.- Even a quick read to NetworkSetting.java and INetworkQueryService interface, gives us an idea to achieve your goal.
Connect the service in declaration.
/**
* Service connection code for the NetworkQueryService.
* Handles the work of binding to a local object so that we can make
* the appropriate service calls.
*/
/** Local service interface */
private INetworkQueryService mNetworkQueryService = null;
/** Service connection */
private final ServiceConnection mNetworkQueryServiceConnection = new ServiceConnection() {
/** Handle the task of binding the local object to the service */
public void onServiceConnected(ComponentName className, IBinder service) {
if (DBG) log("connection created, binding local service.");
mNetworkQueryService = ((NetworkQueryService.LocalBinder) service).getService();
// as soon as it is bound, run a query.
loadNetworksList();
}
/** Handle the task of cleaning up the local binding */
public void onServiceDisconnected(ComponentName className) {
if (DBG) log("connection disconnected, cleaning local binding.");
mNetworkQueryService = null;
}
};
onCreate starts the NetworkQueryService and binds it.
Intent intent = new Intent(this, NetworkQueryService.class);
...
startService (intent);
bindService (new Intent(this, NetworkQueryService.class), mNetworkQueryServiceConnection,
Context.BIND_AUTO_CREATE);
loadNetworksList() tells the service to query for network operators.
private void loadNetworksList() {
...
// delegate query request to the service.
try {
mNetworkQueryService.startNetworkQuery(mCallback);
} catch (RemoteException e) {
}
displayEmptyNetworkList(false);
}
INetworkQueryServiceCallback is evaluated:
/**
* This implementation of INetworkQueryServiceCallback is used to receive
* callback notifications from the network query service.
*/
private final INetworkQueryServiceCallback mCallback = new INetworkQueryServiceCallback.Stub() {
/** place the message on the looper queue upon query completion. */
public void onQueryComplete(List<OperatorInfo> networkInfoArray, int status) {
if (DBG) log("notifying message loop of query completion.");
Message msg = mHandler.obtainMessage(EVENT_NETWORK_SCAN_COMPLETED,
status, 0, networkInfoArray);
msg.sendToTarget();
}
};
If the event "EVENT_NETWORK_SCAN_COMPLETED" was raised, networksListLoaded will be called to iterate over the available Networks.
private void networksListLoaded(List<OperatorInfo> result, int status) {
...
if (status != NetworkQueryService.QUERY_OK) {
...
displayNetworkQueryFailed(status);
displayEmptyNetworkList(true);
} else {
if (result != null){
displayEmptyNetworkList(false);
...
} else {
displayEmptyNetworkList(true);
}
}
}
I hope it helps. I think it's an interesting challenge so maybe I'll give it a try next time I have some spare time. Good luck!
private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallForwardingIndicatorChanged(boolean cfi) {
super.onCallForwardingIndicatorChanged(cfi);
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
//checkInternetConnection();
String callState = "UNKNOWN";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
callState = "IDLE";
break;
case TelephonyManager.CALL_STATE_RINGING:
callState = "Ringing (" + incomingNumber + ")";
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
callState = "Offhook";
break;
}
Log.i("Phone Stats", "onCallStateChanged " + callState);
super.onCallStateChanged(state, incomingNumber);
}
#Override
public void onCellLocationChanged(CellLocation location) {
String cellLocationString = location.toString();
super.onCellLocationChanged(location);
}
#Override
public void onDataActivity(int direction) {
String directionString = "none";
switch (direction) {
case TelephonyManager.DATA_ACTIVITY_IN:
directionString = "IN";
break;
case TelephonyManager.DATA_ACTIVITY_OUT:
directionString = "OUT";
break;
case TelephonyManager.DATA_ACTIVITY_INOUT:
directionString = "INOUT";
break;
case TelephonyManager.DATA_ACTIVITY_NONE:
directionString = "NONE";
break;
default:
directionString = "UNKNOWN: " + direction;
break;
}
Log.i("Phone Stats", "onDataActivity " + directionString);
super.onDataActivity(direction);
}
#Override
public void onDataConnectionStateChanged(int state,int networktype) {
String connectionState = "Unknown";
switch (state ) {
case TelephonyManager.DATA_CONNECTED :
connectionState = "Connected";
break;
case TelephonyManager.DATA_CONNECTING:
connectionState = "Connecting";
break;
case TelephonyManager.DATA_DISCONNECTED:
connectionState = "Disconnected";
break;
case TelephonyManager.DATA_SUSPENDED:
connectionState = "Suspended";
break;
default:
connectionState = "Unknown: " + state;
break;
}
super.onDataConnectionStateChanged(state);
Log.i("Phone Stats", "onDataConnectionStateChanged "
+ connectionState);
}
#Override
public void onMessageWaitingIndicatorChanged(boolean mwi) {
super.onMessageWaitingIndicatorChanged(mwi);
}
#Override
public void onServiceStateChanged(ServiceState serviceState) {
String serviceStateString = "UNKNOWN";
switch (serviceState.getState()) {
case ServiceState.STATE_IN_SERVICE:
serviceStateString = "IN SERVICE";
break;
case ServiceState.STATE_EMERGENCY_ONLY:
serviceStateString = "EMERGENCY ONLY";
break;
case ServiceState.STATE_OUT_OF_SERVICE:
serviceStateString = "OUT OF SERVICE";
break;
case ServiceState.STATE_POWER_OFF:
serviceStateString = "POWER OFF";
break;
default:
serviceStateString = "UNKNOWN";
break;
}
Log.i("Phone Stats", "onServiceStateChanged " + serviceStateString);
super.onServiceStateChanged(serviceState);
}
#Override
public void onSignalStrengthChanged(int asu) {
Log.i("Phone Stats", "onSignalStrengthChanged " + asu);
setSignalLevel( asu);
super.onSignalStrengthChanged(asu);
}
private void setSignalLevel(int level) {
int sLevel = (int) ((level / 31.0) * 100);
Log.i("signalLevel ", "" + sLevel);
}
};
As I have no 50 reputation points, here is the result of my searches about the subject :
The solution of Alejandro Colorado seems to be the good one. But the problem is that the classes used to achieve it are reserved for android system applications, i.e. apps which are signed with the same signature key as the system.
How could it be possible? I found two way to achieve this.
The first one is to ask a job at any manufacturer compagny, and sign their NDA, but eh, that's not a really good solution. Especially as the app implemented and signed with this key will only work on devices from the compagny...
The second one, much more enjoyable, but i warn you, it's not gonna be easy, is to make your own ROM. You'll have to create your application, insert it in the /system/app/ directory of your ROM and recompile it to flash your device with your new system. But there's a question i've not answered yet, is the problem of unrecognised ROM signature.
I think the best way to avoid this problem is to add your ROM signing key in the Recovery you'll be using.
That's where i am at this point, maybe you could find these research usefull, i hope so!
I'll come back later if i find some more informations for you guys. Bye.
create a PhoneStateListener and handle the onSignalStrengthChanged callback. When your app is initialized, it should give you an initial notification. This is in 1.x. in 2.x, there's an open issueabout this.

Categories

Resources