android监听短信并判断是否未读

final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
BroadcastReceiver SMSbr = new BroadcastReceiver() {
 
        @Override
        public void onReceive(Context context, Intent intent) {
                              Bundle bundle = intent.getExtras();
                if (bundle != null) {
                                                Object[] pdus = (Object[]) bundle.get("pdus");
                        final SmsMessage[] messages = new SmsMessage[pdus.length];
                        for (int i = 0; i < pdus.length; i++)
                                messages[i] = SmsMessage
                                                .createFromPdu((byte[]) pdus[i]);
                        if (messages.length > -1) {
                              .
                                String smsToast = "New SMS received from "
                                                + messages[0].getOriginatingAddress() + "\n'"
                                                + messages[0].getMessageBody() + "'";
                                Toast.makeText(context, smsToast, Toast.LENGTH_LONG)
                                                .show();
                        }
                }
        }
};

IntentFilter SMSfilter = new IntentFilter(SMS_RECEIVED);
this.registerReceiver(SMSbr, SMSfilter); 

private boolean checkSMS() {
        // Sets the sms inbox's URI
        Uri uriSMS = Uri.parse("content://sms");
        Cursor c = getBaseContext().getContentResolver().query(uriSMS, null,
                        "read = 0", null, null);
        // Checks the number of unread messages in the inbox
        if (c.getCount() == 0) {
                return false;
        } else
                return true;
} 

<uses-permission id="android.permission.RECEIVE_SMS" />   
<uses-permission id="android.permission.READ_SMS" />  

你可能感兴趣的:(android)