当我们在另一个应用程序中时,Android 10会发出类似whats应用程序的来电通知

当我们在另一个应用程序中时,Android 10会发出类似whats应用程序的来电通知,android,firebase-cloud-messaging,android-notifications,whatsapp,Android,Firebase Cloud Messaging,Android Notifications,Whatsapp,一旦我们在android 10后台收到FCM推送通知消息,启动活动将受到限制。当我们在另一个应用程序中时,需要像WhatsApp和Skype通知来电这样的解决方案 我们将非常感谢您的帮助 下面是前台服务和时间敏感通知的代码 startForeground(1234,getNotification(IncomingCallContent)) 我找到了解决办法。您需要为此创建一个前台服务。 这也将帮助您在锁屏上显示铃声拨号器。在这段代码中,我添加了铃声和振动 呼叫通知服务 public class

一旦我们在android 10后台收到FCM推送通知消息,启动活动将受到限制。当我们在另一个应用程序中时,需要像WhatsApp和Skype通知来电这样的解决方案

我们将非常感谢您的帮助

下面是前台服务和时间敏感通知的代码

startForeground(1234,getNotification(IncomingCallContent))


我找到了解决办法。您需要为此创建一个前台服务。 这也将帮助您在锁屏上显示铃声拨号器。在这段代码中,我添加了铃声和振动

呼叫通知服务

public class HeadsUpNotificationService extends Service implements MediaPlayer.OnPreparedListener  {
private String CHANNEL_ID = AppController.getInstance().getContext().getString(R.string.app_name)+"CallChannel";
private String CHANNEL_NAME = AppController.getInstance().getContext().getString(R.string.app_name)+"Call Channel";MediaPlayer mediaPlayer;
Vibrator mvibrator;
AudioManager audioManager;
AudioAttributes  playbackAttributes;
private Handler handler;
AudioManager.OnAudioFocusChangeListener afChangeListener;
private boolean status = false;
private boolean vstatus = false;


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Bundle data = null;
    String name="",callType="";
    int NOTIFICATION_ID=120;try {
        audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

        if (audioManager != null) {
            switch (audioManager.getRingerMode()) {
                case AudioManager.RINGER_MODE_NORMAL:
                    status = true;
                    break;
                case AudioManager.RINGER_MODE_SILENT:
                    status = false;
                    break;
                case AudioManager.RINGER_MODE_VIBRATE:
                    status = false;
                    vstatus=true;
                    Log.e("Service!!", "vibrate mode");
                    break;
            }
        }

        if (status) {
            Runnable delayedStopRunnable = new Runnable() {
                @Override
                public void run() {
                    releaseMediaPlayer();
                }
            };

            afChangeListener =  new AudioManager.OnAudioFocusChangeListener() {
               public void onAudioFocusChange(int focusChange) {
                   if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                       // Permanent loss of audio focus
                       // Pause playback immediately
                       //mediaController.getTransportControls().pause();
                       if (mediaPlayer!=null) {
                           if (mediaPlayer.isPlaying()) {
                               mediaPlayer.pause();
                           }
                       }
                       // Wait 30 seconds before stopping playback
                       handler.postDelayed(delayedStopRunnable,
                               TimeUnit.SECONDS.toMillis(30));
                   }
                   else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                       // Pause playback
                   } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                       // Lower the volume, keep playing
                   } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                       // Your app has been granted audio focus again
                       // Raise volume to normal, restart playback if necessary
                   }
               }
           };
             KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);


            mediaPlayer= MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
            mediaPlayer.setLooping(true);
            //mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                 handler = new Handler();


              playbackAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();

                AudioFocusRequest focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
                        .setAudioAttributes(playbackAttributes)
                        .setAcceptsDelayedFocusGain(true)
                        .setOnAudioFocusChangeListener(afChangeListener, handler)
                        .build();
                int res = audioManager.requestAudioFocus(focusRequest);
                if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                      if(!keyguardManager.isDeviceLocked()) {

                          mediaPlayer.start();
                         }

                }
            }else {

                // Request audio focus for playback
                int result = audioManager.requestAudioFocus(afChangeListener,
                        // Use the music stream.
                        AudioManager.STREAM_MUSIC,
                        // Request permanent focus.
                        AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

                if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                    if(!keyguardManager.isDeviceLocked()) {
                        // Start playback
                        mediaPlayer.start();
                    }
                }

            }

        }
        else if(vstatus){
            mvibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            // Start without a delay
            // Each element then alternates between vibrate, sleep, vibrate, sleep...
            long[] pattern = {0, 250, 200, 250, 150, 150, 75,
                    150, 75, 150};

            // The '-1' here means to vibrate once, as '-1' is out of bounds in the pattern array
            mvibrator.vibrate(pattern,0);
            Log.e("Service!!", "vibrate mode start");

        }

    } catch (Exception e) {
        e.printStackTrace();
    }         
         
    if (intent != null && intent.getExtras() != null) {
       
        data = intent.getExtras();
        name =data.getString("inititator");
        if(AppController.getInstance().getCall_type().equalsIgnoreCase(ApplicationRef.Constants.AUDIO_CALL)){
            callType ="Audio";
        }
        else {
            callType ="Video";
        }

    }
    try {
        Intent receiveCallAction = new Intent(AppController.getInstance().getContext(), CallNotificationActionReceiver.class);

        receiveCallAction.putExtra("ConstantApp.CALL_RESPONSE_ACTION_KEY", "ConstantApp.CALL_RECEIVE_ACTION");
        receiveCallAction.putExtra("ACTION_TYPE", "RECEIVE_CALL");
        receiveCallAction.putExtra("NOTIFICATION_ID",NOTIFICATION_ID);
        receiveCallAction.setAction("RECEIVE_CALL");

        Intent cancelCallAction = new Intent(AppController.getInstance().getContext(), CallNotificationActionReceiver.class);
        cancelCallAction.putExtra("ConstantApp.CALL_RESPONSE_ACTION_KEY", "ConstantApp.CALL_CANCEL_ACTION");
        cancelCallAction.putExtra("ACTION_TYPE", "CANCEL_CALL");
        cancelCallAction.putExtra("NOTIFICATION_ID",NOTIFICATION_ID);
        cancelCallAction.setAction("CANCEL_CALL");

        Intent callDialogAction = new Intent(AppController.getInstance().getContext(), CallNotificationActionReceiver.class);
        callDialogAction.putExtra("ACTION_TYPE", "DIALOG_CALL");
        callDialogAction.putExtra("NOTIFICATION_ID",NOTIFICATION_ID);
        callDialogAction.setAction("DIALOG_CALL");

        PendingIntent receiveCallPendingIntent = PendingIntent.getBroadcast(AppController.getInstance().getContext(), 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent cancelCallPendingIntent = PendingIntent.getBroadcast(AppController.getInstance().getContext(), 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent callDialogPendingIntent = PendingIntent.getBroadcast(AppController.getInstance().getContext(), 1202, callDialogAction, PendingIntent.FLAG_UPDATE_CURRENT);

        createChannel();
        NotificationCompat.Builder notificationBuilder = null;
        if (data != null) {
           // Uri ringUri= Settings.System.DEFAULT_RINGTONE_URI;
            notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle(name)
                    .setContentText("Incoming "+callType+" Call")
                    .setSmallIcon(R.drawable.ic_call_icon)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setCategory(NotificationCompat.CATEGORY_CALL)
                    .addAction(R.drawable.ic_call_decline, getString(R.string.reject_call), cancelCallPendingIntent)
                    .addAction(R.drawable.ic_call_accept, getString(R.string.answer_call), receiveCallPendingIntent)
                    .setAutoCancel(true)
                    //.setSound(ringUri)
                    .setFullScreenIntent(callDialogPendingIntent, true);
            
        }

        Notification incomingCallNotification = null;
        if (notificationBuilder != null) {
            incomingCallNotification = notificationBuilder.build();
        }
        startForeground(NOTIFICATION_ID, incomingCallNotification);

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

    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();// release your media player here audioManager.abandonAudioFocus(afChangeListener);
    releaseMediaPlayer();
    releaseVibration();
}

public void createChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        try {
            Uri ringUri= Settings.System.DEFAULT_RINGTONE_URI;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("Call Notifications");
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
           /* channel.setSound(ringUri,
                    new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setLegacyStreamType(AudioManager.STREAM_RING)
                            .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION).build());*/
            Objects.requireNonNull(AppController.getInstance().getContext().getSystemService(NotificationManager.class)).createNotificationChannel(channel);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}public void releaseVibration(){
    try {
        if(mvibrator!=null){
            if (mvibrator.hasVibrator()) {
                mvibrator.cancel();
            }
            mvibrator=null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private void releaseMediaPlayer() {
    try {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.reset();
                mediaPlayer.release();
            }
            mediaPlayer = null;
        }

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

@Override
public void onPrepared(MediaPlayer mediaPlayer) {

}}
服务接收方

CallNotificationActionReceiver

public class CallNotificationActionReceiver extends BroadcastReceiver {


Context mContext;

@Override
public void onReceive(Context context, Intent intent) {
    this.mContext=context;
    if (intent != null && intent.getExtras() != null) {
      
        String action ="";
        action=intent.getStringExtra("ACTION_TYPE");

        if (action != null&& !action.equalsIgnoreCase("")) {
            performClickAction(context, action);
        }

        // Close the notification after the click action is performed.
        Intent iclose = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        context.sendBroadcast(iclose);
        context.stopService(new Intent(context, CallNotificationService.class));

    }


}
private void performClickAction(Context context, String action) {
    if(action.equalsIgnoreCase("RECEIVE_CALL")) {

        if (checkAppPermissions()) {                
        Intent intentCallReceive = new Intent(mContext, VideoCallActivity.class);
        intentCallReceive.putExtra("Call", "incoming");
            intentCallReceive.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            mContext.startActivity(intentCallReceive);               
        }
        else{
                    Intent intent = new Intent(AppController.getInstance().getContext(), VideoCallRingingActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra("CallFrom","call from push");
                    mContext.startActivity(intent);                  
            
        }
    }
    else if(action.equalsIgnoreCase("DIALOG_CALL")){

                // show ringing activity when phone is locked
                Intent intent = new Intent(AppController.getInstance().getContext(), VideoCallRingingActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                mContext.startActivity(intent);
            }

    else {            
        context.stopService(new Intent(context, CallNotificationService.class));
        Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        context.sendBroadcast(it);
    }
}

private Boolean checkAppPermissions() {
    return hasReadPermissions() && hasWritePermissions() && hasCameraPermissions() && hasAudioPermissions();
}

private boolean hasAudioPermissions() {
    return (ContextCompat.checkSelfPermission(AppController.getInstance().getContext(), Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED);
}

private boolean hasReadPermissions() {
    return (ContextCompat.checkSelfPermission(AppController.getInstance().getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
}

private boolean hasWritePermissions() {
    return (ContextCompat.checkSelfPermission(AppController.getInstance().getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
}
private boolean hasCameraPermissions() {
    return (ContextCompat.checkSelfPermission(AppController.getInstance().getContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED);
}
}
我们需要在应用程序选项卡内的清单中设置这两个

清单

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
<uses-permission android:name="android.permission.VIBRATE" />
  <!-- Incoming call  -->
    <service android:name=".CallNotificationService"/>
    <receiver
        android:name=".CallNotificationActionReceiver"
        android:enabled="true">
        <intent-filter android:priority="999">
            <action android:name="ConstantApp.CALL_RECEIVE_ACTION" />
            <action android:name="ConstantApp.CALL_CANCEL_ACTION"/>
        </intent-filter>
    </receiver>
停止通知

getApplicationContext().stopService(new Intent(AppController.getInstance().getContext(), HeadsUpNotificationService.class));
                                    Intent istop = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
                                    getApplicationContext().sendBroadcast(istop);

这可以通过来自FCM的数据消息实现。您需要安装以下内容:

  • 创建扩展FirebaseMessagingService的服务
    。在FCM文档中。我们必须重写服务类中的
    onMessageReceived()
  • 创建全屏意图或显示时间敏感通知。在FCM文档中。在我们的服务中覆盖的
    onMessageReceived()
    中显示此通知
  • 现在,您必须找到从FCM发送数据消息的方法。Firebase控制台不支持此操作。后端必须为此创建一个设置 让我深入了解更多细节

    FCM中有两种不同的消息类型

  • 通知消息:这是常见的消息类型。这可以从FCM控制台中的notification composer发送。这种类型的消息将具有名为title、body等属性。如果我们发送通知消息,则仅当应用程序位于前台时才会调用
    onMessageReceived()
  • 数据消息:无法从FCM控制台中的notification composer发送此消息。此类消息应具有属性数据(有效负载)。这是从服务器发送的,可以采用以下格式:
  • 若我们发送数据消息,
    onMessageReceived()
    将被调用,即使应用程序在后台或不在内存中。这就是我们想要的!


    让我重温一下步骤
    步骤1:这是我们必须创建的唯一服务。我们不必创建任何其他前台服务。那是另一种情况。重写
    onMessageReceived()
    以执行步骤2。

    步骤2:全屏意图或显示时间敏感通知将显示问题中所示的抬头显示通知或显示来电的整个活动。当我们收到第3步中提到的
    onMessageReceived()
    数据消息时,在
    onMessageReceived()中显示此通知。
    

    步骤3:联系服务器发送上面显示的有效负载JSON


    就这样

    这回答了你的问题吗?你能帮我解决这个问题吗?你有什么解决办法吗?我在找Same你有什么办法吗?你有没有找到解决办法?怎么播放铃声?我在这方面遇到了麻烦。你需要使用媒体播放器。非常感谢。但我面临一个问题,当应用程序在后台时服务没有启动您需要从通知服务启动服务当启动广播意图添加标志时:(标志\u活动\u将\u带到\u前台,标志\u活动\u重新排序\u到\u前台,标志\u从\u后台)当使用清单权限锁定屏幕以唤醒锁定时,还可以在启动活动上添加设置
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
    <uses-permission android:name="android.permission.VIBRATE" />
      <!-- Incoming call  -->
        <service android:name=".CallNotificationService"/>
        <receiver
            android:name=".CallNotificationActionReceiver"
            android:enabled="true">
            <intent-filter android:priority="999">
                <action android:name="ConstantApp.CALL_RECEIVE_ACTION" />
                <action android:name="ConstantApp.CALL_CANCEL_ACTION"/>
            </intent-filter>
        </receiver>
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        Intent serviceIntent = new Intent(getApplicationContext(), CallNotificationService.class);
                                        Bundle mBundle = new Bundle();
                                        mBundle.putString("inititator", name);
                                        mBundle.putString("call_type",callType);
                                        serviceIntent.putExtras(mBundle);
                                        ContextCompat.startForegroundService(getApplicationContext(), serviceIntent);
    }
    
    getApplicationContext().stopService(new Intent(AppController.getInstance().getContext(), HeadsUpNotificationService.class));
                                        Intent istop = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
                                        getApplicationContext().sendBroadcast(istop);
    
    {
        "data":{
            "property1":"value1",
            "property2":42
        }
    }
    // Please note it should have data node.