2016-12-05 115 views
1

我正在注册我的PhoneStateListener我的服务onStartCommand。它在Android N设备下完美工作。但有时它在android N设备中没有响应。它与睡眠模式有关吗?如果是的话如何解决它?PhoneStateListener有时没有响应牛轧糖

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

回答

0

我有这个问题也试图在服务中运行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); 


} 

希望这有助于!

0

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

onResume() { 
    PhoneCallListener p = new PhoneCallListener; 
    TelephonyManager t = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); 
    t.listen(p,PhoneStateListener.LISTEN_CALL_STATE); 
} 
0

需要我有这个问题,浪费了2-3天,可让应用程序自动启动后解决它,当代码禁用从设置 - >权限 - >管理自动启动

+0

无法在Nougat中找到任何此类设置 – PPB

相关问题