如何在广播接收器中使用全局字符串?

时间:2015-04-27 22:36:48

标签: android broadcastreceiver global-variables

如何在广播接收器中使用全局字符串? sms变量有什么问题?

public class MainActivity extends Activity {
    String sms=""; //here is wrong???
    TextView view = new TextView(this);
    Uri uriSMSURI = Uri.parse("content://sms/inbox");
    Cursor cur = getContentResolver().query(uriSMSURI, null, null, null ,null);
    while (cur.moveToNext()) {
        if(cur.getString(13).startsWith("\n ")){
            sms +=cur.getString(13)+"\n";
        }             
    }

    TextView text = (TextView) findViewById(R.id.tabel);
    text.setText(sms);
    //here works well

    private final BroadcastReceiver SMSReceiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
              Bundle bundle=intent.getExtras();
              Object messages[]=(Object[])bundle.get("pdus");
              SmsMessage smsMessage[]=new SmsMessage[messages.length];
              for (int i=0; i < messages.length; i++) {
                     smsMessage[i]=SmsMessage.createFromPdu((byte[])messages[i]);
                 }

              if(smsMessage[0].getMessageBody().startsWith("\n ")){
                     sms +=smsMessage[0].getMessageBody(); 
                     //or here is wrong?
                }

          TextView text = (TextView) findViewById(R.id.tabel);
          text.setText(sms);

我想列出收到所有短信的清单,当我收到短信时,必须更新此清单。

1 个答案:

答案 0 :(得分:0)

我所做的是创建一个类并将所有静态变量放入其中。

例如,

class Values {
    static public Activity frontActivity = null;
    static public int currentStatus = Status.IDLE;
}

并像

一样访问它们
Values.frontActivity = this;
Values.currentStatis = Status.ACTIVE;