首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当应用程序在后台时,自定义通知音不起作用

当应用程序在后台时,自定义通知音不起作用
EN

Stack Overflow用户
提问于 2019-04-28 14:41:58
回答 1查看 1.5K关注 0票数 1

我正在尝试使用自定义通知音调。当应用程序运行时,音调工作得很好,但当应用程序在后台时,会播放默认音调。此外,当应用程序不活动时接收到通知消息时,振动也不工作

我尝试了以下几种方法:

我的Messenging Service类。

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

发布于 2019-04-29 05:04:06

你可以通过发送通知的方式向你的应用推送通知给你的应用,当你的应用关闭时,根据一些参数转到fire base。

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

Fire base Cloud Messaging

它会向你的应用程序推送通知,如果它关闭了,那么它会让用户通过按下通知按钮打开应用程序,如果你想向用户显示通知,让他们直接转到同一帐户的其他应用程序,当应用程序将被使用时,这两种情况都会发生在这个代码中:

创建一流的MyFirebaseMessagingService

代码语言:javascript
复制
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;
    }
}


    }

创建另一个类FirebaseIDService以获取fire base的实例id服务

代码语言:javascript
复制
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();

}

将类名设为LikeService

代码语言:javascript
复制
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;
}
    }

要使用firebase支持Oreo的通知功能,请不要忘记创建通道,此通道在您的第一个启动器活动的中进行初始化。

在你项目的oncreate中,第一个启动器活动包括这些通道;

代码语言:javascript
复制
   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);

    }

现在,您必须将Firebase服务类放在应用程序标记下的Mainfest中:

代码语言:javascript
复制
      <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>

现在在你的设备上运行你的应用程序,然后使用fire base推送通知,确保你的代码正确集成,然后运行app:,并转到fire base cloud messaging:

根据你的应用程序将数据放入照片中:当它关闭时:

如果您的应用程序正在使用中,那么您的数据提前写入选项将显示您的同一帐户的促销应用程序的数据,请不要在此处使用其他帐户应用程序,

确保您的密钥与上述类中的onMessagede在MyFirebaseMessagingService类中接收到的密钥类似

喜欢

标题、消息、applink、imageurl

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55887711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档