onPartialResult is always one value, even after I change the keyword? - java

hypothesis.getHypstr() is always one value, even after I change the keyword!
I am using pocketsphinx to do speech recognition, and I let the user change what to listen for. This value is stored in my shared preferences. My problem is that hypothesis.getHypstr() is only called when the previous keyword is spoken.
For example:
If it is set to default keyword (oranges and rainbows), then the recognition works fine. But, if the user changes it to "hello computer" then the onPartialResult method still only gets called when the user says hello, and hypothesis.getHypstr() is still oranges and rainbows.
onCreate:
try {
Assets assets = new Assets(MyService.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
Log.v(TAG, "SET UP DIRECTORIES STARTING LISTENING!");
mSpeechRecognizer.startListening("usersKeyword");
} catch (IOException e) {
e.printStackTrace();
Log.v(TAG, e.toString());
}
setupRecognizer()
public void setupRecognizer(File sphinxDir) {
try {
mSpeechRecognizer = defaultSetup()
.setAcousticModel(new File(sphinxDir, "en-us-ptm"))
.setDictionary(new File(sphinxDir, "cmudict-en-us.dict"))
.setBoolean("-allphone_ci", true)
.setKeywordThreshold(1e-40f)
.getRecognizer();
} catch (IOException e) {
e.printStackTrace();
}
mSpeechRecognizer.addListener(this);
mSpeechRecognizer.addKeyphraseSearch("usersKeyword", keyword.getString("keyword", "oranges and rainbows"));
}
onPartialResult:
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null) { //no one spoke
return;
}
String text = hypothesis.getHypstr();
Log.v(TAG, "TEXT: " + text + "hypothesis.getHypstr: " + hypothesis.getHypstr());
if (text.equals(keyword.getString("keyword", "oranges and rainbows"))) { //Only happens when text is oranges and rainbows, even after changing preference value!!!
Log.v(TAG, "Heard user keyword!");
mSpeechRecognizer.cancel();
mSpeechRecognizer.startListening("usersKeyword");
}
}
Why is hypothesis.getHypstr() always only one value, even after I change the value of the addKeyphraseSearch?
Thanks,
Ruchir
EDIT:
I actually stop and start the service every time the user changes their input, and so onCreate() is called every time the user changes their data.
FULL CODE:
https://gist.github.com/anonymous/47efc9c1ca08d808e0be

You do not need to destroy the service, you create it once with onCreate.
You can set the command in onStartCommand:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
recognizer.cancel();
recognizer.addKeyphraseSearch("usersKeywords", intent.getStringExtra("keyword"););
recognizer.startListening("usersKeywords");
}
From the other class which is a user of the service you start service with intent:
Intent i = new Intent(this, MyService);
i.putExtra("keyword", "hello");
startService(i);
For more details read documentation

You need to call mSpeechRecognizer.addKeyphraseSearch() every time you want to change the key phrase.

Related

Dial multiple numbers one by one programmatically | Android

I am trying to develop a feature for an app where you have a list of "codes" that you enter and that are dialed one by one. I have looked over TelephonyManager and followed a tutorial on developing a broadcast receiver with a listener for responses but it does not always work as it should.
One idea was to store all the numbers necessary in SharedPref. If the Activity (only created for the intent towards dialer) went into onStop() (meaning that above, the dialer screen was on) and then into onResume() (call ended and activity resumed), I would remove the number last dialed from the SharedPref and then, if any remained, open the dialer again. The broadcast made sure than once the state flow of the TelephonyManager was "OFFHOOK => IDLE", it would return the user to the Activity . Short story, it did not always perform as it should have.
How should I tackle the problem ?
EDIT
My curent solution was to
Create a doPhoneCall() function that would handle the intent creation and deployment itself.
#Override
protected void doPhoneCall(){
super.onResume();
wentIntoCall = false;
/** More code here for dialing */
}
Place this function into the onResume(). Even if the onResume will be called multiple times, the wentIntoCall boolean will make sure that the function won't be called multiple times.
#Override
protected void onResume() {
super.onResume();
if(wentIntoCall)
doPhoneCall();
}
Having in mind that after a call, the phone should return to its previous state, so it would return to the Activity in which we are doing are call, we will add to the activity a CallListener, and in the case of IDLE, based on the tutorial linked above, we make the wentIntoCall be true. ( The activity will go into onResume() and, upon seeing that the boolean is true, it will initialize the next call ).
case TelephonyManager.CALL_STATE_IDLE:
Log.e(TAG, "CALL_STATE_IDLE==>"+incoming_number);
if((prev_state == TelephonyManager.CALL_STATE_OFFHOOK)){
prev_state=state;
wentIntoCall = true;
//Answered Call which is ended
}
if((prev_state == TelephonyManager.CALL_STATE_RINGING)){
prev_state=state;
wentIntoCall = true;
//Rejected or Missed call
}
My final question : is this the right way to handle this functionality, or should I try to come up with another implementation of it ?
EDIT 2
Looks like my "codes", being USSD codes, are not behaving like normal phone calls.. So for normal phone calls the code above seems to work, but for dialing codes, not that much. I have "downgraded" my solution to a simple for-loop. Seems to be working fine now.
I dont know for android O , but for android 6.0 > You cant detect answer in direct way . Call no exist number and see PhoneStateListener what will trigger in one case and track successed call also.
Make public static array , add all your numbers intro array .
I made services . Insert permissions in manifest make your own action also ( NEXT_CALL for example ) .
Than easy make intent for startServices :
SharedPreferences settings;
SharedPreferences.Editor SAVES;
Intent serviceIntent = new Intent(MainActivity.this, ServiceForCalls.class);
serviceIntent.setAction("xxx.xxx.NEXT_CALL");
startService(serviceIntent);
isCalling = true;
SAVES.putBoolean( "isCalling" , isCalling );
SAVES.commit();
SAVES.apply();
You must use timeout interval about 10 sec for next call.
Heres little help func - end call and phoneState handler :
void END_CALL () throws InvocationTargetException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException {
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Class c = null;
try {
c = Class.forName(tm.getClass().getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method m = null;
try {
m = c.getDeclaredMethod("getITelephony");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
m.setAccessible(true);
Object telephonyService = m.invoke(tm); // Get the internal ITelephony object
c = Class.forName(telephonyService.getClass().getName()); // Get its class
m = c.getDeclaredMethod("endCall"); // Get the "endCall()" method
m.setAccessible(true); // Make it accessible
m.invoke(telephonyService); // invoke endCall()
if ( SIGNAL_STOP == false ) {
timerHandlerServicesStartNewNumber.postDelayed(timerRunnableServicesStartNewNumber, 1000);
}
}
private class PhoneStateChangeListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.println( Log.INFO , "RINGING" , "SERVICES%%%%%%%%%%%%%%%%RINGING%%%%%%%%%%%%%%%%%%");
wasRinging = true;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.println( Log.INFO , "OFFHOOK BROADCAST" , "SERVICES%%%%%%%%%%%%%%%%%%%%%%%%");
if (!wasRinging) {
// Start your new activity
Log.println( Log.INFO , "OFFHOOK BROADCAST" , "SERVICES%%%%%%%%%%%%%%%%%%%%%%%");
if (SIGNAL_STOP == false) {
timerHandlerServices.postDelayed(timerRunnableServices, 10000);
}
} else {
// Cancel your old activity
Log.println( Log.INFO , "OFFHOOK BROADCAST" , "SERVICES%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
}
// this should be the last piece of code before the break
wasRinging = true;
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.println( Log.INFO , "IDLE BROADCAST" , "SERVICES%%%%%%%%%%%%%%%%%IDLE%%%%%%%%%%%%%%%%%%%");
// this should be the last piece of code before the break
wasRinging = false;
break;
}
}
}
Thanks for : "meaning that above, the dialer screen was on" nice catch.
As a side note, in the Android O developer preview there is a new API which allows you to send a USSD request and register a callback to receive its results. For newer versions of Android this might meet your needs better.

How can I keep my service alive after finishing its work, waiting for data from another class?

i have a class(location2.java) that finds location for me,I use this code in my class :
What is the simplest and most robust way to get the user's current location on Android?
and I have a service that override that abstract "locationResult";Now i want my service after running its codes,service doesn't finish and stay alive for receiving location from location2.java.
appreciating any help for this.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Location2.LocationResult locate = new Location2.LocationResult() {
#Override
public void gotLocation(Location location1, Boolean Gps, Boolean Net) {
if (location1 != null) {
Log.e("Loc", String.valueOf(location1.getLatitude()));
}
try {
//this is a method that i want to be run after receiving location from location2.java
json_maker(location1, speed_computation(location1), Gps, Net);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Location2 location = new Location2();
location.getLocation(context, locate);
return Service.START_FLAG_REDELIVERY;
}
The most successful way is to use return START_STICKY.
"and if service wants to restart, multiple constants for example START_STICKY can be used.doesn't it?" - Yes, we can use.
START_STICKY
Constant to return from onStartCommand(Intent, int, int) if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Developer guide: Android

Parse: Duplicate records for the a single saveInBackground Call

I have a single incident where a complete duplicate of a entry was made into the database (the same user comment appeared twice). They had different object IDs but were otherwise the exact same. It was slower than usual to finish the posting and only happened once out of dozens of comments, so I want to say it was a Parse issue during the saveInBackground call. Even so, I expect a service like Parse to be a little more robust. As my first time working with Android though, I also can't be sure nothing is wrong on my end. Any help? Also just any criticisms? This is the method called when the user hits a comment submission button:
private void submitComment() {
String text = commentText.getText().toString().trim();
Intent intent = getIntent();
String ID = intent.getStringExtra("imageID");
String parentID = intent.getStringExtra("parent");
// Set up a progress dialog
final ProgressDialog loadingDialog = new ProgressDialog(CommentSubmitActivity.this);
loadingDialog.setMessage(getString(R.string.publishing_comment));
loadingDialog.show();
Comment comment = new Comment();
comment.setText(text);
comment.setUser((ParseUser.getCurrentUser()));
if (ID.equals("#child")) {
comment.setParent(parentID);
comment.setImage("#child");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Comment");
query.getInBackground(parentID, new GetCallback<ParseObject>() {
public void done(ParseObject parentComment, ParseException e) {
if (e == null) {
int numChild = parentComment.getInt("numChild");
parentComment.put("numChild", ++numChild);
parentComment.saveInBackground();
} else {
Log.d("numChild: ", "error");
}
}
});
} else {
comment.setImage(ID);
comment.put("numChild", 0);
ParseQuery<ParseObject> query = ParseQuery.getQuery("ImageUpload");
query.getInBackground(ID, new GetCallback<ParseObject>() {
public void done(ParseObject image, ParseException e) {
if (e == null) {
int numComments = image.getInt("numComments");
image.put("numComments", ++numComments);
image.saveInBackground();
} else {
Log.d("numComments: ", "error");
}
}
});
}
comment.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
loadingDialog.dismiss();
finish();
}
}
});
}
I encountered similar problem like yours.
I created an app where user can create account and add photo to it and list of objects (friends in my case).
Once when I was testing it user was created twice.
I went through my code and my my suspicions are connected with async calls.
I see that you use asynchronous parse api in you application so no fragment of code is waiting for response and blocking the rest of operations.
You cannot control when parse server will response.
What I did I just put all synchronous requests in my custom async code (AsyncTask in Android).
Hope that my answer somehow meeets your expectations.

Android SIP registration failed (-9 IN_PROGRESS)

Here is my registration code:
protected void initializeManagerOpen(){
consoleWrite("initializeOpen");
if(mSipManager==null) {
return;
}
SipProfile.Builder builder;
try {
builder = new SipProfile.Builder("13", "10.0.0.4");
builder.setPassword("13");
builder.setPort(5062);
builder.setProtocol("UDP");
mSipProfile = builder.build();
try {
Intent intent = new Intent();
intent.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, Intent.FILL_IN_DATA);
mSipManager.open(mSipProfile, pendingIntent, null);
mSipManager.setRegistrationListener(mSipProfile.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
mNotificationTask.endNotification();
mNotificationTask.createNotification(R.drawable.ic_stat_connecting,"Test","Connecting");
consoleWrite("Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime){
mNotificationTask.endNotification();
mNotificationTask.createNotification(R.drawable.ic_stat_connected,"Test","Connected");
consoleWrite("Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage){
mNotificationTask.endNotification();
mNotificationTask.createNotification(R.drawable.ic_stat_disconnected,"Test","Failed to connect:"+errorCode);
consoleWrite("Registration failed. Please check settings.");
consoleWrite(""+errorCode);
consoleWrite(errorMessage);
}
});
} catch (SipException e) {
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
Though sometimes it registered successfully, most time I got a error code -9:
Registration failed. Please check settings.
-9
0
I found this description on reference site:
public static final int IN_PROGRESS
The client is in a transaction and cannot initiate a new one.
Constant Value: -9 (0xfffffff7)
What does it means exactly? I don't have any other SIP application running on my phone.
PS. First time when i am trying to connect, it is working. But second time it returns -9. Maybe i not close connection correctly? I think i have problem because i am trying to close connection but it is not closing...
public void closeLocalProfile() {
if(mSipManager==null){
return;
}
try{
if(mSipProfile!=null){
mSipManager.close(mSipProfile.getUriString());
consoleWrite("mSipManager Closed - "+mSipProfile.getUriString());
}
}catch(Exception e){
consoleWrite("Failed to close local profile. - "+e);
}
}
Delete all SIP account from Call Parameter and retry :
Call App->Parameter->Call account internet
Delete all account
PS: Sorry for the name menu, my phone isn't in english
I've faced the same issue and zicos22's comment helped me to solve it. The problem starts because of unclosed SipProfiles, so you need to run closeLocalProfile() inside onPause() method (it does not work when called inside onDestroy()). Actually, i think i have to run this sip stuff in separate thread, but for now i'm just closing profile in onPause. On my android phone with ZenUI i'am able to close currently opened sip profiles manually in Settings -> Call Settings -> Phone Account Settings -> SIP accounts.

Sms ContentObserver onChange() fires multiple times

I know this question has been asked multiple times, but nobody has been able to come up with a working answer from what I have seen.
Im working on an app to intercept text messages and depending on the sending #, pop up with a custom alert. I have it working beautifully with a broadcast receiver, however if the user has goSms installed the onReceive() method is never called as goSms aborts it before it ever reaches my app.
To get around this, Im trying a content observer on content://sms/
Its working just fine, however the onChange() is called twice, with exactly the same parameters. Ive tried to check the time stamps, but they are the same, as is the type and every other parameter I have set.
From what I've seen, this is a common issue, but not one that I've seen answered anywhere.
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
querySMS();
}
protected void querySMS() {
Cursor cur = getContentResolver().query(u, null, null, null, null);
cur.moveToNext(); // this will make it point to the first record, which is the last SMS sent
String type = cur.getString(cur.getColumnIndex("type"));
String body = cur.getString(cur.getColumnIndex("body")); //content of sms
String add = cur.getString(cur.getColumnIndex("address")); //phone num
if (type.equals("1")) {
if (add.equals(Test.SENDER)) {
String[] bodys = body.split(" ", 7);
if (bodys[0].equals("test")) {
test = true;
}
cat = bodys[1];
level = bodys[2];
urgency = bodys[3];
certainty = bodys[4];
carrier = bodys[5];
message = bodys[6];
final Intent intent = new Intent(context, AlertActivity.class);
Bundle b = new Bundle();
b.putString("title", cat);
b.putString("certainty", certainty);
b.putString("urgency", urgency);
b.putString("level", level);
b.putString("message", message);
b.putBoolean("test", test);
intent.putExtras(b);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
carrierName = manager.getNetworkOperatorName();
if (carrierName.replaceAll(" ", "").equals(carrier)) {
context.startActivity(intent);
} else {
//testing
Toast.makeText(context, carrierName.replaceAll(" ", ""), Toast.LENGTH_LONG).show();
}
}
}
}
Because of the onChange() being fired twice, Im getting two alerts as well. I cannot for the life of me figure out a way around this.
If the two are identical:
store each message recv'd
compare it to previous messages recv'd
if not found, process
if found, discard the message
The life of the messages stored should be infinitesimal, a little circular buffer of 5 messages should be fine.
here is my code, it works fine for me
public class SmsObserver extends ContentObserver {
private Context context;
private static int initialPos;
private static final String TAG = "SMSContentObserver";
private static final Uri uriSMS = Uri.parse("content://sms/sent");
public SmsObserver(Handler handler, Context ctx) {
super(handler);
context = ctx;
initialPos = getLastMsgId();
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
queryLastSentSMS();
}
public int getLastMsgId() {
Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, null);
cur.moveToFirst();
int lastMsgId = cur.getInt(cur.getColumnIndex("_id"));
Log.i(TAG, "Last sent message id: " + String.valueOf(lastMsgId));
return lastMsgId;
}
protected void queryLastSentSMS() {
new Thread(new Runnable() {
#Override
public void run() {
Cursor cur =
context.getContentResolver().query(uriSMS, null, null, null, null);
if (cur.moveToNext()) {
try {
if (initialPos != getLastMsgId()) {
// Here you get the last sms. Do what you want.
String receiver = cur.getString(cur.getColumnIndex("address"));
System.out.println(" Receiver Ph no :"+receiver);
// Then, set initialPos to the current position.
initialPos = getLastMsgId();
}
} catch (Exception e) {
// Treat exception here
}
}
cur.close();
}
}).start();
}
}//End of class SmsObserver
You can save last message's id and compare it to the id of the message that is returned by cur in onChange. you then can simply disregard the message if ids are the same.
// might contain mistakes, but you'll get the idea:
protected void querySMS() {
Cursor cur = getContentResolver().query(u, null, null, null, null);
cur.moveToNext();
if (lastId == cur.getLong(cur.getColumnIndex("_id")))
return;
lastId = cur.getLong(cur.getColumnIndex("_id"));
... //continue as it was
}
However - GO SMS only prevents other app's from recieving Broadcast if the user selected this option (Recieve Settings - Disable other message notification) - so if the user does not want other apps to disturb him - I think it's good idea not to do so.
I just use SharedPreference to remark last SMS info (like: id\type ...). if it is the same, I will return.

Categories

Resources