我也遇到了这个问题,试图在服务中运行 PhoneStateListener,而且它似乎只会在 N 台设备上“丢弃”。
我尝试了很多不同的建议,但我在运行 7.0.0 的 nexus5x 上不断失去听众。我能够让它在 100% 的时间内保持活跃的方法是让服务运行前台通知。基本上,只要服务处于活动状态,它就会在通知托盘中保持活动状态。这使我的服务在不同的电话状态下保持活力,在这些状态下它会在之前挂断听众,例如当一个拨出电话被接听时。只要您不对通知生成器设置声音或振动,它就几乎不会引起注意。我的 onCreate 服务如下所示:
MyPhoneListener phoneStateListener = new MyPhoneListener(getApplicationContext());
TelephonyManager telephonymanager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
telephonymanager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
Intent notificationIntent = new Intent(this, YourActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_favorites) //status bar icon
.setContentTitle("Title") //whatever title
.setContentText("Stuff") //main notification text
.setContentIntent(pendingIntent).build();
startForeground(12345, notification);
然后在服务的 onDestroy 中删除通知:
@Override
public void onDestroy() {
Log.i("log", "service ending");
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.cancel(12345);
}
希望这可以帮助!