【问题标题】:PhoneStateListener is sometimes not responding in NougatPhoneStateListener 有时在 Nougat 中没有响应
【发布时间】:2016-12-05 09:32:27
【问题描述】:
我在onStartCommand 我的服务中注册了我的PhoneStateListener。它在以下 android N 设备中运行良好。但有时它在 android N 设备中没有响应。它与打盹模式有关吗?如果是,如何解决?
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
CustomPhoneStateListener phoneStateListener = new CustomPhoneStateListener();
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
【问题讨论】:
标签:
android
phone-state-listener
android-doze
【解决方案1】:
我在尝试在服务中运行 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);
}
希望这会有所帮助!
【解决方案2】:
我找到了解决方案:我的一个应用在 Noughat 中遇到了同样的问题。在调试时,我发现状态监听器只被调用一次,并且在创建活动时也是如此。一旦我进行任何调用,活动就会进入后台,并且在监听器从未被调用之后,因此我推断我在 onCreate 中附加的监听器在我离开活动时会分离,因此“在 onResume 中附加你的状态监听器”。您的问题将得到解决。
onResume() {
PhoneCallListener p = new PhoneCallListener;
TelephonyManager t = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
t.listen(p,PhoneStateListener.LISTEN_CALL_STATE);
}
【解决方案4】:
我遇到了这个问题,并在浪费了 2-3 天后解决了这个问题,允许应用程序从设置 -> 权限 -> 管理自动启动自动启动