在android中获取4.1及以上版本的通知

时间:2013-10-24 09:41:58

标签: android android-service

如何使用4.0以上的辅助功能服务在Android中获取通知?

为什么onAccessibilityEvent(AccessibilityEvent event)没有调用当Notification在4.0以上时触发 请给出正确的建议

提前致谢

@Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

        final int eventType = event.getEventType();
        System.out.println("MyServ.onAccessibilityEvent()");
        switch (eventType) {
        case AccessibilityEvent.TYPE_VIEW_FOCUSED:
            Toast.makeText(getApplicationContext(), "Notification fired",
                    Toast.LENGTH_LONG).show();
            break;
        case AccessibilityEvent.TYPE_ANNOUNCEMENT:
            Toast.makeText(getApplicationContext(), "Type is Announcement",
                    Toast.LENGTH_LONG).show();
            break;
        default:
            break;
        }

    }

onServiceConnected()

@Override
    protected void onServiceConnected() {
        super.onServiceConnected();
    AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN;
        setServiceInfo(info);
}

1 个答案:

答案 0 :(得分:1)

试试这段代码:

    private void generateNotification(Context context, String message,
        long when, String query) {

    int icon = R.drawable.icon;
         long when = System.currentTimeMillis();
    String appname = context.getResources().getString(R.string.app_name);
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    Notification notification;

    Intent intent = new Intent(context, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            intent, 0);

        if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
            notification = new Notification(icon, message, when);
            notification.setLatestEventInfo(context, appname, message,
                    contentIntent);
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify((int) when, notification);

        } else {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(
                    context);
            notification = builder.setContentIntent(contentIntent)
                    .setSmallIcon(icon).setTicker(appname).setWhen(when)
                    .setAutoCancel(true).setContentTitle(appname)
                    .setContentText(message).build();

            notificationManager.notify((int) when, notification);

        }

}

您可以在generateNotification()中调用onAccessibilityEvent()方法,系统会显示通知。