当前位置: 首页 > 知识库问答 >
问题:

当我们在另一个应用程序中时,Android 10来电通知,例如Whats应用程序

穆鸿波
2023-03-14

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

int NOTIFICATIONID = 1234;
       // Uri sound =  RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.capv_callingtone);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();
            String CHANNEL_ID = BuildConfig.APPLICATION_ID.concat("_notification_id");
            String CHANNEL_NAME = BuildConfig.APPLICATION_ID.concat("_notification_name");
            assert notificationManager != null;

            NotificationChannel mChannel = notificationManager.getNotificationChannel(CHANNEL_ID);
            if (mChannel == null) {
                mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                mChannel.setSound(sound, audioAttributes);
                notificationManager.createNotificationChannel(mChannel);
            }
            in.setClass(CapVFirebaseMessagingService.this, DashBoardActivity.class);
            in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            in.putExtra(NOTIFICATION_ID, NOTIFICATIONID);
            Intent buttonIntent = new Intent(getBaseContext(), NotificationReceiver.class);
            buttonIntent.putExtra(NOTIFICATION_ID, NOTIFICATIONID);
            buttonIntent.putExtra(CapV.MESSAGE_TYPE,in.getSerializableExtra(CapV.MESSAGE_TYPE));
            Log.d("Audiotask",""+in.getSerializableExtra(CapV.MESSAGE_TYPE));
            PendingIntent dismissIntent = PendingIntent.getBroadcast(getBaseContext(), 0, buttonIntent, 0);
            SharedPreferences localPrefs = getSharedPreferences(LOCAL_PREFERENCES,MODE_PRIVATE);
            SharedPreferences.Editor editor = getSharedPreferences(LOCAL_PREFERENCES, MODE_PRIVATE).edit();
            editor.putBoolean("Fragment_created",true).commit();
            editor.putBoolean("Incoming_call",true).commit();
            // The PendingIntent to launch activity.
            PendingIntent activityPendingIntent = PendingIntent.getActivity(this, 0,
                    in, 0);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);

            builder.setSmallIcon(R.drawable.logo)
                    .setContentTitle(("Incoming Call"))
                    .setContentText("Group")
                    .setDefaults(0)
                    .addAction(R.drawable.answer, getString(R.string.answer),
                            activityPendingIntent)
                    .addAction(R.drawable.reject, getString(R.string.reject),
                            dismissIntent)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setCategory(NotificationCompat.CATEGORY_CALL)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setSound(sound)
                    .setOngoing(true);
            android.app.Notification notification = builder.build();
            notificationManager.notify(1234, notification);

任何帮助都将不胜感激。

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

startForeground(1234,getNotification(IncomingCallContent));

private android.app.Notification getNotification(Intent in) {



    in.putExtra(EXTRA_STARTED_FROM_NOTIFICATION, true);

   PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,in, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"")
            .setSmallIcon(R.drawable.logo)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setFullScreenIntent(pendingIntent, true);

    // Set the Channel ID for Android O.
        //builder.setChannelId("115"); // Channel ID

   return builder.build();


}

共有2个答案

夹谷晋
2023-03-14

这可以通过FCM的数据消息实现。您需要设置以下内容:

  1. 创建扩展FirebaseMessagingService的服务。请参阅FCM文件。我们必须重写服务类中的onMessageReceived()
  2. 创建全屏意图或显示时间敏感通知。请参阅FCM文件。在我们的服务中的overridedonMessageReceived()中显示此通知
  3. 现在,您必须找到从FCM发送数据消息的方法。Firebase控制台不支持此功能。后端必须为此创建一个设置。请参阅此处

让我深入了解更多细节。

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

  1. 通知消息:这是常见的消息类型。这可以从FCM控制台中的通知编辑器发送。这种类型的消息将具有名为title、body等的属性。如果我们发送通知消息,只有当应用程序处于前台时,才会调用onMessageRecect()
  2. 数据消息:这不能从FCM控制台中的通知编辑器发送。这种类型的消息应该有属性数据(有效负载)。这将从服务器发送,格式如下:
{
    "data":{
        "property1":"value1",
        "property2":42
    }
}
// Please note it should have data node.

若我们发送数据消息,即使应用程序在后台或不在内存中,也会调用onMessageReceived()。这就是我们想要的<请参阅FCM文档中的数据消息,让我重温步骤1:这是我们必须创建的唯一服务。我们不需要创建任何其他前台服务。这是另一种情况。重写onMessageReceived()以执行步骤2步骤#2:全屏意图或显示时间敏感通知将显示问题中所示的抬头显示通知或显示来电的整个活动。当我们收到步骤#3中提到的数据消息时,在onMessageReceived()中显示此通知步骤#3:联系服务器发送我上面所示的有效负载JSON。

就是这样!

祁嘉木
2023-03-14

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

呼叫通知服务

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>

要启动该服务,您需要从firebase通知服务调用它。

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);
 类似资料:
  • 我正在处理使用通知侦听器服务类从通知中读取数据的应用程序。我已完成文本部分,但无法存储通知中收到的图像。 我想存储在WhatsApp应用程序中从通知中收到的图像。我已经尝试了堆栈溢出的所有解决方案,但没有得到任何解决方案。我已经尝试了<代码>通知。EXTRA_PICTURE但它总是返回null。 我见过许多应用程序这样做,但看起来我错过了一些东西。 因此,如果有人能以任何方式提供帮助,我们将不胜感

  • 问题内容: 我确信你们中有人注意到,如果您有Acrobat Reader(或其他PDF阅读器),并在Firefox中打开一个PDF,您会看到它嵌入在您的标签中。有什么方法可以将应用程序嵌入JFrame中? 问题答案: 这是一个相当棘手的问题。通常,诸如Adobe Reader之类的本机应用程序不提供可以嵌入到swing应用程序中的组件。但是在Windows中,有COM / OLE方法可以将应用程序

  • 当应用程序完全关闭时,如何以编程方式发送通知? 示例:用户关闭应用程序,也在Android Taskmanager中,然后等待。应用程序应在X秒后或应用程序检查更新时发送通知。 我试图使用这些代码示例,但是: 应用程序关闭时推送通知-活动太多/无法工作 我如何让我的应用程序在关闭时发送通知很多信息,但我不知道如何处理 当android应用程序关闭时,如何发送本地通知?-很多信息,但我不知道如何处理

  • 如果应用程序未运行,GCMinentService(扩展GCMBasEventService)不会收到通知。 来自:http://developer.android.com/about/versions/android-3.1.html 已停止应用程序上的启动控制请注意,系统会将标志\u排除\u已停止\u包添加到所有广播意图中。它这样做是为了防止来自后台服务的广播无意或不必要地启动已停止应用程序的

  • 当我打开我的android应用程序并测试解析推送通知时,它工作了。但是当我把我的应用程序从多任务中杀死并再次测试时,应用程序崩溃了。 错误日志 08-18 21:16:21.694 244 06-24406/?E/AndroidRuntime:致命异常:main process:com.myatminsoe.mKeyboard,PID:24406 java.lang.runtimeExceptio