我目前正在开发一个简单的Android应用程序来读取短信并用TexView而不是Toast打印。但是在接收器活动中,我们不会初始化" findbyid"所以我们无法在textView中打印短信。现在我在Toast中显示短信进行测试,但我不希望它出现在toast中。我也读了问题/答案以及其他文章,但无法找到我想要的东西。
接收者活动,
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class read_sms extends BroadcastReceiver {
// Get the object of SmsManager
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
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("SmsReciver", "senderNum: " + senderNum + ", message: " + message);
//ourSMS.getSmsDetails(senderNum, message);
// Show SMS notification
//Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, Toast.LENGTH_LONG).show();
if(message.equals("Milind")){
Toast.makeText(context, "sms matched", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context, "not matched", Toast.LENGTH_LONG).show();
}
} // end of for loop
} // bundle
} catch (Exception e) {
// TODO: handle exception
Log.e("SmsReciver", "Exception smsReciver" + e);
}
}
}
我的家庭活动是空的,因为我无法找到放在这里的代码。
public class home extends AppCompatActivity {
TextView SMS_textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
SMS_textview = (TextView) findViewById(R.id.sms_text);
}
}
答案 0 :(得分:0)
将TextView更改为
public static TextView SMS_textview;
添加方法
public void recivedSms(String message)
{
try
{
SMS_textview.setText(message);
}
catch (Exception e)
{
}
}
在read_sms类中,在收到短信时添加以下代码
home Sms = new home();
Sms.recivedSms(message );
答案 1 :(得分:0)
每当您在接收方收到文本时,请在您的活动中注册您的Receiver 在Receiver类中使用此代码
Intent broadcastIntent = new Intent();
broadcastIntent.putExtra("your key", your Value);
broadcastIntent.setAction("link from you have recieve a text");
context.sendBroadcast(broadcastIntent);
之后在您的活动中注册一个广播接收器,如下所示
private void registerSmsReciever() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("link from you have recieve a text");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("onReceive", "Sms recieved in progress");
String message= intent.getStringExtra("key");
textView.setText(intent.getStringExtra("key"));
}
};
registerReceiver(broadcastReceiver, intentFilter);
}