我意識到,這裏有一些問題,但我認爲我的代碼是真的不同於他們(我是一個初學者),我無法理解他們的答案!刷新我的ListView,每當我有一個新的短信
所以我想刷新我的ListView每次我收到一條短信,我試圖使用cursor.requery();
和一些方法,我發現谷歌,但它仍然無法正常工作。
這是我的代碼:
public class SMSActivity extends Activity implements OnItemClickListener {
ArrayList<String> smsList = new ArrayList<String>();
// String ADDRESS[];
// int total = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://sms/inbox"), null, null,
null, null);
int indexBody = cursor.getColumnIndex("body");
int indexAddr = cursor.getColumnIndex("address");
if (indexBody < 0 || !cursor.moveToFirst())
return;
smsList.clear();
do {
String str = "Sender : " + cursor.getString(indexAddr) + "\n"
+ cursor.getString(indexBody);
smsList.add(str);
// ADDRESS[total] = cursor.getString(indexAddr);
// total++;
} while (cursor.moveToNext());
ListView lvSms = (ListView) findViewById(R.id.SMSList);
lvSms.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, smsList));
// cursor.requery();
lvSms.setOnItemClickListener(this);
}
編輯: 而這正是我與廣播接收器擴展它的類:
public class SMSReceiver extends BroadcastReceiver {
private static final int NOTIF_ID = 0;
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Bundle bundle = arg1.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
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 += "You Get New SMS from " + msgs[i].getOriginatingAddress();
str += " :"; str += msgs[i].getMessageBody().toString();
str += "\n";
Toast.makeText(arg0, str, Toast.LENGTH_SHORT).show();
NotificationManager nm = (NotificationManager) arg0.getSystemService(Context.NOTIFICATION_SERVICE);
String tickerText = str;
Notification notif = new Notification(R.drawable.ic_launcher, tickerText, System.currentTimeMillis());
notif.flags = Notification.FLAG_AUTO_CANCEL;
String contentTitle = msgs[i].getOriginatingAddress();
String contentText = msgs[i].getMessageBody().toString();
Intent intent = new Intent(arg0, SMSReply.class);
PendingIntent pi = PendingIntent.getActivity(arg0, 0, intent, 0);
notif.setLatestEventInfo(arg0, contentTitle, contentText, pi);
notif.defaults = Notification.DEFAULT_ALL;
nm.notify(NOTIF_ID, notif);
String tempSMS = msgs[i].getOriginatingAddress();
Intent pass = new Intent();
Bundle bundlePass = new Bundle();
bundlePass.putString("key", tempSMS);
pass.putExtras(bundlePass);
}
}
}
我不知道如何這兩個類鏈接,以便每次BroadcastReceiver工作(新短信來)我的ListView將更新(就像你的手機短信應用程序)
謝謝所有。
你告訴列表應該在收到短信時更新。您的Braodcast Receiver在哪裏? – 2012-03-01 10:10:39
錯誤..我有它在另一個類...我會更新我的問題,謝謝先生:D – 2012-03-01 10:24:43