1

我正在注册我PhoneStateListeneronStartCommand服务。它在以下 android N 设备中运行良好。但有时它在 android N 设备中没有响应。它与打盹模式有关吗?如果是,如何解决?

    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    CustomPhoneStateListener phoneStateListener = new CustomPhoneStateListener();
    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
4

4 回答 4

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); 


}

希望这可以帮助!

于 2016-12-06T00:14:02.203 回答
0

或者在清单中注册您的接收器,并在需要时通过PackageManager https://stackoverflow.com/a/6529365/671580在代码中启用/禁用它

于 2017-02-22T08:21:04.133 回答
0

我找到了解决方案:我的一个应用在 Noughat 中遇到了同样的问题。在调试时,我发现状态监听器只被调用一次,并且在创建活动时也是如此。一旦我进行任何调用,活动就会进入后台,并且在监听器从未被调用之后,因此我推断我在 onCreate 中附加的监听器在我离开活动时被分离,因此“在 onResume 中附加你的状态监听器”。你的问题将得到解决。

onResume() {
    PhoneCallListener p = new PhoneCallListener;
    TelephonyManager t = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
    t.listen(p,PhoneStateListener.LISTEN_CALL_STATE);
}
于 2017-02-22T07:36:16.647 回答
0

我遇到了这个问题,并在浪费了 2-3 天后解决了这个问题,允许应用程序从设置 -> 权限 -> 管理自动启动自动启动

于 2017-10-25T15:41:34.703 回答