gpt4 book ai didi

android - 如何在服务和 Activity 之间发送/接收广播

转载 作者:行者123 更新时间:2023-11-29 17:49:48 27 4
gpt4 key购买 nike

我需要从 SmsReceiver 类向我的 Main_Activity 发送消息,但无法执行。我尝试了很多并搜索了但是...。

这是我的代码

SmsReceiver.java

public class SmsReceiver extends BroadcastReceiver {

// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context, Intent intent) {

// Retrieves a map of extended data from the 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 phoneNumber = currentMessage.getDisplayOriginatingAddress();

String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);

Intent intent1=new Intent(context, MainActivity.class);

intent1.putExtra("m",message);
context.sendBroadcast(intent1);
} // end for loop
} // bundle is null

} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);

}

}
}

MainActivity.java

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText intext=(EditText) findViewById(R.id.editText2Inputtext);

BroadcastReceiver mysms=new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
String sms=arg1.getExtras().getString("m");
intext.setText(sms);

}
};
}
}

最佳答案

您发送和注册广播接收器的代码不正确。发送广播:

Intent intent = new Intent("your_action_name");
intent.putExtra(....);
sendBroadcast(intent);

接收:

BroadcastReceiver mysms=new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
String sms=arg1.getExtras().getString("m");
intext.setText(sms);

}
};
registerReceiver(mysms, new IntentFilter("your_action_name"));

并记得在销毁您的 Activity 时取消注册。

关于android - 如何在服务和 Activity 之间发送/接收广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23722097/

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