之前做的APP有语音通话功能,近来发现9.0之后休眠会导致通话中断。查阅资料后,发现安卓9.0为了保护用户的隐私,在程序至入后台或者休眠之后会禁止用户访问麦克风、摄像头等功能,这就导致了通话在休眠或至入后台的短时间后就断掉了。找了很多,试过wakeLock,以及悬浮框来解决问题。但是悬浮框只能解决至入后台不会中断,休眠锁屏依然会有问题,给出的一版解决方案不断点亮屏幕也感觉非常不合理。最后还是研究微信以及QQ的通话,查阅API找到的解决思路——Notification
好了,不废话了直接上图
下面贴上我的代码
public class NotificationService extends Service { private static final String TAG = "NotificationService"; private NotificationManager notificationManager; //通知的唯一标识号。 private int NOTIFICATION = R.string.notification_live_start; @Override public void onCreate() { super.onCreate(); notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); showNotification(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } private void showNotification(){ // PendingIntent如果用户选择此通知,则启动我们的活动 PendingIntent pendingIntent = PendingIntent.getActivity(this,0,new Intent(this,NotificationService.class),0); //设置通知面板中显示的视图的信息。 Notification notification =new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher).setTicker("正在通话") .setContentTitle(getText(R.string.notification_live_start)) .setContentTitle("正在运行") .setContentIntent(pendingIntent) .build(); LogUtil.i(TAG,"显示通知"); //发送通知 notificationManager.notify(NOTIFICATION,notification); startForeground(R.string.notification_live_start,notification); } @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onDestroy() { super.onDestroy(); notificationManager.cancel(NOTIFICATION); } }
测试可以解决休眠及息屏通话中断的问题。