简体   繁体   English

无法从服务启动前台通知?

[英]Unable to start foreground notification from Service?

I want to start a foreground notification from a service.Here is my code: 我想从服务启动前台通知,这是我的代码:

Manifest : 清单:

<receiver android:name=".PowerConnectionReceiver">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
        </intent-filter>
</receiver>

Broadcast Receiver : 广播接收器

@Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
            Toast.makeText(context, "Charger connected (#)", Toast.LENGTH_SHORT).show();
            Intent startIntent = new Intent(context, NotificationService.class);
            startIntent.setAction("a_abhi_apps.batterychargenotifier.action.startforeground");
            context.startService(startIntent);
        } else {
            intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
            Toast.makeText(context, "Charger disconnected (#)", Toast.LENGTH_SHORT).show();
stopIntent.setAction("a_abhi_apps.batterychargenotifier.action.stopforeground");
            }
        }

NotificationService.java : NotificationService.java

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent.getAction().equals("a_abhi_apps.batterychargenotifier.action.startforeground")) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentTitle("Charging ")
                    .setContentText("Phone is charging");

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

            // Add as notification
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//            manager.notify(0, builder.build());
            startForeground(0, builder.build());
        } else if (intent.getAction().equals("a_abhi_apps.batterychargenotifier.action.stopforeground")) {
            stopForeground(true);
            stopSelf();
        }
        return START_STICKY;
    }

I have declared broadcast receiver in manifest as it receives power state changed.So there is no related code in MainActivity. 我已经在清单中声明了广播接收器,因为它接收到电源状态已更改。因此MainActivity中没有相关代码。

I have commented this line in NotificationService.java : 我已经在NotificationService.java中注释了这一行:

manager.notify(0, builder.build());

I get notification if i remove the comment.But i would like to make it stick to the notification space,so that i can use that service to perform some other actions. 如果删除评论,我会收到通知。但是我想使其保持在通知空间内,以便我可以使用该服务执行其他一些操作。

But i am unable to make it as a foreground notification. 但是我无法将其作为前台通知。

Try this 尝试这个

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

    NotificationCompat.Builder note = new NotificationCompat.Builder(this)
            .setContentTitle(getString(R.string.name))
            .setSmallIcon(R.drawable.quantum_ic_refresh_white_24);

    note.setOnlyAlertOnce(true);
    note.setOngoing(true);
    note.setWhen( System.currentTimeMillis() );
    note.setAutoCancel(false);
    note.setContentText(getString(R.string.downloading_new_teachkits));

    Notification notification = note.build();
    mNotificationManager.notify(notifyID, notification );

You can follow below Code :- 您可以按照以下代码进行:-

 private static int notification_id=1001;

    NotificationCompat.Builder mBuilder;
    mBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher3)
                        .setContentTitle(title)
                        .setContentText(DeviceName)
                        .setSubText(timestamp)
                        .setVisibility(visibility)
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setVibrate(vibrate)
                        .setOngoing(true)
                        .setFullScreenIntent(null, true);

    Intent resultIntent = new Intent(this, NotificationActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);

    NotificationManagerCompat mNotificationManager = (NotificationManagerCompat) NotificationManagerCompat.from(this);
    Notification notification = mBuilder.build();


            notification.defaults |= Notification.DEFAULT_VIBRATE;
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(notification_id, notification);

    startForeground (notification_id,  notification)
    notification_id = notification_id + 1;

You have to change your notification id in startForeground(0, builder.build()) . 您必须在startForeground(0,builder.build())中更改通知ID。 You can't use 0 as your notification id. 您不能使用0作为通知ID。

From here : 这里

The identifier for this notification as per NotificationManager.notify(int, Notification); 根据NotificationManager.notify(int,Notification);的此通知的标识符; must not be 0 . 不能为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM