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
}
Related
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();
} }
I have added the module GCM and it works with APPENGINE correcty. I've done the documentation says to register and receive messages from Endpoint.
Now I wan't to unregister a device and I don't know how do it....
Any idea ?
I have tested gcm.unregister() and regService.unregister(Idphone).execute() but it doesn't work
I've tried to do a new AsyncTask class GcmUnRegistrationAsyncTask extends AsyncTask {
private static Registration regService = null;
private GoogleCloudMessaging gcm;
private Context context;
private static final String SENDER_ID = "892982546498";
public GcmUnRegistrationAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... params) {
if (regService == null) {
Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://myproject.appspot.com/_ah/api/");
regService = builder.build();
}
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
String regId = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regId;
MainActivity.token=regId;
regService.unregister(regId).execute();
gcm.unregister();
} catch (IOException ex) {
ex.printStackTrace();
msg = "Error: " + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
// Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
Logger.getLogger("unREGISTRATION").log(Level.INFO, msg);
Toast.makeText(context, MainActivity.token, Toast.LENGTH_LONG).show();
}
}
I would like to show all devices too......
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
In one of my application i need to make app like chat application in that i am able to send data from device to server but not able to get data back from server to device.
In my manifest file... i have done
<permission android:name="<package name>.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="<package name>.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<receiver
android:name="<package name>.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="<package name>" />
</intent-filter>
</receiver>
<service android:name=".GcmIntentService" ></service>
my GcmIntentService is like
public class GcmIntentService extends IntentService {
private static final String TAG = "GcmIntentService";
public static final int NOTIFICATION_ID = 101;
private NotificationManager mNotificationManager;
private DBAdapter dbAdapter;
public GcmIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("GcmIntentService>>>>>>>>>>>>>>>>>>>>>>>>>>>>");// this tag display in logcat
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String gcmMessageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
// has effect of unparcelling Bundle
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(gcmMessageType)) {
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(gcmMessageType)) {
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(gcmMessageType)) {
AppLog.Log(TAG, "newMessage :: " + intent);
String newMessage = intent.getExtras().getString("message");
AppLog.Log(TAG, "newMessage :: " + newMessage);
try {
handleMessage(newMessage);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void handleMessage(String message) throws JSONException {
if (message == null) {
return;
}
dbAdapter = new DBAdapter(getApplicationContext());
UserDetail detail = new MyPrefrence(getApplicationContext())
.getDetail();
JSONObject object = new JSONObject(message);
object = object.getJSONObject("details");
int who = object.getInt("who");
switch (who) {
case MessageModel.WHO_PERSONAL:
AHttpResponse response = new AHttpResponse(message, true);
MessageModel model = response.getSendMessage();
insertIfUSerNotExits(model, message);
model.setMessageStatus(MessageModel.STATUS_DELIVERED);
String tempMessage = null;
AppLog.Log(TAG, "MESSAGE ::" + model);
switch (model.getMessageType()) {
case MessageModel.MESSAGE_TYPE_MESSAGE:
tempMessage = model.getDisplayName() + ":" + model.getMessage();
break;
case MessageModel.MESSAGE_TYPE_VEDIO:
tempMessage = model.getDisplayName() + ": Video";
break;
case MessageModel.MESSAGE_TYPE_IMAGE:
tempMessage = model.getDisplayName() + ": image";
break;
case MessageModel.MESSAGE_TYPE_LOCATION:
tempMessage = model.getDisplayName() + ": location";
break;
case MessageModel.MESSAGE_TYPE_CONTACT:
tempMessage = model.getDisplayName() + " sends you contact of "
+ model.getMessage().split("//s+")[0];
break;
}
if (message != null) {
generateNotification(tempMessage);
}
dbAdapter.openForWrite();
int receiveMessageID = dbAdapter.insertMessage(model);
int userUpdateId = dbAdapter.updateLastMessageId(
receiveMessageID,
detail.getUserId() == model.getUserID() ? model
.getFriendId() : model.getUserID());
if (userUpdateId == 1) {
AppLog.Log(TAG, "User Update Success");
} else {
AppLog.Log(TAG, "User Update UnSucess");
}
dbAdapter.close();
// Intent intent = new Intent(MyActions.MESSAGE_UPDATE);
// LocalBroadcastManager.getInstance(getApplicationContext())
// .sendBroadcast(intent);
break;
case MessageModel.WHO_GROUP:
AppLog.Log(TAG,
"******************Group Message Received*********************");
AHttpResponse responseG = new AHttpResponse(message, true);
MessageModel modelG = responseG.getSendMessage();
insertIfUSerNotExits(modelG, message);
modelG.setMessageStatus(MessageModel.STATUS_DELIVERED);
AppLog.Log(TAG, "MESSAGE ::" + modelG);
// modelG.setUserID(new MyPrefrence(this).getDetail().getUserId());
// generateNotification(model.getDisplayName() + ":"
// + model.getMessage());
dbAdapter.openForWrite();
int receiveMessageIDG = dbAdapter.insertMessage(modelG);
if (modelG.getMessage() != null) {
generateNotification(modelG.getMessage());
}
int userUpdateIdG = dbAdapter.updateLastMessageId(
receiveMessageIDG,
detail.getUserId() == modelG.getUserID() ? modelG
.getFriendId() : modelG.getUserID());
if (userUpdateIdG == 1) {
AppLog.Log(TAG, "User Update Success");
} else {
AppLog.Log(TAG, "User Update UnSucess");
}
dbAdapter.close();
break;
case MessageModel.WHO_JOIN_GROUP:
AHttpResponse aHttpResponse = new AHttpResponse(message, true);
UserDetail userDetail = aHttpResponse.getJoinGroupDetail();
AppLog.Log(TAG, "userdetail :: " + userDetail.getName());
dbAdapter.openForRead();
dbAdapter.insertOrUpdateGroup(userDetail);
AppLog.Log(TAG, "Group is Created ");
getGtoupDetailFromServer(userDetail);
// } else {
// AppLog.Log(TAG, "Group creation failed");
// }
dbAdapter.close();
// dbAdapter.inserGroup();
// {"details":{"id":"119","time":"2014-06-12 17:02:11","type":"","user_id":"131","friend_id":"","who":"4","message":"","delivery_time":"","image":"group\/default.jpg","user_status":"","phone":"","phone_code":"","name":"test
// 33","status":""},"success":true,"message":"Successfully group
// created."}
break;
default:
break;
}
Intent intent = new Intent(MyActions.MESSAGE_UPDATE);
LocalBroadcastManager.getInstance(getApplicationContext())
.sendBroadcast(intent);
}
/**
*
* #param model
* #param newMessage
*
* responsible if user does not exists in database
*/
private void insertIfUSerNotExits(MessageModel model, String newMessage) {
dbAdapter.openForRead();
UserDetail userDetail = dbAdapter.getUserDetail(model.getUserID());
dbAdapter.close();
if (userDetail == null) {
UserDetail newUserDetail = new UserDetail();
try {
JSONObject jsonObject = new JSONObject(newMessage);
if (jsonObject.has("details")) {
jsonObject = jsonObject.getJSONObject("details");
newUserDetail.setUserId(jsonObject.getInt("user_id"));
newUserDetail.setImage(jsonObject.getString("image"));
newUserDetail
.setStatus(jsonObject.getString("user_status"));
newUserDetail.setPhoneNo(jsonObject.getString("phone"));
newUserDetail.setPhoneCode(jsonObject
.getString("phone_code"));
newUserDetail.setName(jsonObject.getString("name"));
// time to insert local database
dbAdapter.openForRead();
dbAdapter.insertOrUpdateUser(newUserDetail);
dbAdapter.close();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void getGtoupDetailFromServer(final UserDetail detail) {
new Thread(new Runnable() {
#Override
public void run() {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", detail
.getUserId() + ""));
HttpRequest httpRequest = new HttpRequest();
try {
String responseString = httpRequest.postData(
Urls.GET_GROUP_MEMBER, nameValuePairs);
JSONObject jsonObject = new JSONObject(responseString);
AppLog.Log(TAG, "Getting Group Detail response :: "
+ responseString);
if (jsonObject.getBoolean("success")) {
JSONArray array = jsonObject.getJSONArray("details");
dbAdapter.openForWrite();
dbAdapter.deleteAllGroupUsers(detail.getUserId());
dbAdapter.close();
AppLog.Log(TAG, "GRoup Members ***************** "
+ array.length());
UserDetail detail;
for (int i = 0; i < array.length(); i++) {
detail = new UserDetail();
jsonObject = array.getJSONObject(i);
detail.setUserId(jsonObject.getInt("id"));
detail.setGroupId(jsonObject.getInt("group_id"));
detail.setAdmin(jsonObject.getInt("is_admin") == 1);
detail.setName(jsonObject.getString("name"));
detail.setPhoneCode(jsonObject
.getString("phone_code"));
detail.setPhoneNo(jsonObject.getString("phone"));
detail.setImage(jsonObject.getString("image"));
detail.setStatus(jsonObject.getString("status"));
dbAdapter.openForRead();
dbAdapter.insertUpdateGroupMember(detail);
dbAdapter.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void generateNotification(String message) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getResources().getString(R.string.app_name))
.setStyle(
new NotificationCompat.BigTextStyle().bigText(message))
.setTicker(message).setContentText(message).setAutoCancel(true);
// Play default notification sound
mBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.FLAG_AUTO_CANCEL);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, RecentChatList.class), 0);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
and GcmBroadcastReceiver class
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
// private static final String TAG = "GcmBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
System.out.println("PACKAGE NAME>>>>>>>>>>>>>>>>"+context.getPackageName()+"");
System.out.println("GcmBroadcastReceiver>>>>>>>>>>>>>>>>>>>>>");////still running
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
System.out.println("GcmBroadcastReceiver STARTED>>>>>>>>>>>>>>>>>>>>>");//still running
setResultCode(Activity.RESULT_OK);
}
*note GcmIntentService and GcmBroadcastReceiver is lies under my direct package
Please help to sove this problem
You need this permission to receive messages:
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
To register,
GoogleCloudMessaging mGCM = GoogleCloudMessaging.getInstance(mContext);
String regId = mGCM.register(GOOGLE_PROJECT_ID);
Then just check if regId is a valid String.
I coding an application which when a button is pressed and a timer reaches zero, an SMS and email sends to saved contacts and the message contain information saved in preferences. I have the email sending fine and SMS seems to be working with no crashes but i don't receive any SMS at all:
#Override
public void onFinish() {
final String[] personalInfo = db.getPersonalDetails();
final Cursor contacts = db.getContacts();
if (match == false) {
sendSms();
if (db.hasGmail()) {
Thread s = new Thread(new Runnable() {
public void run() {
String args[] = db.getGmail();
GmailSender sender = new GmailSender(args[0],args[1], getApplicationContext());
Cursor c = db.getEmailContacts();
while (c.moveToNext()) {
try {
Log.e(args[0], args[1]);
sender.sendMail(
args[0],
c.getString(c
.getColumnIndex("emailAddress")));
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
}
});
s.start();
}
Toast.makeText(getApplicationContext(), "Information sent",
5000).show();
}
}
}.start();
}
private void sendSms() {
sms = new Intent(this, SMS.class);
this.startService(sms);
}
SMS Class:
public class SMS extends Service {
String BankAccount, BankNameAddress, SortCode;
String message;
SharedPreferences prefs;
public void initilizePrefs() {
prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
BankAccount = prefs.getString("BankAccount", null);
BankNameAddress = prefs.getString("BankNameAddress", null);
SortCode = prefs.getString("SortCode", null);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onStart(Intent intent, int startid) {
super.onStart(intent, startid);
initilizePrefs();
String mes = "my account info is: " + BankNameAddress + " "
+ " account number: " + BankAccount + " Sort Code is: "
+ SortCode + " " + "Thank you so much!!";
try {
if (BankNameAddress != null && BankAccount != null
&& SortCode != null) {
sendSMS("Help!! I've completely run out of money and need you to send some via bank transfer please. "
+ mes);
}
else
Toast.makeText(getBaseContext(),
"Please ensure all sections of preferences are filled",
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendSMS(String message) {
Database db = new Database(this);
Cursor cursor = db.getNumbers();
db.onStop();
if (cursor != null) {
while (cursor.moveToNext()) {
String phoneNumber = cursor.getString(cursor
.getColumnIndex("number"));
Log.e("number", phoneNumber);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
you need to have a broadcast receiver which will receive your sms . the code is as follows :
public class SmsReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");//it must be given as it is only
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); //Create an SmsMessage from a raw PDU.
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
//---display the new SMS message---
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("message", str);
context.startActivity(i);
Toast.makeText(context, "mmmm"+str, Toast.LENGTH_SHORT).show();
}
}
}
In your activity class , receive the intent :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tx=(TextView) findViewById(R.id.textView1);
Bundle bun=getIntent().getExtras();
String stuff=bun.getString("message");
tx.setText("Welcome,"+stuff);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Add permisions :