Cordova - 通知后台运行服务

6
我正在使用Cordova构建我的Android应用程序。由于Android会杀死服务,所以我绑定了一个带有通知的服务,以避免服务被杀死。
以下是我绑定带有通知的服务的方法。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    context = this.getApplicationContext();
    notifyService();

    return START_NOT_STICKY;
}

private void notifyService() {
    String package_name = this.getApplication().getPackageName();

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

    Bitmap icon = BitmapFactory.decodeResource(getResources(),
            this.getApplication().getResources().getIdentifier("icon", "drawable-hdpi", package_name));

    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("Smart Home")
            .setContentText("Smart Home running in background")
.setSmallIcon(this.getApplication().getResources().getIdentifier("icon", "drawable-hdpi", package_name))
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .build();

    startForeground(notificationId, notification);
} 

这是输出

enter image description here

通知已生成,但通知标题未按我设置的那样显示。另外,当我点击此通知时,它会跳转到应用程序信息活动页面。但我想要跳转到我的主要活动页面。

有没有人遇到过这个问题?或者我的代码需要更改以适用于cordova?


你想把Cordova通知应用程序作为后台服务吗?这是你的问题吗? - Gandhi
有关此事有任何更新吗? - Gandhi
@Gandhi,我想通了。问题出在我的待处理意图上。 - Ijas Ahamed N
@Gandhi 这是我的第一个 Cordova 项目。我在 Android Studio 项目中尝试了我的先前代码,它可以正常工作。所以我认为问题出在 Cordova 上。现在我已经取消标记 Cordova。谢谢。 - Ijas Ahamed N
感谢提供信息。 - Gandhi
显示剩余5条评论
2个回答

3
当我点击该通知时,它会跳转到应用程序信息活动页面。但我想要跳转到我的主要活动页面。为了实现这个目标,修改这行代码为:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

到这一行

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

希望它能够帮到您。

3

经过长时间的尝试,我终于弄清楚了。问题出在我的待处理意图活动名称上。下面的代码对我有用:

String package_name = this.getApplication().getPackageName();
Intent notificationIntent = context.getPackageManager().getLaunchIntentForPackage(package_name);

接受 Naresh Kumar 的答案并使用这个解决方案有什么问题吗? - Nick Cardoso
@NickCardoso 对不起,我没有说明我的待处理意图有什么问题。我传递给pendingIntent的NotificationIntent是不正确的。它应该是Intent notificationIntent = context.getPackageManager().getLaunchIntentForPackage(package_name); - Ijas Ahamed N
很好的澄清,你应该只限制回答中改变的行,以使其更清晰。 - Nick Cardoso

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接