I am planning to create an Android App that will automate sending a users response to a USSD Menu. At a click of a button, the app will send the initial code, followed by the rest of the menu inputs.
For example, the initial number is *143#, followed by 1, 1, 1, and a user PIN. I'd like to be able to automate that sequence of inputs so that the user won't have to input it on their own.
I know that in Android Oreo, they implemented a USSD Callback using the TelephonyManager, where the Android App can send a USSD Request, and then read the response given.
I am currently exploring that option and this is what I've tried so far. Heavily lifted from this StackOverflow Question.
interface UssdResultNotifiable {
void notifyUssdResult(String request, String returnMessage, int resultCode);
}
public class MainActivity extends Activity implements UssdResultNotifiable {
USSDSessionHandler hdl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onUssdSend(View view) {
hdl = new USSDSessionHandler(MainActivity.this, MainActivity.this);
hdl.doSession(((EditText) this.findViewById(R.id.ussdText)).getText().toString());
}
#Override
public void notifyUssdResult(final String request, final String returnMessage, final int resultCode) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Request was " + request + "\n response is "
+ returnMessage + "\n result code is " + resultCode, Toast.LENGTH_LONG).show();
Log.e(TAG, "ussd result hit! Response is = " + returnMessage);
hdl.doSession("1");
}
});
}
}
class USSDSessionHandler {
TelephonyManager tm;
private UssdResultNotifiable client;
private Method handleUssdRequest;
private Object iTelephony;
USSDSessionHandler(Context parent, UssdResultNotifiable client) {
this.client = client;
this.tm = (TelephonyManager) parent.getSystemService(Context.TELEPHONY_SERVICE);
try {
this.getUssdRequestMethod();
} catch (Exception ex) {
//log
}
}
private void getUssdRequestMethod() throws ClassNotFoundException, NoSuchMethodException,
InvocationTargetException, IllegalAccessException {
if (tm != null) {
Class telephonyManagerClass = Class.forName(tm.getClass().getName());
if (telephonyManagerClass != null) {
Method getITelephony = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephony.setAccessible(true);
this.iTelephony = getITelephony.invoke(tm); // Get the internal ITelephony object
Method[] methodList = iTelephony.getClass().getMethods();
this.handleUssdRequest = null;
for (Method _m : methodList)
if (_m.getName().equals("handleUssdRequest")) {
handleUssdRequest = _m;
break;
}
}
}
}
#android.support.annotation.RequiresApi(api = Build.VERSION_CODES.N)
public void doSession(String ussdRequest) {
try {
if (handleUssdRequest != null) {
handleUssdRequest.setAccessible(true);
handleUssdRequest.invoke(iTelephony, SubscriptionManager.getDefaultSubscriptionId(), ussdRequest, new ResultReceiver(new Handler()) {
#Override
protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
Object p = ussdResponse.getParcelable("USSD_RESPONSE");
if (p != null) {
Method[] methodList = p.getClass().getMethods();
for(Method m : methodList){
Log.e(TAG, "onReceiveResult: " + m.getName());
}
try {
CharSequence returnMessage = (CharSequence) p.getClass().getMethod("getReturnMessage").invoke(p);
CharSequence request = (CharSequence) p.getClass().getMethod("getUssdRequest").invoke(p);
USSDSessionHandler.this.client.notifyUssdResult("" + request, "" + returnMessage, resultCode); //they could be null
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
});
}
} catch (IllegalAccessException | InvocationTargetException e1) {
e1.printStackTrace();
}
}
}
What you get is an app that would ask for a USSD Input for the user, and once the "Send" button is hit, the USSD Response is displayed via a Toast on the notifyUssdResult function. In that same function, I send the next input in my sequence which is "1". Am I able to once again send a reply to the USSD, and the USSD takes it as the input and goes to the next menu.
However, as soon as I send the reply, the USSD menu shows up in my device and I'm unable to proceed further. I am unable to navigate the USSD Menu purely through my app, as the USSD Menu interferes with the screen and doesn't go away.
Is there any samples I can follow?
FOR EXAMPLE YOU WANT TO RUN *123# 1 then 1 then 1 then 2
so you can directly write this in string here is the code hope it helps
String s= "*123*1*1*2#"
//screen from which can get the number
if((s.startsWith("*"))&&(s.endsWith("#"))){
//if true then it is a USSD call----
callstring=s.substring(0, s.length()-1);
callstring=callstring+ Uri.encode("#");
Log.d("CALL TYPE---------->", "USSD CALL");
}else{
callstring=s;
Log.d("CALL TYPE---------->", "Not a USSD CALL");
}
Intent i=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+callstring));
startActivity(i);
Related
I am trying to make a phone number verification on android studio using java. I followed the instructions from the documentation here https://developers.google.com/identity/sms-retriever/user-consent/overview but sadly it isn't sending me an SMS code, and I am not getting any error. Below is my code:
public class OTPSMSActivity extends AppCompatActivity {
private ImageView blur;
private TextView resend;
private CustomEditText editText;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private KProgressHUD loadingBar;
private static final int SMS_CONSENT_REQUEST = 2;
// Set to an unused request code
private final BroadcastReceiver smsVerificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
Status smsRetrieverStatus = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
switch (smsRetrieverStatus.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
// Get consent intent
Intent consentIntent = extras.getParcelable(SmsRetriever.EXTRA_CONSENT_INTENT);
try {
/*Start activity to show consent dialog to user within
*5 minutes, otherwise you'll receive another TIMEOUT intent
*/
startActivityForResult(consentIntent, SMS_CONSENT_REQUEST);
Log.d("life", "Intent to send image");
} catch (ActivityNotFoundException e) {
Log.e("life", "Exception: " + e.toString());
}
break;
case CommonStatusCodes.TIMEOUT:
Log.d("life", "Timeout!");
break;
}
} else {
Log.d("life", "SmsRetriever don't matched");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otpsms);
blur = findViewById(R.id.blur);
editText = findViewById(R.id.number);
Button verify = findViewById(R.id.verify);
TextView change = findViewById(R.id.textView42);
resend = findViewById(R.id.resend);
Paper.init(this);
getBackgroundImage();
change.setOnClickListener(view -> {
finish();
});
String phoneNumber = getIntent().getStringExtra("phone");
loadingBar = KProgressHUD.create(OTPSMSActivity.this)
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("Please wait")
.setDetailsLabel("Sending sms code to your phone number.")
.setCancellable(true)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
verify.setOnClickListener(view -> {
loadingBar = KProgressHUD.create(OTPSMSActivity.this)
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("Loading")
.setDetailsLabel("Verifying code")
.setCancellable(true)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
String theCode = editText.getText().toString();
if (theCode.length() != 6){
new StyleableToast
.Builder(OTPSMSActivity.this)
.text("Invalid code.")
.iconStart(R.drawable.error)
.textColor(Color.WHITE)
.backgroundColor(getResources().getColor(R.color.error))
.show();
editText.setError("Invalid phone number.");
editText.requestFocus();
loadingBar.dismiss();
return;
}
verifyCode(theCode);
});
resend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
String phone = "+63" + phoneNumber.substring(1);
Log.d("life", phone);
Task<Void> task = SmsRetriever.getClient(this).startSmsUserConsent(phone);
task.addOnCompleteListener(listener -> {
if (listener.isSuccessful()) {
Log.d("life", "Success");
loadingBar.dismiss();
IntentFilter intentFilter = new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION);
registerReceiver(smsVerificationReceiver, intentFilter);
} else {
Exception exception = listener.getException();
exception.printStackTrace();
}
});
}
private void verifyCode(String code) {
if (code.equals(editText.getText().toString())) {
String phoneNumber = getIntent().getStringExtra("phone");
String userID = Paper.book().read("userID");
loadingBar.setDetailsLabel("Uploading number to database");
db.collection("Buyers").document(userID)
.update("phone", "+63" + phoneNumber.substring(1))
.addOnCompleteListener(task11 -> {
if (task11.isSuccessful()){
loadingBar.dismiss();
StyleableToast.makeText(OTPSMSActivity.this, "Success! Phone number updated.", Toast.LENGTH_LONG, R.style.successtoast).show();
finish();
}
});
} else {
new StyleableToast
.Builder(OTPSMSActivity.this)
.text("Code does not matched.")
.iconStart(R.drawable.error)
.textColor(Color.WHITE)
.backgroundColor(getResources().getColor(R.color.error))
.show();
loadingBar.dismiss();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SMS_CONSENT_REQUEST) {
if (resultCode == RESULT_OK) {
// Get SMS message content
String message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE);
// Extract one-time code from the message and complete verification
String oneTimeCode = parseOneTimeCode(message);
Log.d("life", "oneTimeCode: " + oneTimeCode);
//for this demo we will display it instead
editText.setText(oneTimeCode);
} else {
Log.d("life", "Error2");
}
} else {
Log.d("life", "Error1");
}
}
private String parseOneTimeCode(String message) {
//simple number extractor
return message.replaceAll("[^0-9]", "");
}
#Override
protected void onDestroy() {
super.onDestroy();
//to prevent IntentReceiver leakage unregister
unregisterReceiver(smsVerificationReceiver);
}
I want to know what am I doing wrong here.
Calling this API won't be sending you an SMS. This API listens to the SMS that you will receive on your device, ask for your permission and then retrieve it.
You should not wait for the task to complete. It is there to listen to the SMS you receive. So the first thing that you need to correct in your onCreate function:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otpsms);
...
Task<Void> task = SmsRetriever.getClient(this).startSmsUserConsent(null);
IntentFilter intentFilter = new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION);
registerReceiver(smsVerificationReceiver, intentFilter);
...
}
The phone number you are passing to SmsRetriever.getClient(this).startSmsUserConsent is the phone number of the sender. So if you know which number will send you an SMS, then pass it to this function. But if you don't know the number of the sender, keep it null.
And note that the sender phone number should not be in the phone's contacts list as mentioned in the documentation: https://developers.google.com/identity/sms-retriever/choose-an-api
So first call create this task instruction above, have it wait for your sms and then request an SMS. You could use third party platforms to send SMS messages. To test that you can send an SMS using your emulator to the emulator device.
I wrote a custom plugin to read blocks of data from an NfcA(i.e.non-ndef) tag. It seems to work fine , but only after the second scan. I am using Activity intent to derive the "NfcAdapter.EXTRA_TAG" to later use it for reading the values. I am also updating the Intents in onNewIntent(). OnNewIntent gets called after the second scan and after that I get result all the time.But in the first scan onNewIntent does not gets called, hence I end up using the Activity tag that does not have "NfcAdapter.EXTRA_TAG", hence I get null. Please see the my code below.
SE_NfcA.java(my native code for plugin)
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
String Result = "";
String TypeOfTalking = "";
if (action.contains("TalkToNFC"))
{
JSONObject arg_object = args.getJSONObject(0);
TypeOfTalking = arg_object.getString("type");
if(TypeOfTalking != "")
{
if (TypeOfTalking.contains("readBlock"))
{
if(TypeOfTalking.contains("#"))
{
try
{
String[] parts = TypeOfTalking.split("#");
int index = Integer.parseInt(parts[1]);
Result = Readblock(cordova.getActivity().getIntent(),(byte)index);
callbackContext.success(Result);
}
catch(Exception e)
{
callbackContext.error("Exception Reading "+ TypeOfTalking + "due to "+ e.toString());
return false;
}
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
return true;
}
#Override
public void onNewIntent(Intent intent) {
ShowAlert("onNewIntent called");
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
super.onNewIntent(intent);
getActivity().setIntent(intent);
savedTag = tagFromIntent;
savedIntent = intent;
}
#Override
public void onPause(boolean multitasking) {
Log.d(TAG, "onPause " + getActivity().getIntent());
super.onPause(multitasking);
if (multitasking) {
// nfc can't run in background
stopNfc();
}
}
#Override
public void onResume(boolean multitasking) {
Log.d(TAG, "onResume " + getActivity().getIntent());
super.onResume(multitasking);
startNfc();
}
public String Readblock(Intent Intent,byte block) throws IOException{
byte[] response = new byte[]{};
if(Intent != null)
{
Tag myTag = Intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if(savedTag != null)
myTag = savedTag;
if(myTag != null)
{
try{
Reader nTagReader = new Reader(myTag);
nTagReader.close();
nTagReader.connect();
nTagReader.SectorSelect(Sector.Sector0);
response = nTagReader.fast_read(block, block);
nTagReader.close();
return ConvertH(response);
}catch(Exception e){
ShowAlert(e.toString());
}
}
else
ShowAlert("myTag is null.");
}
return null;
}
private void createPendingIntent() {
if (pendingIntent == null) {
Activity activity = getActivity();
Intent intent = new Intent(activity, activity.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
}
}
private void startNfc() {
createPendingIntent(); // onResume can call startNfc before execute
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null && !getActivity().isFinishing()) {
try {
nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), getIntentFilters(), getTechLists());
if (p2pMessage != null) {
nfcAdapter.setNdefPushMessage(p2pMessage, getActivity());
}
} catch (IllegalStateException e) {
// issue 110 - user exits app with home button while nfc is initializing
Log.w(TAG, "Illegal State Exception starting NFC. Assuming application is terminating.");
}
}
}
});
}
private void stopNfc() {
Log.d(TAG, "stopNfc");
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null) {
try {
nfcAdapter.disableForegroundDispatch(getActivity());
} catch (IllegalStateException e) {
// issue 125 - user exits app with back button while nfc
Log.w(TAG, "Illegal State Exception stopping NFC. Assuming application is terminating.");
}
}
}
});
}
private Activity getActivity() {
return this.cordova.getActivity();
}
private PendingIntent getPendingIntent() {
return pendingIntent;
}
private IntentFilter[] getIntentFilters() {
return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
}
private String[][] getTechLists() {
//noinspection ToArrayCallWithZeroLengthArrayArgument
return techLists.toArray(new String[0][0]);
}
}
My index.js file
nfc.addTagDiscoveredListener(
function(nfcEvent){
console.log(nfcEvent.tag.id);
alert(nfcEvent.tag.id);
window.echo("readBlock#88");//call to plugin
},
function() {
alert("Listening for NFC tags.");
},
function() {
alert("NFC activation failed.");
}
);
SE_NfcA.js(plugin interface for interaction b/w index.js and SE_NfcA.java)
window.echo = function(natureOfTalk)
{
alert("Inside JS Interface, arg =" + natureOfTalk);
cordova.exec(function(result){alert("Result is : "+result);},
function(error){alert("Some Error happened : "+ error);},
"SE_NfcA","TalkToNFC",[{"type": natureOfTalk}]);
};
I guess I have messed up with the Intents/Activity Life-Cycle, please help. TIA!
I found a tweak/hack and made it to work.
Before making any call to read or write, I made one dummy Initialize call.
window.echo("Initialize");
window.echo("readBlock#88");//call to plugin to read.
And in the native code of the plugin, on receiving the "Initialize" token I made a startNFC() call.
else if(TypeOfTalking.equalsIgnoreCase("Initialize"))
{
startNfc();
}
I've been given access to the blogger API, I've confirmed that on my developer console.
I've also written some code to perform oAuth2 with Google Play Services using some of the code below.
String SCOPE ="oauth2:https://www.googleapis.com/auth/blogger";
GoogleAuthUtil.getToken(context, "myEmail#gmail.com", mScope);
It returns a token. As it should.
However, once I try to access the api using the token i get a error.
Unexpected response code 403 for https://www.googleapis.com/blogger/v3/users/self/blogs
Here is my request:
And here is my response:
Here is my BaseActivity.java code that gets the token:
public class BaseActivity extends Activity {
static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
static final int REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1001;
static final int REQUEST_CODE_RECOVER_FROM_AUTH_ERROR = 1002;
private static final String SCOPE ="oauth2:https://www.googleapis.com/auth/blogger";
private String mEmail; // Received from newChooseAccountIntent(); passed to getToken()
public ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDialog = new ProgressDialog(this);
login();
}
public void login() {
pickUserAccount();
}
private void pickUserAccount() {
String[] accountTypes = new String[]{"com.google"};
Intent intent = AccountPicker.newChooseAccountIntent(null, null, accountTypes, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
// Receiving a result from the AccountPicker
if (resultCode == RESULT_OK) {
mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
// With the account name acquired, go get the auth token
getToken();
} else if (resultCode == RESULT_CANCELED) {
// The account picker dialog closed without selecting an account.
// Notify users that they must pick an account to proceed.
Toast.makeText(this, "Pick Account", Toast.LENGTH_SHORT).show();
}
} else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
&& resultCode == RESULT_OK) {
// Receiving a result that follows a GoogleAuthException, try auth again
getToken();
}
}
private void getToken() {
if (mEmail == null) {
pickUserAccount();
} else {
if (isDeviceOnline()) {
new getTokenTask(BaseActivity.this, mEmail, SCOPE).execute();
} else {
Toast.makeText(this, "Not online", Toast.LENGTH_LONG).show();
}
}
}
/**
* This method is a hook for background threads and async tasks that need to
* provide the user a response UI when an exception occurs.
*/
public void handleException(final Exception e) {
// Because this call comes from the AsyncTask, we must ensure that the following
// code instead executes on the UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (e instanceof GooglePlayServicesAvailabilityException) {
// The Google Play services APK is old, disabled, or not present.
// Show a dialog created by Google Play services that allows
// the user to update the APK
int statusCode = ((GooglePlayServicesAvailabilityException)e).getConnectionStatusCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode, BaseActivity.this, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
dialog.show();
} else if (e instanceof UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
Intent intent = ((UserRecoverableAuthException)e).getIntent();
startActivityForResult(intent, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
}
}
});
}
public boolean isDeviceOnline() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}
public class getTokenTask extends AsyncTask{
Activity mActivity;
String mScope;
String mEmail;
getTokenTask(Activity activity, String name, String scope) {
this.mActivity = activity;
this.mScope = scope;
this.mEmail = name;
}
#Override
protected Object doInBackground(Object[] params) {
try {
String token = fetchToken();
Preferences.saveString(Constants.KEY_BLOGGER_TOKEN, token);
} catch (IOException e) {
// The fetchToken() method handles Google-specific exceptions,
// so this indicates something went wrong at a higher level.
// TIP: Check for network connectivity before starting the AsyncTask.
}
return null;
}
/**
* Gets an authentication token from Google and handles any
* GoogleAuthException that may occur.
*/
protected String fetchToken() throws IOException {
try {
return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
} catch (UserRecoverableAuthException userRecoverableException) {
// GooglePlayServices.apk is either old, disabled, or not present
// so we need to show the user some UI in the activity to recover.
((BaseActivity)mActivity).handleException(userRecoverableException);
} catch (GoogleAuthException fatalException) {
// Some other type of unrecoverable exception has occurred.
// Report and log the error as appropriate for your app.
}
return null;
}
}
}
I've been banging my head against the wall on this one. Anyone have any ideas?
Finally figured it out.
My build.gradle file somehow ended up having a different Application ID than my manifest. I changed it so they both match the manifest, and boom! it worked.
I am building an Android app that communicates with an Arduino board via bluetooth, I have the bluetooth code in a class of it's own called BlueComms. To connect to the device I use the following methord:
public boolean connectDevice() {
CheckBt();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d(TAG, "Connecting to ... " + device);
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
outStream = btSocket.getOutputStream();
Log.d(TAG, "Connection made.");
return true;
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "Unable to end the connection");
return false;
}
Log.d(TAG, "Socket creation failed");
}
return false;
}
private void CheckBt() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
System.out.println("Bt dsbld");
}
if (mBluetoothAdapter == null) {
System.out.println("Bt null");
}
}
This connects fine but as soon as I leave the activity I connected through it drops the connection, showing this through LogCat,
D/dalvikvm(21623): GC_CONCURRENT freed 103K, 10% free 2776K/3056K, paused 5ms+2ms, total 35ms
I can no longer connect to the device, but if I call killBt() it throws a fatal error and if I try to send data I get a 'Socket creation failed' error. My send message code is as follows:
public void sendData(String data, int recvAct) {
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "Bug BEFORE Sending stuff", e);
}
String message = data;
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "Bug while sending stuff", e);
}
}
How should I go about preventing the connection from being paused by the activity I connect with when I switch a different activity, I am switching activities with this code:
Intent myIntent = new Intent(v.getContext(), Timelapse.class);
startActivityForResult(myIntent, 0);
Many Thanks,
Rozz
Where did you store the instance of your BlueComms class? If you put it in the first activity then the class instance would have been killed when that activity was destroyed as you left it and moved to the next activity (NB activities also get destroyed on screen rotation)
So you need to find a way to keep the instance of BlueComms class alive for as long as you need it. You could pass it between activities via public properties and store it in onRetainNonConfigurationInstance() during rotations.
An easier trick is to create a class that extends Application use it as the application delegate for your app and add public property to it to store the instance of BlueComms class within it. That way the instance of BlueComms class would be alive for the lifetime of you app.
Extend Application
import android.app.Application;
public class cBaseApplication extends Application {
public BlueComms myBlueComms;
#Override
public void onCreate()
{
super.onCreate();
myBlueComms = new BlueComms();
}
}
Make your class the application delegate in the app manifest
<application
android:name="your.app.namespace.cBaseApplication"
android:icon="#drawable/icon"
android:label="#string/app_name" >
Access the base app from any of your Activities like this
((cBaseApplication)this.getApplicationContext()).myBlueComms.SomeMethod();
What I have done is, Created a singleton class for BluetoothConnection.
So socket creation happens only for one time.
When onCreate method of any activity is created, it first fetch instance of BluetoothConnection class.
Handler is used to send messages from thread in BluetoothConnection class to the corresponding activity by settings Handler.
Like:
Class MyBTConnection{
private static MyBTConnection connectionObj;
private Handler mHandler;
public MyBTConnection() { //constructor }
public static MyBTConnection getInstance() {
if(connectionObj == null) {
connectionObj = new MyBTConnection();
}
return connectionObj;
}
}
public void setHandler(Handler handler) {
mHandler = handler;
}
..... Code for Bluetooth Connection ....
to send message :
mHandler.obtainMessage(what).sendToTarget();
}
// in first activity
class MainActivity extends Activity {
private MyBTConnection connectionObj;
public onCreate(....) {
/*
* Since this is first call for getInstance. A new object
* of MyBTConnection will be created and a connection to
* remote bluetooth device will be established.
*/
connectionObj = MyBTConnection.getInstance();
connectionObj.setHandler(mHandler);
}
private Handler mHandler = new Handler(){
public void onReceive(...) {
/// handle received messages here
}
};
}
// in second activity
class SecondActivity extends Activity {
private MyBTConnection connectionObj;
public onCreate(....) {
/*
* Since this is second call for getInstance.
* Object for MyBTConnection was already created in previous
* activity. So getInstance will return that previously
* created object and in that object, connection to remote
* bluetooth device is already established so you can
* continue your work here.
*/
connectionObj = MyBTConnection.getInstance();
connectionObj.setHandler(mHandler);
}
private Handler mHandler = new Handler(){
public void onReceive(...) {
/// handle received messages here
}
};
}
I'm currently having exactly the same issue and I was thinking of opening/closing the Bluetooth socket each time an Activity asks for it. Each Activity has it's own BlueComms instance.
Because my application will became a bit complex and there will be Bluetooth threaded requests from different activities, I'm thinking that this way will become very difficult to use and troubleshoot.
Another way I came across by reading here...
https://developer.android.com/guide/components/services.html
A Service can be created on the background having a Bluetooth socket always on. All Bluetooth requests can be made using Intent towards this service. This also creates some fair amount of complexity but feels a lot more tidy and organized.
I'm currently having this dilemma, either to use a thread for each activity or use a service. I don't know which way is actually better.
When you are Selecting A device to connect and when you are click on the device list item for requesting a connection to the device use AsyncTask
and put the connect method inside the AsyncTask like this :-
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
bluetoothSocket = Globals.bluetoothDevice.createRfcommSocketToServiceRecord(Globals.DEFAULT_SPP_UUID);
bluetoothSocket.connect();
// After successful connect you can open InputStream
} catch (IOException e) {
e.printStackTrace();
}
**Here is the full code for the same problem that i have cracked :-**
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lablelexconnected.setText("Connecting ...");
bdDevice = arrayListBluetoothDevices.get(position);
//bdClass = arrayListBluetoothDevices.get(position)
// Toast.makeText(getApplicationContext()," " + bdDevice.getAddress(),Toast.LENGTH_SHORT).show();
Log.i("Log", "The dvice : " + bdDevice.toString());
bdDevice = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
Globals.bluetoothDevice = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
System.out.println("Device in GPS Settings : " + bdDevice);
// startService(new Intent(getApplicationContext(),MyService.class));
/* Intent i = new Intent(GpsSettings.this, MyService.class);
startService(i);*/
// finish();
// connectDevice();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
bluetoothSocket = Globals.bluetoothDevice.createRfcommSocketToServiceRecord(Globals.DEFAULT_SPP_UUID);
bluetoothSocket.connect();
// After successful connect you can open InputStream
InputStream in = null;
in = bluetoothSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
br = new BufferedReader(isr);
while (found == 0) {
String nmeaMessage = br.readLine();
Log.d("NMEA", nmeaMessage);
// parse NMEA messages
sentence = nmeaMessage;
System.out.println("Sentence : " + sentence);
if (sentence.startsWith("$GPRMC")) {
String[] strValues = sentence.split(",");
System.out.println("StrValues : " + strValues[3] + " " + strValues[5] + " " + strValues[8]);
if (strValues[3].equals("") && strValues[5].equals("") && strValues[8].equals("")) {
Toast.makeText(getApplicationContext(), "Location Not Found !!! ", Toast.LENGTH_SHORT).show();
} else {
latitude = Double.parseDouble(strValues[3]);
if (strValues[4].charAt(0) == 'S') {
latitude = -latitude;
}
longitude = Double.parseDouble(strValues[5]);
if (strValues[6].charAt(0) == 'W') {
longitude = -longitude;
}
course = Double.parseDouble(strValues[8]);
// Toast.makeText(getApplicationContext(), "latitude=" + latitude + " ; longitude=" + longitude + " ; course = " + course, Toast.LENGTH_SHORT).show();
System.out.println("latitude=" + latitude + " ; longitude=" + longitude + " ; course = " + course);
// found = 1;
NMEAToDecimalConverter(latitude, longitude);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
I'm trying to integrate the Twilio client into a larger application. Everything seems to work fine until I call device.connect(parameters, connectionListener). I get the 31100 Generic Malformed Request error and that's it.
On the same device, using the same Twilio account and the same Twilio application, the sample code supplied with the Twilio Android SDK (MonkeyPhone) works perfectly.
I can't find any more details about what the error means or what are the possible causes. While I'm assuming that I'm sending invalid data, I don't see how is that possible. The Capability Token is OK, I've verified it against the one generated in the MonkeyPhone sample app. Creating a Device works fine, no errors. The error is thrown even when I'm not sending any parameters in the connect() method. The onConnecting() method of the ConnectionListener gets called, but then the onDisconnected(Connection inConnection, int inErrorCode, String inErrorMessage) is called with the Malformed Request error.
The code for the Voice TwiML is working fine, it's just a simple PHP script generating the most simple <Dial> verb possible:
<Response>
<Dial>someone</Dial>
</Response>
Other specific information... I'm running another service in my application, used to do various other operations. Could this interfere in some way? Also, I'm using a trial account and I'm living in Romania, where calling real phone numbers is not supported (but I'm not using phone numbers anyway). Could this affect me in any way?
I apologize in advance for throwing the huge wall of code, but I hope a second pair of eyes can spot something wrong. This is the version of the code most similar to the MonkeyPhone sample. The only difference is that I'm using an AsyncTask to get the capability token (the JsonAsyncRequestWithError class.
public class MonkeyPhone implements Twilio.InitListener, DeviceListener {
private static final String TAG = "MonkeyPhone";
private Context context;
private Device device;
private Connection connection;
public MonkeyPhone(Context context) {
this.context = context;
Twilio.initialize(context, this /* Twilio.InitListener */);
}
#Override
/* Twilio.InitListener method */
public void onInitialized() {
Log.d(TAG, "Twilio SDK is ready");
// the Emulator has a somewhat unique "product" name
String clientName = "doug";
HttpGet get = new HttpGet("http://teamphoenix.zzl.org/capability.php?ClientName=" + clientName);
JsonAsyncRequestWithError asyncRequestWithError = new JsonAsyncRequestWithError(context, "test", new AsyncRequestWithErrorListener() {
#Override
public void onResult(AsyncRequestResponse response, Object destination) {
createDevice(response.getMessage());
}
#Override
public void onErrorResult(AsyncRequestResponse response, Object destination) {
}
});
asyncRequestWithError.execute(get);
}
public void createDevice(String token) {
try {
device = Twilio.createDevice(token, this /* DeviceListener */);
Intent intent = new Intent(context, SpringshotPhoneActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
device.setIncomingIntent(pendingIntent);
} catch (Exception e) {
Log.e(TAG, "", e);
}
}
#Override
/* Twilio.InitListener method */
public void onError(Exception e) {
Log.e(TAG, "Twilio SDK couldn't start: " + e.getLocalizedMessage());
}
#Override
/* DeviceListener method */
public void onStartListening(Device inDevice) {
Log.i(TAG, "Device is now listening for incoming connections");
}
#Override
/* DeviceListener method */
public void onStopListening(Device inDevice) {
Log.i(TAG, "Device is no longer listening for incoming connections");
}
#Override
/* DeviceListener method */
public void onStopListening(Device inDevice, int inErrorCode, String inErrorMessage) {
Log.i(TAG, "Device is no longer listening for incoming connections due to error " + inErrorCode + ": " + inErrorMessage);
}
#Override
/* DeviceListener method */
public boolean receivePresenceEvents(Device inDevice) {
return false; // indicate we don't care about presence events
}
#Override
/* DeviceListener method */
public void onPresenceChanged(Device inDevice, PresenceEvent inPresenceEvent) {
}
public void connect(String phoneNumber) {
Map<String, String> parameters = new HashMap<String, String>(1);
parameters.put("PhoneNumber", phoneNumber);
/// ---------------- THIS IS THE CALL THAT FAILS ------------------------------------//
connection = device.connect(parameters, null /* ConnectionListener */);
if (connection == null)
Log.w(TAG, "Failed to create new connection");
}
public void disconnect() {
if (connection != null) {
connection.disconnect();
connection = null;
}
}
public void handleIncomingConnection(Device inDevice, Connection inConnection) {
Log.i(TAG, "Device received incoming connection");
if (connection != null)
connection.disconnect();
connection = inConnection;
connection.accept();
}
#Override
protected void finalize() {
if (connection != null)
connection.disconnect();
if (device != null)
device.release();
}
}
Thank you very much!
I figured out the problem. Apparently, I had to read the InputStream from the server using the UTF-8 encoding (even if there are no special characters in the token).
char[] buf = new char[1024];
InputStream is = response.getEntity().getContent();
StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(is, "UTF-8");
int bin;
while ((bin = in.read(buf, 0, buf.length)) >= 0) {
out.append(buf, 0, bin);
}
return out.toString();