Recieving data from Android watch to phone - android

I am trying text transfer from watch to phone and phone to watch. I am able to send the data from both the devices to each other, and my watch is able to receive the data too.
There seems to be some problem in my Receive_Data_Phone class. It doesn't detect any data which i am sending through watch.
I have shared the code and Logcat Output.
Recieve_Data.java
public class Recieve_Data extends WearableListenerService {
private static final String TAG = "####";
private GoogleApiClient mGoogleApiClient;
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(
Wearable.API).build();
mGoogleApiClient.connect();
System.out.println("Inside RecieveData onCreate()");
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
final List<DataEvent> events = FreezableUtils
.freezeIterable(dataEvents);
dataEvents.close();
System.out.println("Inside OnDataChanged()");
if (!mGoogleApiClient.isConnected()) {
ConnectionResult connectionResult = mGoogleApiClient
.blockingConnect(30, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(TAG,"WEAR :: Service failed to connect to GoogleApiClient.");
return;
}
} else {
Log.e(TAG,"WEAR :: Service connected to GoogleApiClient.");
}
for (DataEvent event : events) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
String path = event.getDataItem().getUri().getPath();
Log.d(TAG, "DataEvent.TYPE_CHANGED, path = " + path);
/* if (Constants.PATH_SERVER_RESPONSE.equals(path)) {
// Get the data out of the event
DataMapItem dataMapItem = DataMapItem.fromDataItem(event
.getDataItem());
final String responseString = dataMapItem.getDataMap()
.getString(Constants.KEY_TITLE);
Log.d(TAG, "DataEvent notif responseString: "
+ responseString);
Intent intent = new Intent("my-event");
intent.putExtra("message", responseString);
LocalBroadcastManager.getInstance(this).sendBroadcast(
intent);
}
*/
if (Constant_Vars.PATH_OBJECTIVE.equals(path)) {
DataMapItem dataMapItem = DataMapItem.fromDataItem(event
.getDataItem());
String msg = dataMapItem.getDataMap().getString(
Constant_Vars.KEY_OBJECTIVE);
int message = Integer.parseInt(msg);
Log.d(TAG, "WEAR:: String " + message);
} else {
Log.d(TAG, "Unrecognized path: " + path);
}
}
}
}
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.d(TAG, "MOBILE:: onMessageReceived messageEvent path: "
+ messageEvent.getPath());
if (messageEvent.getPath().equals(Constant_Vars.PATH_OBJECTIVE)) {
Toast.makeText(getBaseContext(), "Service Working",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Unknown request",
Toast.LENGTH_SHORT).show();
}
}
}
Receive_Data_Phone.java
public class Recieve_Data_Phone extends WearableListenerService {
private static final String TAG = "####";
private GoogleApiClient mGoogleApiClient;
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(
Wearable.API).build();
mGoogleApiClient.connect();
System.out.println("Inside RecieveData onCreate()");
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
final List<DataEvent> events = FreezableUtils
.freezeIterable(dataEvents);
dataEvents.close();
System.out.println("Inside OnDataChanged()");
if (!mGoogleApiClient.isConnected()) {
ConnectionResult connectionResult = mGoogleApiClient
.blockingConnect(30, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(TAG,"PHONE :: Service failed to connect to GoogleApiClient.");
return;
}
} else {
Log.e(TAG,"PHONE :: Service connected to GoogleApiClient.");
}
for (DataEvent event : events) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
String path = event.getDataItem().getUri().getPath();
Log.d(TAG, "DataEvent.TYPE_CHANGED, path = " + path);
/* if (Constants.PATH_SERVER_RESPONSE.equals(path)) {
// Get the data out of the event
DataMapItem dataMapItem = DataMapItem.fromDataItem(event
.getDataItem());
final String responseString = dataMapItem.getDataMap()
.getString(Constants.KEY_TITLE);
Log.d(TAG, "DataEvent notif responseString: "
+ responseString);
Intent intent = new Intent("my-event");
intent.putExtra("message", responseString);
LocalBroadcastManager.getInstance(this).sendBroadcast(
intent);
}
*/
if (Constant_Vars.PATH_FLAG.equals(path)) {
DataMapItem dataMapItem = DataMapItem.fromDataItem(event
.getDataItem());
String msg = dataMapItem.getDataMap().getString(
Constant_Vars.KEY_FLAG);
//int message = Integer.parseInt(msg);
Log.d(TAG, "PHONE:: String " + msg);
} else {
Log.d(TAG, "Unrecognized path: " + path);
}
}
}
}
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.d(TAG, "MOBILE:: onMessageReceived messageEvent path: "
+ messageEvent.getPath());
if (messageEvent.getPath().equals(Constant_Vars.PATH_FLAG)) {
Toast.makeText(getBaseContext(), "Service Working",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Unknown request",
Toast.LENGTH_SHORT).show();
}
}
}

i think, you may send the same data item, try to add a key-value, like
dataMap.putLong("timestamp", System.currentMillion())
it may work
the reason is : if you send the same data item, google service will not detect the data item is changed, so it will not notify onDataChanged() Method

Related

BroadcastReceiver is not called from service

I am starting a service from fragment and passing some data to it and from service I am calling the PubNub for notification then after showing the notification I am sending the sendbroadcast but while sending the broadcast it is not getting receive in activity page.
Activity
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
} else if (intent.getAction().equals("sample-event")) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("Pubnub Message", "Got message: " + message);
}
}
};
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction("sample-event");
this.registerReceiver(mMessageReceiver, filter);
}
Fragment
Intent pubBunintent = new Intent(mContext,Pubnub.class);
pubBunintent.putExtra("AuthKeyArray",AuthkeyArray);
pubBunintent.putExtra("channelKeyArray",ChannelArray);
mContext.startService(pubBunintent);
Service
public class Pubnub extends Service {
private ArrayList<String> Auth;
private ArrayList<String> Channel;
private String PubNubSubscribeKey = "key";
private String PubNubPublishKey = "key";
private Context mContext = this;
#Override
public void onCreate() {
super.onCreate();
StartPubnub();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Auth = intent.getStringArrayListExtra("AuthKeyArray");
Channel = intent.getStringArrayListExtra("channelKeyArray");
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void StartPubnub() {
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey(PubNubSubscribeKey);
pnConfiguration.setPublishKey(PubNubPublishKey);
pnConfiguration.setSecure(true);
pnConfiguration.setConnectTimeout(10000);
pnConfiguration.setAuthKey(Auth.get(0));
PubNub pubnub = new PubNub(pnConfiguration);
// Grant PAM Permissions for channel and auth_key, User Level Grant
pubnub.grant()
.channels(Channel)
.authKeys(Auth) // the keys we are provisioning
.write(true) // allow those keys to write (false by default)
.read(true) // allow keys to read the subscribe feed (false by default)
.ttl(0)// how long those keys will remain valid (0 for eternity)
.async(new PNCallback<PNAccessManagerGrantResult>() {
#Override
public void onResponse(PNAccessManagerGrantResult result, PNStatus status) {
// PNAccessManagerGrantResult is a parsed and abstracted response from server
Log.d("pubnub", "onResponse: grant " + status.toString());
}
});
pubnub.addListener(new SubscribeCallback() {
#Override
public void status(PubNub pubnub, PNStatus status) {
if (status.getOperation() != null) {
switch (status.getOperation()) {
case PNSubscribeOperation:
case PNUnsubscribeOperation:
switch (status.getCategory()) {
case PNConnectedCategory:
Log.d("pubnub", "onResponse: connected ");
case PNReconnectedCategory:
Log.d("pubnub", "onResponse: reconnected ");
break;
case PNDisconnectedCategory:
case PNUnexpectedDisconnectCategory:
pubnub.reconnect();
break;
case PNAccessDeniedCategory:
case PNBadRequestCategory:
Log.d("pubnub", "onResponse: bad ");
pubnub.reconnect();
break;
default:
Log.d("pubnub", "onResponse: bad ");
pubnub.reconnect();
}
case PNHeartbeatOperation:
if (status.isError()) {
} else {
}
break;
default: {
}
}
} else {
status.getCategory();
}
}
#Override
public void message(PubNub pubnub, PNMessageResult message) {
if (message.getChannel() != null) {
Log.d("Pubnub", "message: " + message.toString() + "Channel" + message.getChannel());
NotificationCompat.Builder builder;
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
JsonObject jsonObject = new JsonObject();
JsonElement pushMessage;
jsonObject = message.getMessage().getAsJsonObject();
pushMessage = jsonObject.get("message");
builder = new NotificationCompat.Builder(mContext);
builder.setContentTitle("Sample")
.setContentText(pushMessage.toString())
.setSmallIcon(R.drawable.ic_notification);
notificationManager.notify(0, builder.build());
Constant.PushnoteReceived = true;
Intent intent = new Intent("sample-event");
intent.putExtra("message", pushMessage.toString());
//Put your all data using put extra
sendBroadcast(intent);
} else {
Log.d("Pubnub", "message complete: " + message.toString() + "Subscription" + message.getSubscription());
Log.d("Pubnub", "message: " + message.getMessage());
Log.d("Pubnub", "Time token: " + message.getTimetoken());
}
}
#Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
}
});
//subscribe
pubnub.subscribe().channels(Channel).execute();
// Adding Device to Channel: Enable push notifications on provided set of channels.
pubnub.addPushNotificationsOnChannels()
.pushType(PNPushType.GCM)
.channels(Channel)
.deviceId("com.sample.deviceTokenKey")
.async(new PNCallback<PNPushAddChannelResult>() {
#Override
public void onResponse(PNPushAddChannelResult result, PNStatus status) {
// handle response.
if (status.isError()) {
Log.d("pubnub", "onResponse: push note ERROR");
Log.d("pubnub", "onResponse: push " + status.toString());
} else {
Log.d("pubnub", "onResponse: push " + status.toString());
}
}
});
}
}

Google Play Services chrash when using Android Nearby Connections

I try to implement a small test application for Googles Nearby Connections API. Unfortunately on 2 of 3 tested devices Google Play Services chrash when discovering or advertising. (OnePlus One, Android 6.1; Acer Iconia, Android 4.4)
I see other devices, but when i connect to one of them play service crash (only my Honor 8 keeps on working). It says the connection is suspendend with error code 1. According to Google this means "A suspension cause informing that the service has been killed."
Maybe some of you could help. I made this code based on this tutorial.
Code without imports:
MainActivity.java
package com.example.steffen.nearbyconnectionsdemo;
public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener,
Connections.ConnectionRequestListener,
Connections.MessageListener,
Connections.EndpointDiscoveryListener {
// Identify if the device is the host
private boolean mIsHost = false;
GoogleApiClient mGoogleApiClient = null;
Button bt_ad, bt_search, bt_send;
TextView tv_status;
CheckBox checkBox;
Context c;
String globalRemoteEndpointId = "";
EditText editText;
final int MY_PERMISSIONS_REQUEST = 666;
private static int[] NETWORK_TYPES = {ConnectivityManager.TYPE_WIFI,
ConnectivityManager.TYPE_ETHERNET};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c = this;
checkPermisson();
editText = (EditText) findViewById(R.id.editText);
bt_ad = (Button) findViewById(R.id.bt_ad);
bt_ad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bt_search.setEnabled(false);
startAdvertising();
}
});
bt_search = (Button) findViewById(R.id.bt_search);
bt_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startDiscovery();
}
});
bt_send = (Button) findViewById(R.id.bt_send);
bt_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "message: " + editText.getText().toString();
Toast.makeText(c, "Sending: " + message, Toast.LENGTH_SHORT).show();
byte[] payload = message.getBytes();
Nearby.Connections.sendReliableMessage(mGoogleApiClient, globalRemoteEndpointId, payload);
}
});
tv_status = (TextView) findViewById(R.id.tv_status);
checkBox = (CheckBox) findViewById(R.id.checkBox);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Nearby.CONNECTIONS_API)
.build();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private boolean isConnectedToNetwork() {
ConnectivityManager connManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
for (int networkType : NETWORK_TYPES) {
NetworkInfo info = connManager.getNetworkInfo(networkType);
if (info != null && info.isConnectedOrConnecting()) {
return true;
}
}
return false;
}
private void startAdvertising() {
if (!isConnectedToNetwork()) {
// Implement logic when device is not connected to a network
tv_status.setText("No Network");
return;
}
// Identify that this device is the host
mIsHost = true;
checkBox.setChecked(mIsHost);
// Advertising with an AppIdentifer lets other devices on the
// network discover this application and prompt the user to
// install the application.
List<AppIdentifier> appIdentifierList = new ArrayList<>();
appIdentifierList.add(new AppIdentifier(getPackageName()));
AppMetadata appMetadata = new AppMetadata(appIdentifierList);
// The advertising timeout is set to run indefinitely
// Positive values represent timeout in milliseconds
long NO_TIMEOUT = 0L;
String name = null;
Nearby.Connections.startAdvertising(mGoogleApiClient, name, appMetadata, NO_TIMEOUT,
this).setResultCallback(new ResultCallback<Connections.StartAdvertisingResult>() {
#Override
public void onResult(Connections.StartAdvertisingResult result) {
if (result.getStatus().isSuccess()) {
// Device is advertising
tv_status.setText("Advertising");
} else {
int statusCode = result.getStatus().getStatusCode();
// Advertising failed - see statusCode for more details
tv_status.setText("Error: " + statusCode);
}
}
});
}
private void startDiscovery() {
if (!isConnectedToNetwork()) {
// Implement logic when device is not connected to a network
tv_status.setText("No Network");
return;
}
String serviceId = getString(R.string.service_id);
// Set an appropriate timeout length in milliseconds
long DISCOVER_TIMEOUT = 1000L;
// Discover nearby apps that are advertising with the required service ID.
Nearby.Connections.startDiscovery(mGoogleApiClient, serviceId, DISCOVER_TIMEOUT, this)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
// Device is discovering
tv_status.setText("Discovering");
} else {
int statusCode = status.getStatusCode();
// Advertising failed - see statusCode for more details
tv_status.setText("Error: " + statusCode);
}
}
});
}
#Override
public void onEndpointFound(final String endpointId, String deviceId,
String serviceId, final String endpointName) {
// This device is discovering endpoints and has located an advertiser.
// Write your logic to initiate a connection with the device at
// the endpoint ID
Toast.makeText(this, "Found Device: " + serviceId + ", " + endpointName + ". Start Connection Try", Toast.LENGTH_SHORT).show();
connectTo(endpointId, endpointName);
}
private void connectTo(String remoteEndpointId, final String endpointName) {
// Send a connection request to a remote endpoint. By passing 'null' for
// the name, the Nearby Connections API will construct a default name
// based on device model such as 'LGE Nexus 5'.
tv_status.setText("Connecting");
String myName = null;
byte[] myPayload = null;
Nearby.Connections.sendConnectionRequest(mGoogleApiClient, myName,
remoteEndpointId, myPayload, new Connections.ConnectionResponseCallback() {
#Override
public void onConnectionResponse(String remoteEndpointId, Status status,
byte[] bytes) {
if (status.isSuccess()) {
// Successful connection
tv_status.setText("Connected to " + endpointName);
globalRemoteEndpointId = remoteEndpointId;
} else {
// Failed connection
tv_status.setText("Connecting failed");
}
}
}, this);
}
#Override
public void onConnectionRequest(final String remoteEndpointId, String remoteDeviceId,
final String remoteEndpointName, byte[] payload) {
if (mIsHost) {
byte[] myPayload = null;
// Automatically accept all requests
Nearby.Connections.acceptConnectionRequest(mGoogleApiClient, remoteEndpointId,
myPayload, this).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
String statusS = "Connected to " + remoteEndpointName;
Toast.makeText(c, statusS,
Toast.LENGTH_SHORT).show();
tv_status.setText(statusS);
globalRemoteEndpointId = remoteEndpointId;
} else {
String statusS = "Failed to connect to: " + remoteEndpointName;
Toast.makeText(c, statusS,
Toast.LENGTH_SHORT).show();
tv_status.setText(statusS);
}
}
});
} else {
// Clients should not be advertising and will reject all connection requests.
Nearby.Connections.rejectConnectionRequest(mGoogleApiClient, remoteEndpointId);
}
}
#Override
public void onMessageReceived(String endpointId, byte[] payload, boolean b) {
String message = payload.toString();
Toast.makeText(this, "Received from " + endpointId + ": " + message, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View view) {
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
tv_status.setText("Connection suspended because of " + i);
mGoogleApiClient.reconnect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
tv_status.setText("Connection Failed");
}
#Override
public void onEndpointLost(String s) {
tv_status.setText("Endpoint lost: " + s);
}
#Override
public void onDisconnected(String s) {
tv_status.setText("Disconnected: " + s);
}
public void checkPermisson(){
Toast.makeText(c, "Check permission", Toast.LENGTH_SHORT).show();
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_NETWORK_STATE}, MY_PERMISSIONS_REQUEST);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
Toast.makeText(c, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(c, "Permission not granted, app may fail", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}

Android SipManager registration failed

I'm following Google's guidelines to create in app SIP calls as in https://developer.android.com/guide/topics/connectivity/sip.html
I created a test account on sip.zadarma.com which works with a SIP client I downloaded from the Google Play however when I try to register it in my app I get:
onRegistrationFailed errorCode = -4 errorMessage: registration not running
onRegistrationFailed errorCode = -9 errorMessage: 0
#Override
protected void onResume() {
super.onResume();
if (mNumberKeyedIn == null)
mNumberKeyedIn = "";
if (hasSIPPermissions()) {
initializeSIP();
} else {
requestSIPPermission();
}
}
#Override
public void onPause() {
super.onPause();
closeLocalProfile();
}
public void closeLocalProfile() {
if (mSipManager == null) {
return;
}
try {
if (mSipProfile != null) {
mSipManager.close(mSipProfile.getUriString());
if (mSipManager.isRegistered(mSipProfile.getProfileName()))
mSipManager.unregister(mSipProfile, null);
}
} catch (Exception e) {
Log.d(TAG, "Failed to close local profile.", e);
}
}
private void initializeSIP() {
if (callReceiver == null) {
IntentFilter filter = new IntentFilter();
filter.addAction("com.xxxx.android.apps.xxxx.activity.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
}
try {
if (mSipManager == null) {
mSipManager = SipManager.newInstance(this);
if (!SipManager.isVoipSupported(this)) {
Toast.makeText(this, getString(R.string.sip_not_supported), Toast.LENGTH_SHORT).show();
return;
}
if (SipManager.isSipWifiOnly(this)) {
Toast.makeText(this, getString(R.string.sip_wifi_only), Toast.LENGTH_SHORT).show();
}
}
if (mSipProfile != null) {
closeLocalProfile();
}
SipProfile.Builder builder = new SipProfile.Builder(BuildConfig.SIP_USERNAME, BuildConfig.SIP_DOMAIN);
builder.setPassword(BuildConfig.SIP_PASSWORD);
//builder.setProtocol("TCP");
//builder.setAuthUserName(BuildConfig.SIP_USERNAME);
//builder.setPort(5060);
//builder.setOutboundProxy(BuildConfig.SIP_OUTBOUND_PROXY);
builder.setAutoRegistration(true);
mSipProfile = builder.build();
Intent intent = new Intent();
intent.setAction("com.xxxx.android.apps.xxxx.activity.INCOMING_CALL");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);
mSipManager.open(mSipProfile, pendingIntent, null);
mSipManager.setRegistrationListener(mSipProfile.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus(getString(R.string.sip_registering), R.drawable.circle_orange, false);
Log.d(TAG, "onRegistering " + localProfileUri);
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus(getString(R.string.sip_ready), R.drawable.circle_green, true);
Log.d(TAG, "onRegistrationDone " + localProfileUri + " expiryTime = " + expiryTime);
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus(getString(R.string.sip_registration_failed), R.drawable.circle_red, false);
Log.e(TAG, "onRegistrationFailed " + localProfileUri + " errorCode = " + errorCode + " errorMessage: " + errorMessage);
}
});
} catch (ParseException e) {
e.printStackTrace();
Toast.makeText(this, getString(R.string.sip_not_configured), Toast.LENGTH_SHORT).show();
} catch (SipException e) {
e.printStackTrace();
Toast.makeText(this, getString(R.string.oops_something_went_wrong_short), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, getString(R.string.sip_not_supported), Toast.LENGTH_SHORT).show();
}
}
Any help will be much appreciated.
Following solutions should be tried before to test your Registration server before even looking into code for SipClient.
Try runnig any VoIP SoftPhone client to check your server, if its not working then debug that first i.e. PortNo/IP address issue.
If step one is working then try running Wireshark on server to track reply from incoming REGISTRATION Request from client.
Although from "Error logs " from your text means i.e. IP address is pingable but Registration Port No is not opened.
I don't think this is code issue. It must be your setup issue for sure.

Speech recognition onBeginningOfSpeech and onEndOfSpeech executing without any time lapse

I am trying to have a speech recognition build into my app and I am seeing that onBeginningOfSpeech and onEndOfSpeech are getting fired within the space of 1 second.
Also, when i finish speaking, the speech recognition ends immediately after I give a gap. Normally, the ASR would take about 3-5 seconds wait time before stopping speech recognition.
This code is actually messing up the rest of the speech recognition even on other apps on my phone.
Has there been a case like this?
This is how my code looks like.
Here is my onCreate method for my service. I am using a service to call the Speech recognition
#Override
public void onCreate() {
super.onCreate();
createSR();
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
mSpeechRecognizerIntent.putExtra("android.speech.extra.DICTATION_MODE", true);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
}
Here is the recognition listener code.
protected class SpeechRecognitionListener implements RecognitionListener {
private static final String TAG = "SRecognitionListener";
private boolean isUserSpeaking;
private long userSpokeAt=-1;
private long userStoppedSpeakingAt = -1;
private String completeSegment;
private String recognizingSegment;
private ArrayList<String> recognizedSegments;
#Override
public void onBeginningOfSpeech() {
Log.d(TAG, "onBeginingOfSpeech"); //$NON-NLS-1$
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
Log.d(TAG, "onEndOfSpeech"); //$NON-NLS-1$
}
#Override
public void onError(int error) {
Log.d(TAG, "onError: " + error);
if (error == SpeechRecognizer.ERROR_NO_MATCH) {
return;
}
mIsListening = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try {
mServerMessenger.send(message);
} catch (RemoteException e) {
}
Log.d(TAG, "error = " + error); //$NON-NLS-1$
}
#Override
public void onEvent(int eventType, Bundle params) {
}
/* TODO
* There needs to be a boolean variable that would make sure that the translated message from the partialResults would be a fresh message by refreshing the entire data in the bundle data
* Replace the recognizingSegment to have an empty string before doing anything
* */
#Override
public void onPartialResults(Bundle partialResults) {
ArrayList<String> matches = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (matches != null && matches.size() != 0) {
Log.d(TAG, "onPartialResults: " + matches.get(0));
partialBundleData = partialResults;
String nextPartResult=matches.get(0);
if (!recognizingSegment.equals("")){
String[] nextPartWords = nextPartResult.split(" ");
String[] recWords;
String previousSegments="";
recWords = recognizingSegment.split(" "); //The last recognized segment
if (recognizedSegments.size()>0){
previousSegments=mergeSegments(recognizedSegments);
}
if (nextPartWords.length+2>=recWords.length){ //Most definitely the same segment
Log.d(TAG, "onPartialResults: matching "+recognizingSegment+" with "+nextPartResult);
if (doWordsMatch(recWords,nextPartWords)) { //Since the words match this is probably the same segment
recognizingSegment = nextPartResult;
partialResult = previousSegments + " " + recognizingSegment;
Log.d(TAG, "onPartialResults: Same segment - " + partialResult);
partialResults.putString("PartialSentence", partialResult);
}else{ //Since the words don't match this is probably a new segment
recognizedSegments.add(recognizingSegment);
partialResult=previousSegments+" "+recognizingSegment+" "+nextPartResult;
Log.d(TAG, "onPartialResults: New segment - " + partialResult);
partialResults.putString("PartialSentence",partialResult);
recognizingSegment=nextPartResult;
}
}else{ //This must be a new segment
Log.d(TAG, "onPartialResults: matching "+recognizingSegment+" with "+nextPartResult);
if (!doWordsMatch(recWords, nextPartWords)) { //Since the words don't match this is probably a new segment
recognizedSegments.add(recognizingSegment);
partialResult = previousSegments + " " + recognizingSegment + " " + nextPartResult;
Log.d(TAG, "onPartialResults: New segment - " + partialResult);
partialResults.putString("PartialSentence", partialResult);
recognizingSegment = nextPartResult;
}else{ //Since the words match this is probably the same segment
recognizingSegment = nextPartResult;
partialResult = previousSegments + " " + recognizingSegment;
Log.d(TAG, "onPartialResults: Same segment - " + partialResult);
partialResults.putString("PartialSentence", partialResult);
}
}
}else{
partialResult=nextPartResult;
Log.d(TAG, "onPartialResults: First segment - " + partialResult);
recognizingSegment=nextPartResult;
partialResults.putString("PartialSentence",nextPartResult);
}
Message message = new Message();
message.what = ASRService.MSG_RECOGNIZER_PART_RESULT;
message.setData(partialResults);
sendMessageToClients(message);
} else {
Log.d(TAG, "onPartialResults: No Results");
}
}
private boolean doWordsMatch(String[] phraseA, String[] phraseB){
int noOfWordsToMatch=3;
if (phraseA.length<noOfWordsToMatch){
noOfWordsToMatch=phraseA.length;
}
if (phraseB.length<noOfWordsToMatch){
noOfWordsToMatch=phraseB.length;
}
boolean wordsMatch=false;
int noOfMatchingWords=0;
for (int i=0; i<noOfWordsToMatch; i++){
if (phraseA[i].equals(phraseB[i])){
noOfMatchingWords++;
}
}
Log.d(TAG, "onPartialResults: noOfMatchingWords - "+noOfMatchingWords);
if (noOfMatchingWords>=2 || noOfMatchingWords>=noOfWordsToMatch){
wordsMatch=true;
}
return wordsMatch;
}
private String mergeSegments(ArrayList<String> segments){
StringBuilder mergedSegments=new StringBuilder();
for (String segment: segments){
mergedSegments.append(segment+" ");
}
return mergedSegments.toString().trim();
}
#Override
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
Message message = new Message();
message.what = ASRService.MSG_RECOGNIZER_STARTED_LISTENING;
sendMessageToClients(message);
userSpokeAt=-1;
completeSegment ="";
recognizingSegment="";
recognizedSegments=new ArrayList<>();
}
#Override
public void onResults(Bundle results) {
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (matches != null && matches.size() != 0) {
Log.d(TAG, "onResults: " + matches.get(0));
Message message = new Message();
message.what = ASRService.MSG_RECOGNIZER_RESULT;
message.setData(results);
sendMessageToClients(message);
} else {
Log.d(TAG, "onResults: No Results");
}
cancelSR();
}
#Override
public void onRmsChanged(float rmsdB) {
if (rmsdB > 20) {
if (userSpokeAt==-1) { //The user spoke the first time
partialResultsTimer = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(70000); //We wait for a max duration of this time to cancel the speech recognition because the service automatically times out anyway.
partialResultsTimer=null;
cancelSR();
} catch (InterruptedException e) {
}
return null;
}
}.execute();
}
userSpokeAt = System.currentTimeMillis();
if (!isUserSpeaking) {
Log.d(TAG, "User started speaking");
isUserSpeaking = true;
if (userStoppedSpeakingAt != -1) {
long gap = userSpokeAt - userStoppedSpeakingAt;
Log.d(TAG, "User spoke after " + gap + " millis");
}
userStoppedSpeakingAt = -1;
if (timeoutTaskRunner != null) {
Log.d(TAG, "Speech Recognition timer canceling");
timeoutTaskRunner.cancel();
timerRunning = false;
}
Message message = new Message();
message.what = ASRService.MSG_RECOGNIZER_USER_SPEAKING_STATE_CHANGED;
message.arg1 = 1; //1 means true
sendMessageToClients(message);
}
} else if (isUserSpeaking) {
long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis - userSpokeAt > 1700) {
isUserSpeaking = false;
Log.d(TAG, "User isn't speaking after: " + (currentTimeMillis - userSpokeAt));
userStoppedSpeakingAt = currentTimeMillis;
startTimer();
Message message = new Message();
message.what = ASRService.MSG_RECOGNIZER_USER_SPEAKING_STATE_CHANGED;
message.arg1 = 0; //0 means false
sendMessageToClients(message);
}
}
}
}
#Override
public IBinder onBind(Intent arg0) {
Log.d("ASRService", "onBind"); //$NON-NLS-1$
return mServerMessenger.getBinder();
} }

Android Get SMS Code with the Service BroadCastReceiver

I have login which requests for the SMS Code to Login the user. I have created the Receiver Class to receive the SMS Code the service reads the Full SMS from the Sender and it prints in the Log. I just want the recevier to get the code and verifiy on its own just like whatsapp.
This is the SMS I receive :-
Sent from your Twilio trial account - Your login code for App is :4132
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = SmsReceiver.class.getSimpleName();
private static final String SMS_ORIGIN = "+1 904-414-3527";
private static final String OTP_DELIMITER = ":";
private Context context;
private String code = null;
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (Object aPdusObj : pdusObj) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) aPdusObj);
String senderAddress = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.e(TAG, "Received SMS: " + message + ", Sender: " + senderAddress);
// if the SMS is not from our gateway, ignore the message
if (!senderAddress.toLowerCase().contains(SMS_ORIGIN)) {
return;
}
// verification code from sms
String verificationCode = getVerificationCode(message);
Toast.makeText(context, "OTP received: " + verificationCode, Toast.LENGTH_SHORT).show();
Log.e(TAG, "OTP received: " + verificationCode);
Intent hhtpIntent = new Intent(context, LoginActivity.class);
hhtpIntent.putExtra("otp", verificationCode);
context.startService(hhtpIntent);
}
}
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
/**
* Getting the OTP from sms message body
* ':' is the separator of OTP from the message
*
* #param message
* #return
*/
private String getVerificationCode(String message) {
int index = message.indexOf(OTP_DELIMITER);
if (index != -1) {
int start = index + 2;
int length = 4;
code = message.substring(start, start + length);
}
return code;
}
}
This where I want the code to be verified on its own with the intent but it doesn't work
public void doLogin() {
/* String otp = getIntent().getStringExtra("otp");
Toast.makeText(getApplicationContext(),
"You must enter the 4 digit code texted to your phone number." + otp,
Toast.LENGTH_LONG).show();*/
if (textField.getText().toString().length() != 4) {
codeUI();
} else {
code = Integer.parseInt(textField.getText().toString());
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("phoneNumber", phoneNumber);
params.put("codeEntry", code);
progressBar.setVisibility(View.VISIBLE);
ParseCloud.callFunctionInBackground("logIn", params, new FunctionCallback<String>() {
public void done(String response, ParseException e) {
progressBar.setVisibility(View.GONE);
if (e == null) {
token = response;
Log.d("Cloud Response", "There were no exceptions! " + response);
ParseUser.becomeInBackground(token, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null) {
parseUser.isAuthenticated();
Log.d("Cloud Response", "There were no exceptions! ");
Intent i = new Intent(LoginActivity.this, EditProfileActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
} else {
Log.d("Cloud Response", "Exception: " + e);
TSnackbar snackbar = TSnackbar
.make(relative,"Something went wrong:" + e,TSnackbar.LENGTH_SHORT);
snackbar.show();
phoneNumberUI();
}
}
});
} else {
codeUI();
Log.d("Cloud Response", "Exception: " + response + e);
TSnackbar snackbar = TSnackbar
.make(relative,"Incorrect Code",TSnackbar.LENGTH_SHORT);
snackbar.show();
}
}
});
}
}
Try Like This
public String GENERAL_OTP_TEMPLATE = "Sent from your Twilio trial account - Your login code for App is : (.*).";
SmsMessage[] message = new SmsMessage[pdusObj.length];
Pattern generalCodePattern = Pattern.compile(GENERAL_OTP_TEMPLATE);
Matcher generalCodeMatcher = generalCodePattern .matcher(message[0]
.getMessageBody().toString());
if (generalCodeMatcher.find()) {
String code= generalCodeMatcher.group(1);
//Do Your stuff here for Match your otp
}

Categories

Resources