Thursday, March 16, 2017

Cordova - Notify background running service

Leave a Comment

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?

2 Answers

Answers 1

when i click this notification, it's moving to app info activity. But i want to move to my main activity to achieve this change this line

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

to this line

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

Hope it helps you

Answers 2

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); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment