短信应用程序的android通知

时间:2014-07-01 04:08:36

标签: android sms android-notifications

我正在创建短信应用,我想为每个电话号码提供差异通知。此外,每个通知都应显示msg中未读取的消息计数。我正在使用此代码,但它删除旧通知并将其替换为新通知。

public class SmsReceiver extends BroadcastReceiver {

ArrayList<String> your_array_list = new ArrayList<String>();
@SuppressLint("NewApi")
@Override
public void onReceive(Context context, Intent intent) {
    // ---get the SMS message passed in---
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    String str = "";
    String str2 = "";
    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]);

            str2 += msgs[i].getOriginatingAddress();
            // str2 += " :";
            str += msgs[i].getMessageBody().toString();
        }

        Uri lookupUri = Uri.withAppendedPath(
                PhoneLookup.CONTENT_FILTER_URI, Uri.encode(str2));
        Cursor c = context.getContentResolver().query(lookupUri,
                new String[] { ContactsContract.Data.DISPLAY_NAME }, null,
                null, null);
        try {
            c.moveToFirst();
            String displayName = c.getString(0);
            str2 = displayName;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            c.close();
        }

        Intent i = new Intent(context, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, i, 0);

        String uri = "tel:" + str2;
        Intent iph = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
        PendingIntent pCall = PendingIntent.getActivity(context, 0, iph, 0);

        // Build notification

        Notification noti = new Notification.Builder(context)
                .setStyle(new Notification.BigTextStyle().bigText(str))
                .setContentTitle("New sms from " + str2)
                .setContentText(str)
                .setSmallIcon(R.drawable.ic_action_chat)
                .setContentIntent(pIntent)
                .addAction(R.drawable.ic_action_call, "Call", pCall)
                .addAction(R.drawable.ic_action_accept, "Read", pIntent)
                .addAction(R.drawable.ic_action_discard, "Delete", pIntent)
                .build();

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(context.NOTIFICATION_SERVICE);
        // hide the notification after its selected
        noti.flags |= Notification.FLAG_AUTO_CANCEL;
        // notification
        notificationManager.notify(0, noti);
    }
}

}

所以如何解决此问题并显示通知计数。 当我点击一些动作通知时也不会消失。如何解决这个问题。 谢谢

1 个答案:

答案 0 :(得分:0)

notificationManager.notify(0, noti);

您放在此处的0是您的通知ID。因此,如果您对每个通知使用0,通知将会被替换。我们的想法是为每个通知使用不同的ID。