【问题标题】:Getting output from second activity class to first activity which is invokes by the first activity从第二个活动类获取输出到第一个活动调用的第一个活动
【发布时间】:2016-03-21 20:25:09
【问题描述】:

我的代码有两个活动。

public class OnCallingActivity extends Activity implement TextToSpeech.OnInitListener{}

public class TextReceiverActivity extends BroadcastReceiver{}

我希望第一个活动扩展第二个活动

OnCallingActivity extends TextReceiverActivity {}

所以我这样做了,

public class OnCallingActivity extends Activity implements TextToSpeech.OnInitListener {

  private TextReceiverActivity TextReceiverActivityClass;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.on_calling_layout);

    TextReceiverActivityClass= new TextReceiverActivity();
    speaker= new TextToSpeech(this, this);
    callerIdText=(TextView)findViewById(R.id.callerIdtextview);
    callerText=(TextView)findViewById(R.id.callermsgtextview);
    translatedText=(TextView)findViewById(R.id.translatedTextview);
    speakButton=(ImageButton)findViewById(R.id.btnSpeak);
    sendButton=(Button)findViewById(R.id.buttonsend);
    endCallButton=(ImageButton)findViewById(R.id.buttonendCall);        
}

我的第二个活动如下,

public class TextReceiverActivity extends BroadcastReceiver{
  @Override
  public void onReceive(Context context, Intent intent) {
     number ="";
     message="";

     final Bundle bundle = intent.getExtras(); 

     try {
        if(bundle != null) {
            final Object[] pduObjects = (Object[]) bundle.get("pdus");

            for(int i = 0; i < pduObjects.length; ++i) {

                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pduObjects[i]);

                number = currentMessage.getDisplayOriginatingAddress();
                message = currentMessage.getDisplayMessageBody();

                Toast.makeText(context, "SENDER NUMBER: " + number + "; MESSAGE: " + message, Toast.LENGTH_LONG).show();
            }               
        }
     } catch (Exception e) {
        e.printStackTrace();
     }
  }

在第一个活动中,我这样调用第二个活动的方法

public void onReceive(Context context, Intent intent) { 

    TextReceiverActivityClass.onReceive(context, intent);       

}

onReceive 给出数字和消息的值。所以我怎样才能让它们进入我的第一个活动以在 TextViews 中显示它们。

onReceive 是一个内置方法,因此我无法更改返回类型。

【问题讨论】:

  • 请正确格式化您的问题。这是不可读的。
  • 对不起..刚刚做了,

标签: java android android-intent


【解决方案1】:
  1. 如果 TextReceiverActivity extends BroadcastReceiver,那么 TextReceiverActivity 不是 Activity,我会避免将其称为 Activity。

  2. BroadcastReceiver 的onReceive 方法是从Android 系统调用的,而不是你。

  3. 要从 Activity 向 BroadcastReceiver 发送消息,您需要发送一个 Broadcast。见the docs

  4. 如果您想从 BroadcastReceiver 向您的 Activity 发送消息,则有一个 couplequestions about

【讨论】:

  • 谢谢 Ascorbin!您的链接有助于解决我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多