我正在尝试弄清楚如何在Android中读取传入的短信并执行特定任务,例如在发送带有“RingAlarm”文本的短信时发出警报。
我发现使用BroadcastReciever类来读取SMS,但是当带有预定义文本的消息到达时,如何执行特定操作。任何人都可以指导我需要使用哪个类和/或方法以及如何使用?
public class IncomingSms extends BroadcastReceiver {
String key = MainActivity.keyword; //Keyword is a variable in MainActivity.
//I guess, my mistake is in accessing this variable in the IncomingSms class.
@Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String sms = 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";
sms = msgs[i].getMessageBody().toString();
}
//---display the new SMS message---
//Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
//---compare received message with keyword
if(sms==key)
{
Toast toast = Toast.makeText(context, "Keyword Recieved", Toast.LENGTH_LONG);
toast.show();
}
}
}
提前致谢!
答案 0 :(得分:4)
这是我解决问题的简单模块。
我们假设关键字是“RING”。
MyReceiver:是一个类文件,用于检测关键字“RING”并启动RingActivity。
RingActivity:无论是处于静音模式还是振动模式,都会为您的设备振铃。
MyReceiver
public class MyReceiver extends BroadcastReceiver
{
final SmsManager sms = SmsManager.getDefault();
@Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
{
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
try
{
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";
}
String replyPhone = msgs[0].getOriginatingAddress();
String request = msgs[0].getMessageBody().toString();
if(request.equals("RING"))
{
this.abortBroadcast();
Intent i = new Intent(context, RingActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("num", replyPhone);
i.putExtra("msg", request);
context.startActivity(i);
}
}
}
catch (Exception e)
{
Log.e("MyReceiver", "Exception smsReceiver" +e);
}
}//close if
}//close onReceive();
}
RingActivity
public class RingActivity extends Activity {
final Context context = this;
MediaPlayer mp = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
String num = extras.getString("num");
String msg = extras.getString("msg");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "I AM At Reciver\nsenderNum: "+num+", message: " + msg, duration);
toast.show();
SmsManager smsManager = SmsManager.getDefault();
if(IsRingerSilent() || IsVibrate())
{
smsManager.sendTextMessage(num, null, "Device turned to ringing mode.. && It's Ringing..", null, null);
AudioManager audioManager= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
mp.setLooping(true);
try
{
AssetFileDescriptor afd;
afd = getAssets().openFd("fire_siren.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
smsManager.sendTextMessage(num, null, "Device Ringing...", null, null);
AudioManager audioManager= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
mp.setLooping(true);
try
{
AssetFileDescriptor afd;
afd = getAssets().openFd("fire_siren.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// Setting Dialog Title
alertDialogBuilder.setTitle("Device Ringing");
// Setting Dialog Message
alertDialogBuilder.setMessage("Sender : "+num+"\n"+"Message : "+msg);
alertDialogBuilder.setNegativeButton("Dialog Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
if(mp.isPlaying())
{
mp.setLooping(false);
mp.stop();
}
dialog.cancel();
finish();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
//show dialog
alertDialog.show();
}
private boolean IsVibrate()
{
AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE )
{
return true;
}
else
{
return false;
}
}
private boolean IsRingerSilent()
{
AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_SILENT )
{
return true;
}
else
{
return false;
}
}
public boolean onKeyDown(int keycode, KeyEvent ke)
{
if(keycode==KeyEvent.KEYCODE_BACK)
{
if(mp.isPlaying())
{
mp.setLooping(false);
mp.stop();
}
finish();
}
return true;
}
}