简体   繁体   中英

I want to create a service which run in background continuously and receive fire base notification

I'm new to Stackoverflow and currently working on an app that processes incoming notification from fire base and open the my application. As I was searching for a solution. The goal is to receive the notification even when app is in background and screen is off (phone locked). Or even my app killed but I want still my notification receive by the app like whatsapp. In whatsapp all notification receive even phone is locked or app is killed, I want do same thing but I am new in android development so I cant understand how to do this.

When my App is in foreground, all notification are recognized by the Receiver. Even when app is in background but my phone is still on, I can receive those messages. The strange things happen here:

App is in foreground and I turn the screen off -->notification are recognized. App is in background and I turn the screen off -->notification wont be recognized.

The Big strange thing is my goal achieved in my old micromax Unite 3 mobile. In this mobile I receive notification even my was background or killed but in my redmi note 3 when app has killed notification not recognised.

I want solution for this. I want my notification recognized even app is foreground, background or killed in all version of os and mobile phones.

I user simple onMessageReceived() method of firebase service code is below

    public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    if(remoteMessage.getData()!=null)
            sendNotification(remoteMessage);
}

private void sendNotification(RemoteMessage remoteMessage) {
    Map<String,String> data=remoteMessage.getData();
    String title=data.get("title");
    String content=data.get("content");

    NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID="Gov_Job";

    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
    {
        //Only active for Android o and higher because it need Notification Channel
        @SuppressLint("WrongConstant") NotificationChannel notificationChannel=new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                "GovJob Notification",
                NotificationManager.IMPORTANCE_MAX);

        notificationChannel.setDescription("GovJob channel for app test FCM");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{0,1000,500,1000});
        notificationChannel.enableVibration(true);

        notificationManager.createNotificationChannel(notificationChannel);

    }

    NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

    notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            //.setSmallIcon(android.support.v4.R.drawable.notification_icon_background)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setTicker("Hearty365")
            .setContentTitle(title)
            .setContentText(content)
            .setContentInfo("info");

    notificationManager.notify(1,notificationBuilder.build());




}   

For getting this facility, I use BroadcastReceiver and Android Notification Service `

package com.alarmmanager_demo;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import static android.support.v4.content.WakefulBroadcastReceiver.startWakefulService;

/**
 * Created by sonu on 09/04/17.
 */

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "ALARM!! ALARM!!", Toast.LENGTH_SHORT).show();

        //Stop sound service to play sound for alarm
        context.startService(new Intent(context, AlarmSoundService.class));

        //This will send a notification message and show notification in notification tray
        ComponentName comp = new ComponentName(context.getPackageName(),
                AlarmNotificationService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));

    }


}
`

In firebase this is known as Firebase Cloud Messaging. In this case, first I connect my apps with firebase. Then I implemented the firebase-messaging in my build.gradle(module-app) implementation 'com.google.firebase:firebase-messaging:11.8.0' .

Then I make this class which extends FirebaseInstanceIdService. Because Firebase provide individual id for individual apps.

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

String REG_TOKEN="REG_TOKEN";

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(REG_TOKEN,"Token   " +refreshedToken);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.


}

}

Then I make another class which extends FirebaseMessagingService.. `public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Intent intent=new Intent(this,MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationbuilder= new NotificationCompat.Builder(this);
    notificationbuilder.setContentTitle("FOR NOTIFICATION");
    notificationbuilder.setContentText(remoteMessage.getNotification().getBody());
    notificationbuilder.setAutoCancel(true);
    notificationbuilder.setSmallIcon(R.mipmap.ic_launcher);
    notificationbuilder.setContentIntent(pendingIntent);
    NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,notificationbuilder.build());

}

}

enter code here

After all I send a message from firbase console. which is received by my phone as a notification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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