我有以下代码来显示listview中收到的消息:
package com.example.smsTest;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class SMSReceiverActivity extends ListActivity {
private BroadcastReceiver mIntentReceiver;
ListView listview;
ArrayAdapter<String> arrayAdpt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smsreceiver);
listview=this.getListView();
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter("SmsMessage.intent.MAIN");
mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("get_msg");
//Process the sms format and extract body & phoneNumber
msg = msg.replace("\n", "");
String body = msg.substring(msg.lastIndexOf(":")+1, msg.length());
String pNumber = msg.substring(0,msg.lastIndexOf(":"));
//Add it to the list or do whatever you wish to
ArrayList<String> bodyarr=new ArrayList<String>();
bodyarr.add(body);
arrayAdpt = new ArrayAdapter<String>(SMSReceiverActivity.this, android.R.layout.simple_list_item_1,
bodyarr);
listview.setAdapter(arrayAdpt);
arrayAdpt.notifyDataSetChanged();
}
};
this.registerReceiver(mIntentReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(this.mIntentReceiver);
}
}
然而,问题是之前的消息被覆盖了。我尝试添加arrayAdpt.notifyDataSetChanged();
代码无效。
我在这里也阅读了很多答案,但它不能解决我的代码问题。
请帮助。
答案 0 :(得分:2)
每次收到新邮件时,您都会创建一个全新的空列表,这就是为什么以前的邮件总是会被覆盖的。
相反,将bodyarr和arrayAdpt的声明移动到类字段,以便每次收到新消息时都可以共享和修改它们:
private ArrayList<String> bodyarr = new ArrayList<String>();
private ArrayAdapter<String> arrayAdpt;
在onCreate中,您应该为ListView设置列表适配器:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smsreceiver);
listview = this.getListView();
arrayAdpt = new ArrayAdapter<String>(SMSReceiverActivity.this, android.R.layout.simple_list_item_1,
bodyarr);
listview.setAdapter(arrayAdpt);
}
然后,在您的广播接收器的onReceive方法中,除了使用现有的列表和数组适配器之外,您几乎可以完成以前所做的操作,这样您已经添加的内容就不会被覆盖:
mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("get_msg");
//Process the sms format and extract body & phoneNumber
msg = msg.replace("\n", "");
String body = msg.substring(msg.lastIndexOf(":")+1, msg.length());
String pNumber = msg.substring(0,msg.lastIndexOf(":"));
bodyarr.add(body);
arrayAdpt.notifyDataSetChanged();
}