应用程序在后台时自定义通知音不起作用 [英] Custom notification tone not working when the application is in the background

查看:69
本文介绍了应用程序在后台时自定义通知音不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用自定义通知音.应用程序运行时音调工作正常,但应用程序在后台时播放默认音调.当应用程序处于非活动状态时收到通知消息时,振动也不起作用

我试过如下:

我的消息服务类.

public class MyFirebaseMessagingService 扩展 FirebaseMessagingService{private static final String TAG = "MyFirebaseMsgService";Utilities utils = new Utilities();通知通知;@覆盖public void onMessageReceived(RemoteMessage remoteMessage) {如果 (remoteMessage.getData() != null) {sendNotification(remoteMessage.getData().get("message"));Log.e(TAG,remoteMessage.getData().get("message"));}别的{utils.print(TAG,"FCM 通知失败");}}私人无效sendNotification(字符串messageBody){长[] v = {500,1000};如果 (!isAppIsInBackground(getApplicationContext())) {utils.print(TAG,"前景");Log.e(TAG,"通知"+messageBody);Intent intent = new Intent(this, MainActivity.class);intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);intent.putExtra("push", true);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,PendingIntent.FLAG_ONE_SHOT);NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setContentText(messageBody).setAutoCancel(false).setVibrate(v).setContentIntent(pendingIntent);notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder), 1);通知 = notificationBuilder.build();notification.sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone);notification.defaults=Notification.DEFAULT_LIGHTS |通知.DEFAULT_VIBRATE;通知管理器通知管理器 =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);NotificationManager.notify(0, 通知);}别的{if(messageBody.equalsIgnoreCase("新的来车")){Intent intent = new Intent(this, MainActivity.class);intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,PendingIntent.FLAG_ONE_SHOT);Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setContentText(messageBody).setAutoCancel(false).setVibrate(v).setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone)).setContentIntent(pendingIntent);notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder), 1);通知管理器通知管理器 =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);通知 = notificationBuilder.build();notification.defaults=Notification.DEFAULT_LIGHTS |通知.DEFAULT_VIBRATE;notification.sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone);NotificationManager.notify(0, 通知);}别的{Intent intent = new Intent(this, MainActivity.class);intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);intent.putExtra("push", true);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,PendingIntent.FLAG_ONE_SHOT);NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setContentText(messageBody).setAutoCancel(false).setVibrate(v).setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone)).setContentIntent(pendingIntent);notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder), 1);通知管理器通知管理器 =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);通知 = notificationBuilder.build();notification.sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone);NotificationManager.notify(0, 通知);}}}私有 int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(),R.color.colorPrimary));返回 R.mipmap.ic_launcher;}别的 {返回 R.mipmap.ic_launcher;}}公共静态布尔 isAppIsInBackground(上下文上下文){boolean isInBackground = true;ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);如果 (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {列表runningProcesses = am.getRunningAppProcesses();for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {如果(processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){for (String activeProcess : processInfo.pkgList) {如果(activeProcess.equals(context.getPackageName())){isInBackground = false;}}}}} 别的 {列表taskInfo = am.getRunningTasks(1);ComponentName componentInfo = taskInfo.get(0).topActivity;if (componentInfo.getPackageName().equals(context.getPackageName())) {isInBackground = false;}}返回 isInBackground;

解决方案

您可以通过发送通知向您的应用推送通知,以便用户与 fire base 互动,当您的应用关闭时,根据某些参数转到 fire base .

在执行此操作之前,请先确保您的项目已添加到 Fire base 中:否则将您的项目与包名称、指纹和 google_services.json 文件一起添加到您的项目的应用文件夹中.

如果您的应用正在使用中,那么您的数据预先写入选项将显示,它是关于您的同一帐户的促销应用的数据,请不要在此处使用其他帐户应用,

确保您的密钥应与上述类中的 onMessagede Recieved in MyFirebaseMessagingService 类相同

喜欢

标题、消息、应用链接、图片网址

I am trying to use the custom notification tone. The tone is working fine when the application running but the default tone is played when the app is in the background. Also the vibration is not working when the notification message is received when the application is not active

I have tried as follows:

My Messenging Service class.

public class MyFirebaseMessagingService extends FirebaseMessagingService{

private static final String TAG = "MyFirebaseMsgService";
Utilities utils = new Utilities();
Notification notification;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getData() != null) {
        sendNotification(remoteMessage.getData().get("message"));
        Log.e(TAG,remoteMessage.getData().get("message"));
    }else{
        utils.print(TAG,"FCM Notification failed");
    }
}
private void sendNotification(String messageBody) {
    long[] v = {500,1000};

    if (!isAppIsInBackground(getApplicationContext())) {

        utils.print(TAG,"foreground");
        Log.e(TAG,"Notifcation"+messageBody);
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("push", true);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);


            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(messageBody)
                    .setAutoCancel(false)
                    .setVibrate(v)
                    .setContentIntent(pendingIntent);

            notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder), 1);

        notification = notificationBuilder.build();
        notification.sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone);
        notification.defaults=Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;

            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0, notification);
    }
    else{
        if(messageBody.equalsIgnoreCase("New Incoming Ride")){
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                   PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(messageBody)
                    .setAutoCancel(false)
                    .setVibrate(v)
                    .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone))
                   .setContentIntent(pendingIntent);

            notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder), 1);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notification = notificationBuilder.build();
            notification.defaults=Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;
            notification.sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone);
            notificationManager.notify(0, notification);
        }
        else{
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("push", true);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(messageBody)
                    .setAutoCancel(false)
                    .setVibrate(v)
                    .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone))
                   .setContentIntent(pendingIntent);

            notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder), 1);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notification = notificationBuilder.build();
            notification.sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone);
            notificationManager.notify(0, notification);
        }
    }
}

private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(),R.color.colorPrimary));
        return  R.mipmap.ic_launcher;
    }else {
        return R.mipmap.ic_launcher;
    }
}
public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }
    return isInBackground;

解决方案

You can push notification to your app for user engaging with fire base by sending notification,when your app is closed,on basis of some parameters go to fire base .

Make sure Your Project is Added in Fire base first before doing this at all:otherwise add your project in fire base with package name,fingerprint and google_services.json file in app folder of your project .

Fire base Cloud Messaging

it will push notification to your app, if its closed then it let the user to open the app via notification pressed, and if you wants to show notification to the user to direct to another apps of the same account , when the app will be in use both will happened with this code:

Create you first class MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
private static final String ADMIN_CHANNEL_ID ="admin_channel";
private NotificationManager notificationManager;


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    if (remoteMessage.getData().size()>0){

        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setData(Uri.parse(remoteMessage.getData().get("applink")));
        PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        final PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0 /* Request code */, notificationIntent,
                PendingIntent.FLAG_ONE_SHOT);

        int notificationId = new Random().nextInt(60000);
        Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("imageurl"));

        Intent likeIntent = new Intent(this,LikeService.class);
        likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
        likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get("message"));
        PendingIntent likePendingIntent = PendingIntent.getService(this,
                notificationId+1,likeIntent, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            setupChannels();

        }

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
                        .setLargeIcon(bitmap)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle(remoteMessage.getData().get("title"))
                        .setStyle(new NotificationCompat.BigPictureStyle()
                                .setSummaryText(remoteMessage.getData().get("message"))
                                .bigPicture(bitmap))/*Notification with Image*/
                        .setContentText(remoteMessage.getData().get("message"))
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .addAction(R.drawable.icon,
                                getString(R.string.notification_add_to_cart_button),likePendingIntent)
                        .setContentIntent(pendingIntent);

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


    }

}


@RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(){
    CharSequence adminChannelName = getString(R.string.notifications_admin_channel_name);
    String adminChannelDescription = getString(R.string.notifications_admin_channel_description);

    NotificationChannel adminChannel;
    adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW);
    adminChannel.setDescription(adminChannelDescription);
    adminChannel.enableLights(true);
    adminChannel.setLightColor(Color.RED);
    adminChannel.enableVibration(true);
    if (notificationManager != null) {
        notificationManager.createNotificationChannel(adminChannel);
    }
}



public Bitmap getBitmapfromUrl(String imageUrl) {
    try {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        return BitmapFactory.decodeStream(input);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}


    }

Create another class FirebaseIDService to get instance id service of fire base

public class FirebaseIDService extends FirebaseInstanceIdService {


public static final String FIREBASE_TOKEN = "firebase token";

@Override
public void onTokenRefresh() {
    super.onTokenRefresh();

    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    SharedPreferences preferences =
            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    preferences.edit().putString(FIREBASE_TOKEN, refreshedToken).apply();

}

Make class Name LikeService

public class LikeService extends Service {

private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
    }

To Support Notification at Oreo with firebase dont forget to create Channels and this channels initialize in your First Launcher Activity.

in oncreate of your project first launcher activity include these channels;

   String channelId = "1";
    String channel2 = "2";

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(channelId,
                "Channel 1", NotificationManager.IMPORTANCE_HIGH);

        notificationChannel.setDescription("This is BNT");
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setShowBadge(true);
        notificationManager.createNotificationChannel(notificationChannel);

        NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
                "Channel 2",NotificationManager.IMPORTANCE_MIN);

        notificationChannel.setDescription("This is bTV");
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setShowBadge(true);
        notificationManager.createNotificationChannel(notificationChannel2);

    }

Now you have to put your Firebase service class in Mainfest under application tag:

      <service android:name=".activities.services.MyFirebaseMessagingService"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>

            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            <action android:name="com.google.android.c2dm.intent.RECEIVE"/>

        </intent-filter>

    </service>

    <service android:name=".activities.services.FirebaseIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

Now run your app on your device before push notification with fire base make sure your code is integrated correctly then run app: and go to fire base cloud messaging:

put data as in photo according to your app: when its closed:

if your app is in use then your data written in advance option will show, its data about your promotional app of the same account, don use another account app here,

make sure your key should be like in above class as onMessagede Recieved in MyFirebaseMessagingService class

like

title ,message,applink,imageurl

这篇关于应用程序在后台时自定义通知音不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆