I have an app that replies to any received SMS with a default message. The app works, however it also works when I close the app. Is there anyway I can un-override the onReceive method for BroadcastReceiver, so that once I close the app, it won’t use my version of the onReceieve method? If not, what’s the best way to fix this problem?
//SMS.java
package net.learn2develop.SMSMessaging;
import net.learn2develop.SMSMessaging.R;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SMS extends Activity
{
Button btnExit;
static EditText txtMessage;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnExit = (Button) findViewById(R.id.btnExit);
txtMessage = (EditText) findViewById(R.id.txtMessage);
btnExit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
}
public static String getMessage(){
return txtMessage.getText().toString();
}
}
______________________________________________________________________________________
//SMSReceiver.java
package net.learn2develop.SMSMessaging;
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.widget.Toast;
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");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
sendSms(msgs[i].getOriginatingAddress(),SMS.getMessage());
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
private void sendSms(String phonenumber,String message)
{
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(phonenumber, null, message, null, null);
}
}
I would just create a boolean which decides whether to execute your code or the super’s onRecieve method. Then just override the onPause method of the activity and toggle the boolean flag.