Android通知不会消失

时间:2020-01-05 09:43:07

标签: java android notifications

这是我在应用程序中创建通知的方式:

public class NotificationService extends Service {
    public static final String ACTION_FOREGROUND = "com.tfsapps.generic.FOREGROUND";
    private static final String ACTION_BACKGROUND = "com.tfsapps.generic.BACKGROUND";
    private static final String WIDGET_PLAY = "PLAY";
    static final String WIDGET_PAUSE = "PAUSE";
    private static final String WIDGET_NEXT = "NEXT";
    private static final String WIDGET_BACK = "BACK";

    private static final String CHANNEL_ID = "player_channel";

    @SuppressWarnings("rawtypes")
    private static final Class[] mStartForegroundSignature = new Class[]{int.class, Notification.class};
    @SuppressWarnings("rawtypes")
    private static final Class[] mStopForegroundSignature = new Class[]{boolean.class};

    private NotificationManager mNM;
    private Method mStartForeground;
    private Method mStopForeground;
    private Object[] mStartForegroundArgs = new Object[2];
    private Object[] mStopForegroundArgs = new Object[1];

    public static final int NOTIFICATION_ID = 3232;

    /**
     * This is a wrapper around the new startForeground method, using the older
     * APIs if it is not available.
     */
    void startForegroundCompat(int id, Notification notification) {
        // If we have the new startForeground API, then use it.
        if (mStartForeground != null) {
            mStartForegroundArgs[0] = Integer.valueOf(id);
            mStartForegroundArgs[1] = notification;
            try {
                mStartForeground.invoke(this, mStartForegroundArgs);
            } catch (InvocationTargetException e) {
            } catch (IllegalAccessException e) {
            }
            return;
        }

        callSetForeground(true);
        mNM.notify(id, notification);
    }

    private void callSetForeground(boolean foreground) {
        try {
            Method method = getClass().getMethod("setForeground", boolean.class);
            method.invoke(this, foreground);
        } catch (NoSuchMethodException e) {
            // Too bad!
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }
    }

    private void stopForegroundCompat(int id) {
        if (mStopForeground != null) {
            mStopForegroundArgs[0] = Boolean.TRUE;
            try {
                mStopForeground.invoke(this, mStopForegroundArgs);
            } catch (InvocationTargetException e) {
            } catch (IllegalAccessException e) {
            }
            return;
        }
        mNM.cancel(id);
        callSetForeground(false);
    }

    @Override
    public void onCreate() {
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        try {
            mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature);
            mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature);
        } catch (NoSuchMethodException e) {
            mStartForeground = mStopForeground = null;
        }
    }

    @Override
    public void onDestroy() {
        stopForegroundCompat(R.string.notification_service_started);
    }


    @Override
    public void onStart(Intent intent, int startId) {
        if (intent != null) {
            handleCommand(intent);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            if (intent != null) {
                handleCommand(intent);
                return START_STICKY;
            }
        } catch (Exception e) {
            Logger.e(e);
        }
        return START_STICKY_COMPATIBILITY;
    }

    @SuppressLint("NewApi")
    private void handleCommand(Intent intent) {
        if (ACTION_FOREGROUND.equals(intent.getAction())) {

            final YouTubeFile ytf = PlayerDataManager.getInstance().getYouTubeFile();
            String nowPlayingTitle = "";
            if (ytf != null) {
                nowPlayingTitle = ytf.getTitle();
            }

            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

            long when = System.currentTimeMillis();

            final RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
            ReceiverNotification.s_RemoteView = contentView;

            if (ytf != null) {
                try {
                    Bitmap bmp = ImageLoader.getInstance().loadImageSync(ytf.getImageUrl());
                    contentView.setImageViewBitmap(R.id.icon_fav_notification, bmp);

                } catch (Exception e) {
                    Logger.e(e);
                }
            }

            contentView.setTextViewText(R.id.toptext, nowPlayingTitle);

            Intent rewindIntent = new Intent(this, ReceiverNotification.class);
            rewindIntent.putExtra("ACTION", 0);
            rewindIntent.setAction("REWIND");
            PendingIntent pendingIntent1 = PendingIntent.getBroadcast(getApplicationContext(), 000, rewindIntent,
                    FLAG_UPDATE_CURRENT);
            contentView.setOnClickPendingIntent(R.id.imageButtonPlayLast, pendingIntent1);

            Intent playIntent = new Intent(this, ReceiverNotification.class);
            playIntent.putExtra("ACTION", 1);
            playIntent.setAction("PLAY");
            PendingIntent pendingIntent2 = PendingIntent
                    .getBroadcast(getApplicationContext(), 111, playIntent, FLAG_UPDATE_CURRENT);
            contentView.setOnClickPendingIntent(R.id.imageButtonPlay, pendingIntent2);

            Intent forwardIntent = new Intent(this, ReceiverNotification.class);
            forwardIntent.putExtra("ACTION", 2);
            forwardIntent.setAction("FORWARD");
            PendingIntent pendingIntent3 = PendingIntent.getBroadcast(getApplicationContext(), 222, forwardIntent,
                    FLAG_UPDATE_CURRENT);
            contentView.setOnClickPendingIntent(R.id.imageButtonPlayNext, pendingIntent3);

            Intent exitIntent = new Intent(this, ReceiverNotification.class);
            exitIntent.putExtra("ACTION", 3);
            exitIntent.setAction("EXIT");
            PendingIntent pendingIntent4 = PendingIntent
                    .getBroadcast(getApplicationContext(), 333, exitIntent, FLAG_UPDATE_CURRENT);
            contentView.setOnClickPendingIntent(R.id.exit_icon, pendingIntent4);
            contentView.setViewVisibility(R.id.exit_icon, View.VISIBLE);

            if (PlayerManager.getInstance().isPlaying()) {
                contentView.setImageViewResource(R.id.imageButtonPlay, R.drawable.ic_action_av_pause_light);

            } else {
                contentView.setImageViewResource(R.id.imageButtonPlay, R.drawable.ic_action_av_play_light);
            }

            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(GuiManager.getInstance().getMainActivity(), CHANNEL_ID);
            builder.setContentIntent(contentIntent)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setWhen(when)
                    .setAutoCancel(false).setVibrate(new long[]{0L})
                    .setCustomContentView(contentView);

            if (Build.VERSION.SDK_INT >= 21) {
                builder.setVisibility(Notification.VISIBILITY_PUBLIC);
            }

            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
                builder.setPriority(Notification.PRIORITY_DEFAULT);

            } else {
                createNotificationChannel();
            }

            Notification notification = builder.build();

            notification.flags |= Notification.FLAG_NO_CLEAR;
            notification.defaults |= Notification.DEFAULT_LIGHTS;

            if (mNotificationManager != null) {
                    mNotificationManager.notify(NOTIFICATION_ID, notification);
            }
            startForeground(NOTIFICATION_ID, notification);


        } else if (ACTION_BACKGROUND.equals(intent.getAction())) {
            stopForegroundCompat(R.string.notification_service_started);
        } else {
            // sendWidgetCommand(intent);
        }
    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.notification_channel_title);
            String description = getString(R.string.notification_channel_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    public static PendingIntent getPendingIntentonActivity(Context context, Class C) {
        Intent intentleft = new Intent(context, C);
        intentleft.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intentleft.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return PendingIntent.getActivity(context, 1, intentleft, FLAG_UPDATE_CURRENT);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

这就是我所说的代码:

void showAppNotification() {
        Intent intent = new Intent(NotificationService.ACTION_FOREGROUND);
        intent.setClass(mActivity, NotificationService.class);

        ContextCompat.startForegroundService(mActivity, intent);
    }

我有一个问题,在关闭应用程序后,通知消失并再次返回,知道是什么问题吗?

编辑

compileSdkVersion 28
minSdkVersion 16
targetSdkVersion 28

还有从Service

创建的通知

0 个答案:

没有答案