Search code examples
androidandroid-servicecordova-pluginsandroid-notifications

Cordova - Notify background running service


I am using cordova to build my android application. Since android kills service, i am binding service with a notification to avoid service kill.

Here is my method how i bind the service with notification

@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);
} 

Here's the output

enter image description here

Notification is generated but notification title is not as i set. Also, when i click this notification, it's moving to app info activity. But i want to move to my main activity.

Does anyone faced this same issue? Or my code need any change for cordova?


Solution

  • Figured it out after a long try. Problem was with my pending intent activity name. Below code worked for me

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