我有这个问题也试图在服务中运行PhoneStateListener,它似乎只会'放'在N设备上。
我尝试了很多不同的建议,但我一直在运行7.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);
}
希望这有助于!
无法在Nougat中找到任何此类设置 – PPB