0

我想在收到消息时从收到的消息中传递一些信息,例如消息的内容或消息的源编号,并且我想在某个条件为真时将该信息放在一个按钮中,而不是 oncreate,正在构建消息传递应用程序,所以我想将收到的消息存储在“收件箱”中,我该怎么做?附言。我在一个类中的 onreceive 方法扩展了广播接收器,而我的另一个类扩展了活动,在此先感谢!这是我扩展广播接收器的第一堂课

public class Re extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
 {
 Bundle bundle = intent.getExtras();       
SmsMessage[] msgs = null;
 String address="";
    String body="";
    long time = 0;
    if (bundle != null)
    {
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];
 address= msgs[i].getOriginatingAddress();
            body=msgs[i].getMessageBody().toString();
            time=msgs[i].getTimestampMillis();
}   

}

这是我扩展活动的第二堂课

public class ThirdView extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.third);
    }
}
4

1 回答 1

0

如果您想从 Receiver 的 onReceive 访问您的活动 - 那么您应该将 BroadcastReceiver 定义为 Actvity 的内部类并以编程方式注册它(在 onStart 方法中,并在 onStop 中取消注册);

public class ThirdView extends Activity {

    private static final IntentFilter intentFilter = 
        new IntentFilter("android.provider.Telephony.SMS_RECEIVED");

    TextButton myButton;

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            SmsMessage[] messages;
            //read parse pdus data from intent and pupulate messages array
            //...

            //update the button
            if(messages.length > 0) {
                myButton.setText(messages[0].getOriginatingAddress());
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.third);
        myButton = (TextButton) findViewByiD(R.id.myButton);
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onStop() {
        unregisterReceiver(receiver);
        super.onStop();
    }
}
于 2012-04-21T19:12:03.493 回答