Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
Ijas Ahamed N Avatar asked Mar 06 '17 05:03

Ijas Ahamed N


2 Answers

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

like image 188
Naresh Kumar Avatar answered Oct 21 '22 02:10

Naresh Kumar


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);
like image 41
Ijas Ahamed N Avatar answered Oct 21 '22 00:10

Ijas Ahamed N