我有一个短信阅读器应用程序,将发件人号码和消息正文显示在自定义列表视图中。对于传入的消息,我已经注册了广播接收器并填充了列表视图。
每当新消息进来时,广播接收器就能获取到它,但我想将这些数据传递到活动中。
代码片段如下:
MainActivity.java
我能够在最初将所有信息接收到列表视图中,但我希望ListView在新消息到达时能自动更新。
每当新消息进来时,广播接收器就能获取到它,但我想将这些数据传递到活动中。
代码片段如下:
MainActivity.java
public class MainSmsActivity extends Activity{
private ListView smsList;
SmsAdapter smsAdapter;
private SmsDao smsDao;
private List<SmsDao> smsDataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_demo);
smsDataList = new ArrayList<SmsDao>();
Intent intent = new Intent();
intent.setAction("com.mobile.sms.IncomingSms");
sendBroadcast(intent);
populateSms();
}
public void populateSms(){
Uri inboxURI = Uri.parse("content://sms/inbox");
String[] reqCols = new String[] { "_id", "address", "body", "date" };
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(inboxURI, reqCols, null, null, null);
smsDataList.clear();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
smsDao = new SmsDao();
smsDao.setMessageBody(cursor.getString(1));
smsDao.setSenderNo(cursor.getString(2));
smsDao.setMessageTime(cursor.getLong(3));
smsDataList.add(smsDao);
}
smsAdapter = new SmsAdapter(this,smsDataList);
smsList.setAdapter(smsAdapter);
smsAdapter.notifyDataSetChanged();
cursor.close();
}
}
IncomingSms.Java
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
int duration = Toast.LENGTH_LONG; // HERE I WANT TO SEND MESSAGE BODY TO THE MAIN ACTIVITY CLASS
Toast toast = Toast.makeText(context,
"senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
我能够在最初将所有信息接收到列表视图中,但我希望ListView在新消息到达时能自动更新。
com.mobile.sms.IncomingSms
这种类型过滤 GCM 消息或其他类型的消息。 - prakashthis.IncomingSms
。 - prakash