gpt4 book ai didi

java - 如何在其他非 Activity 类Android的 Activity 中插入TextView?

转载 作者:行者123 更新时间:2023-11-29 19:19:00 26 4
gpt4 key购买 nike

我需要从IncomingSms(非 Activity 类)设置Main3Activity( Activity 类)的TextView对象。

public class IncomingSms extends BroadcastReceiver {

final SmsManager sms = SmsManager.getDefault();

@Override
public void onReceive(Context context, Intent 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 senderNum = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
if (message.equalsIgnoreCase("FIRE DETECTED")) {
//Problem start here: I cant able to set TextView object of Main3Activity
Main3Activity main3Activity = new Main3Activity();
TextView tv = (TextView) main3Activity.findViewById(R.id.firealert);
tv.setText(message);
//Problem end here
Log.i("SmsReceived", "senderNum: " + senderNum + "; message: " + message);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, message, duration);
toast.show();
}
}
}
} catch(Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}

最佳答案

创建一个接口(interface)类然后将其保存为java类

public interface SmsListener {
public void messageReceived(String messageText);
}

final SmsManager sms = SmsManager.getDefault();
private static SmsListener mListener;
@Override
public void onReceive(Context context, Intent 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 senderNum = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
if (message.equalsIgnoreCase("FIRE DETECTED") ){
mListener.messageReceived(message); //add this
Log.i("SmsReceived", "senderNum: "+ senderNum + "; message: " + message);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, message, duration);
toast.show();
}
}
}
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}

然后在您的 Main3Activity onCreate 方法中

TextView tv=(TextView) main3Activity.findViewById(R.id.firealert);


SmsReceiver.bindListener(new SmsListener() {
@Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
tv.setText(messageText);
}
});

关于java - 如何在其他非 Activity 类Android的 Activity 中插入TextView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com