更新ListView - 接收短信 - Android

时间:2015-05-25 22:22:51

标签: android listview

我写了一个接收消息并将它们添加到ListView的应用程序(我是一个初学者,体验级别0)...当我启动一个应用程序并且我在MainActivity中并收到一条消息时,它是写入列表,但问题是,当我正在进行名为'SmsActivity'的活动时,在接收短信时,列表不会更新/刷新。 (我需要回到MainActivity,再次切换到SmsActivity,然后才看到新的meessages。)

public class SmsActivity extends ActionBarActivity {

ListView list_view;
public static ArrayList<String> lista_sms = new ArrayList<String>();
public static ArrayAdapter<String> adapter;

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

    list_view = (ListView) findViewById(R.id.list_view);
    // adding do list in ReceiverSMS.java
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lista_sms);
    list_view.setAdapter(adapter);
}

我收到了在其他类中声明的消息:

`public class ReceiverSMS扩展了BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent)
{
    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    String str = "";
    if (bundle != null)
    {
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            str += "" + msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            str += "\n";
        }
        //---display the new SMS message---
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        SmsActivity.lista_sms.add(str);
        SmsActivity.adapter.notifyDataSetChanged();
    }
}

}`

有没有人知道如何在不切换回MainActivity的情况下更新列表并再次使用SmsActivity?

1 个答案:

答案 0 :(得分:-1)

我看到你使用静态方法更新你的视图,如果可能的话尝试使用观察者模式。别试试这个

myListView.invalidateViews();

基于观察者模式的广播接收器的示例。

  public class MainActivity extends Activity implements
            Observer {
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            BroadcastObserver bco = new BroadcastObserver();
            bco.addObserver(this);
        }

        @Override
        public void update() {
            //TODO: call your desired function
        }
    }

BroadcastObserver.java

public class BroadcastObserver extends Observable {
    private void triggerObservers() {
        setChanged();
        notifyObservers();
    }

    public void change() {
        triggerObservers();
    }
}

@Override
public void onReceive(Context context, Intent intent) {
    BroadcastObserver bco = new BroadcastObserver();
    bco.change();
}