package com.m.omg;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver
{
MediaPlayer mp =new MediaPlayer();
#Override
public void onReceive(Context context, Intent intent)
{
String mymsg = null;
String num = null;
//get the SMS message passed in
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null)
{
//retrieving the received SMS
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
num = msgs[i].getOriginatingAddress();
mymsg = msgs[i].getMessageBody().toString();
}
Toast.makeText(context, "from" + num + ":" + mymsg, Toast.LENGTH_LONG).show();
//making decision, depending on the number & message body
if (num.equalsIgnoreCase("some# :) ")){
abortBroadcast();
if (mymsg.equalsIgnoreCase("start")){
mp.create(context, R.raw.music);
mp.start();
}
}
mp.release();
}
}
}
*media player not initialized when the condition is matched... the app works normally, when I receive the SMS, the Toast is displayed but media player is not triggered, I get this warning in eclipse "The static method create(Context, int) from the type MediaPlayer should be accessed in a static way" which I ignored it :D *
use
mp=MediaPlayer.create(context, R.raw.music);
instead of
mp.create(context, R.raw.music);
for initializing mp instance of MediaPlayer
Related
I think I'm in a bit of a catch 22 situation. I'm making an app that verifies the user's phone number by sending a text message to the number the user entered and then checking - that way it's definitely the user's phone number. This activity should only appear once, at the beginning - for the user to verify, and from then on activity 2 should be loaded.
I am trying to do this with :
// when the form loads, check to see if phoneNo is in there
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String phoneNoCheck = sharedPreferences.getString("phonenumber","");
if (phoneNoCheck != null) {
// if it is in there, start the new Activity
Intent myIntent = new Intent(MainActivity.this, PopulistoContactList.class);
MainActivity.this.startActivity(myIntent);
}
But it doesn't seem to be working properly. For a start, I'm not even sure it should be null. When I turn off my phone and on again, it starts back at activity 1, asking for verification.
And I can't test it. I need to run the app on my device as I can't send an SMS from the emulator, and I'm unable to get to the files where sharedPreferences exist on my device, so I can't even see if it's being written correctly.
Any advice on how I might be able to see the MyData.xml on my phone and proceed with testing my app, or tell my how I may be able to improve my code ? I downloaded the Astro app but still couldn't find it.
Here's my code :
package com.example.chris.tutorialspoint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.tutorialspoint.R;
public class MainActivity extends Activity {
Button sendBtn;
EditText txtphoneNo;
String phoneNo;
String origNumber;
private BroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editText);
// when the form loads, check to see if phoneNo is in there
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String phoneNoCheck = sharedPreferences.getString("phonenumber","");
if (phoneNoCheck != null) {
// if it is in there, start the new Activity
Intent myIntent = new Intent(MainActivity.this, PopulistoContactList.class);
MainActivity.this.startActivity(myIntent);
}
//if it is not in there, proceed with phone number verification
else {
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
IntentFilter filter = new IntentFilter();
// the thing we're looking out for is received SMSs
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
Bundle extras = intent.getExtras();
if (extras == null)
return;
Object[] pdus = (Object[]) extras.get("pdus");
SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[0]);
origNumber = msg.getOriginatingAddress();
Toast.makeText(getApplicationContext(), "Originating number" + origNumber, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Sent to number" + phoneNo, Toast.LENGTH_LONG).show();
}
};
registerReceiver(receiver, filter);
}
}
protected void sendSMSMessage() {
phoneNo = txtphoneNo.getText().toString();
//this is the SMS received
String message = "Verification test code. Please ignore this message. Thank you.";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
//if originating phone number is the same as the sent to number, save
//and go to the next activity
if (origNumber.equals(phoneNo)) {
//save the phone number
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("phonenumber", phoneNo);
editor.commit();
Intent myIntent = new Intent(MainActivity.this, PopulistoContactList.class);
MainActivity.this.startActivity(myIntent);
}
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS failed, please try again.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
if (receiver != null) {
unregisterReceiver(receiver);
receiver = null;
}
super.onDestroy();
}
What do you expect to happen here:
String phoneNoCheck = sharedPreferences.getString("phonenumber","");
if (phoneNoCheck != null) {
...
}
The method that you are calling, getString(String, String), uses the second parameter as the default value, that is, if no property is found, it will default to, as you have defined, an empty string, "".
You then try and compare this to null, which will never be equal.
Try changing it up to something like this:
String phoneNoCheck = sharedPreferences.getString("phonenumber", null);
// check if null or empty
if ( null == phoneNoCheck || phoneNoCheck.equals("") ) {
// unregistered
}
i'm developing an android application which will filter out the messages from a particular number and read its message body.
I have written a class which extends to broadcast receiver as follows.
package com.tutecentral.restfulapiclient;
import android.content.BroadcastReceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class Filter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle extras = intent.getExtras();
if (extras != null) {
Object[] pdus = (Object[])extras.get("pdus");
if (pdus.length < 1) return;
StringBuilder sb = new StringBuilder();
String sender = null;
for (int i = 0; i < pdus.length; i++) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);
if (sender == null){
sender = message.getOriginatingAddress(); //get the sender
}
String text = message.getMessageBody(); //get the message body
Log.d("my broadcast","works");
//System.out.println("tsettexttt"+text);
if (text != null){
sb.append(text);
}
System.out.println("texttst"+text);
}
String number = "+94716355075"; //add the number
abortBroadcast();
}
}
}
}
Now what i want to do is to call this class from the main activity and also get the results from this class (String text : which holds the message body) so that i can use that value for other options in the app.
I went through every stackoverflow question posted regarding this but couldn't find the answer. Please be kind enough to help me out!!
Thanks in advance,
Regards
You can open your activity from the BroadcastReceiver passing some parameters, once the activity is open if certain parameters have been passed to this activity, call the method you want.
Hope it helps!
Edit: check this code out!
#Override
public void onReceive(Context context, Intent intent) {
//Do your normal work...
//start activity
Intent i = new Intent(context,YourActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("param","value"); //your parameter
context.startActivity(i);
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
My android app first displays a toast when a message is received and when it receives a message from a particular number it shows another toast. But it is not displaying the second toast.
Here is my code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
String serverNumber= "+919886096376";
if(senderNum == serverNumber)
{
Toast toast1 = Toast.makeText(context,"alert message received!!!!",Toast.LENGTH_LONG);
toast.show();
}
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
You are comparing if(senderNum == serverNumber) in wrong way. In Java & Android == is used to compare objects not Strings. When you want to compare two Strings you need to use .equals() method.
You need to compare like below,
if(senderNum.equals(serverNumber))
{
Toast toast1 = Toast.makeText(context,"alert message received!!!!",Toast.LENGTH_LONG);
toast1.show(); // change this to toast1
}
Change this
if(senderNum == serverNumber){
Toast toast1 = Toast.makeText(context,"alert message received!!!!",Toast.LENGTH_LONG);
toast.show();
}
to this
if(senderNum.equals(serverNumber)){
Toast toast1 = Toast.makeText(context,"alert message received!!!!",Toast.LENGTH_LONG);
toast1.show();
}
You are not calling show on the correct toast.
Also, the proper way to compare 2 Strings is the following :
senderNum.equals(serverNumber)
By using the == operator, you are comparing references to String objects, so it will much likely return false.
When the button is clicked the audio that is playing has to stop and a message has to be sent. But its not doing either of them! The audio just plays does not stop! What did I do wrong in the code??
Here is my main activity
package com.androidexample.broadcastreceiver;
import java.io.IOException;
import com.wallpaper.rahuldravid.R;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class IncomingSms extends BroadcastReceiver {
private static final String LOGCAT = null;
MediaPlayer objPlayer;
Button Button1;
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(final Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
String serverNumber= "+919845147131";
if(senderNum.equals(serverNumber))
{
Toast toast1 = Toast.makeText(context,"alert message received!!!!",Toast.LENGTH_LONG);
toast1.show();
objPlayer = MediaPlayer.create(context,R.raw.hospital_alarm);
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
Button1 = (Button)findViewById(R.id.button1);
Button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
objPlayer.stop();
objPlayer.release();
String phoneNumber = "919845147131";
String message = "Ambulance sent!";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast toast2 = Toast.makeText(context,"acknowledgement sent!",Toast.LENGTH_LONG);
toast2.show();
}
finally {
}
}
});
}
}
} // end for loop
}
}// bundle is null
catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
Here is my layout code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BroadcastPhoneStates" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="When accident occurs you will be notified okay okay." />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="118dp"
android:text="Accept/Acknowledge" />
</RelativeLayout>
findViewById() is a method of Activity. If to your BroadcastReceiver you passed the Activity context you can do:
Button1 = (Button) ((Activity)context).findViewById(R.id.button1);
The reason you are seeing this is because findViewById() is a method that does not exist in the base class BroadcastReceiver - it is a method that exists in the Activity class. What you can do is:
Button1 = (Button) (Activity)context.findViewById(R.id.button1);
You are using the context the BroadcastReceiver uses to get the Activity.
In my code I have a java file with this in it:
package com.myapp.basic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSReceiverActivity extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Parse the SMS.
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
// Retrieve the SMS.
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
// In case of a particular App / Service.
//if(msgs[i].getOriginatingAddress().equals("+91XXX"))
//{
//str += "SMS from " + msgs[i].getOriginatingAddress();
//str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
//}
}
if (str != "") { // remove the last \n
str = str.substring(0, str.length()-1);
}
// Need to find a better way to check if the activity is running
try {
((Police_ViewActivity) context.getApplicationContext()).handle_incoming_help_message(str); // crash here
} catch(Exception e) {
System.out.println(e.getMessage());
}
System.out.println("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
}
}
}
When the code in the try block happens, it crashes and i get this error:
08-27 22:45:11.345: I/System.out(27606): android.app.Application cannot be cast to com.escortme.basic.Police_ViewActivity
How can I fix this ?
Calling Activity is best using Intent. You can just put something like:
Intent intent = new Intent(Police_ViewActivity.class);
intent.putExtra("help_message", str);
context.startActivity(intent);
In onResume() of your Police view Activity, grab the extra and handles it:
onResume(){
String msg = getIntent().getStringExtra("help_message");
if (msg==null) return;
handleMessage(msg);
}
You don't have to worry multiple instance of the Activity being created, in manifest you can specify how the activity launch using Launchmode. singleInstance could be your choice.
If you just need to call handle_incoming_help_message method in another class, just make handle_incoming_help_message method static.
update:
So you should start Police_ViewActivity and tell it that you need to call handle_incoming_help_message
Intent intent = new Intent(context, Police_ViewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra("handle_incoming_help_message", str);
context.startActivity(intent);
and in Police_ViewActivity's onCreate (or onResume or Onstart)
String str = getIntent().getStringExtra("handle_incoming_help_message");
if(str != null)
handle_incoming_help_message(str);
Update 2
To keep the number of instances of policeviewactivity to be at most 1? -> Android LaunchMode