通过外部类从BroadcastReceiver到特定Activity的信息

时间:2013-08-03 18:38:09

标签: android android-activity broadcastreceiver

我有“ComposeActivity”,它在onClick之后调用“SendSMS”方法,而不是在SMS类中调用metod。我还注册了两个BroadcastReceiver:SmsDeliveredReceiver和SmsSentReceiver,类似于:https://stackoverflow.com/a/17164931/1888738。我如何通知ComposeActivity,短信已经成功发送,并且该活动可以清理一些EditText,并且可能显示crouton是否发送了短信(以及为什么)?我的代码:http://pastebin.com/LNRuSeBu

2 个答案:

答案 0 :(得分:1)

如果您在发送或未发送SMS消息时有接收器处理。您可以通过创建intent并调用intent.setComponent来指定意图应该去的位置来修改两个接收器的onReceive以发送和意图到ComposeActivity。一些数据告诉ComposeActivity尝试发送消息的结果。

更新

 public void onReceive(Context context, Intent arg1) {
    Intent i = new Intent(action);
    i.setComponent(new ComponentName("com.mypackage.compose","ComposeActivity"));
    switch (getResultCode()) {
        case Activity.RESULT_OK:
            Log.d(getClass().getSimpleName(), "SMS delivered");
            intent.setAction("com.mypackage.compose.SMS_SENT"); // String you define to match the intent-filter of ComposeActivity. 
            break;
        case Activity.RESULT_CANCELED:
            Log.d(getClass().getSimpleName(), "SMS not delivered");
            intent.setAction("com.mypackage.compose.SMS_FAILED"); // String you define to match the intent-filter of ComposeActivity. 

            break;
    }
     startActivity(intent); // you may not necessarily have to call startActivity but call whatever method you need to to deliver the intent.

}

此时,只需通过清单或编程方式添加一个intent-filter和一个接收器到你的撰写活动。你的来电。我使用的字符串是组成的,但您可以选择一个现有的意图操作字符串或声明您在意图过滤器中使用的字符串。再次由你决定。也可以帮助您查看有关向Android explicit intent with target component等组件发送显式意图的问题  或者看android docs

答案 1 :(得分:1)

好的,经过5个小时的尝试,我已经解决了这个问题:

onReceive中的BroadcastReceiver中的

Intent intent = new Intent();
intent.setAction("SOMEACTION");
context.sendBroadcast(intent);

在活动中:

public BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("SOMEACTION")) {
            Log.d(TAG, "Sent");
        }
    }
};

并在onCreate Activity中注册了BroadcastReceiver:

registerReceiver(receiver, new IntentFilter("SOMEACTION"));

多数人......