我的原始应用程序接收文本并使用字符拆分来拆分并显示在文本视图中。然后,我实现了从 BroadcastReceiver 调用活动的代码,以便在收到文本时将活动带到最前面,但应用程序的文本视图没有更新。
如果我从 SMSReceiver.java 中删除,它可以正常工作,但应用程序不会被带到前面。
//--Launch the MainActivity--//
Intent mainActivityIntent = new Intent(context, MainActivity.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mainActivityIntent);
SMSReceiver.java 代码:
package com.example.smssend;
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 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 += msgs[i].getMessageBody().toString();
}
//--Display the new SMS Message--//
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
String sender = null;
//--Launch the MainActivity--//
Intent mainActivityIntent = new Intent(context, MainActivity.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mainActivityIntent);
//--Send a broadcast intent to update the SMS received in the activity--//
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
}