我在应用程序中使用服务来监听用户按下他/她的电源按钮的次数.实施在所有设备上都运行良好.但是当我在Android Kitkat上测试应用程序时,我注意到了一些错误.
只要我将应用程序从最近的应用程序中移开,应用程序就不再会监听电源按钮.
这是我正在使用的代码:
public class Receiver extends Service { Notification notification; private static final int NOTIFICATION_ID = 0; NotificationManager manager; PendingIntent toOpen; Intent intent; private BroadcastReceiver POWER_BUTTON = new Powerbuttonrecceiver(); @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(POWER_BUTTON, filter); startNotify(); return START_STICKY; } @Override public void onDestroy() { // TODO Auto-generated method stub unregisterReceiver(POWER_BUTTON); dismissNotification(); super.onDestroy(); } public void startNotify(){ manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.ic_launcher_drop; CharSequence tickerText = "Service activated"; CharSequence tickerContent = "Service is now on. You can press your power button and the app will listen to it. Tap to turn this feature off"; intent = new Intent(Receiver.this, Options.class); toOpen = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); notification = new NotificationCompat.Builder(getApplicationContext()) .setContentTitle(tickerText) .setContentText(tickerContent) .setSmallIcon(icon) .setOngoing(true) .setContentIntent(toOpen) .build(); manager.notify(NOTIFICATION_ID, notification); } public void dismissNotification(){ manager.cancel(NOTIFICATION_ID); } }
可以注意到我正在使用通知来表示该服务是活动的.令我困惑的是,从最近的应用程序轻扫后,通知仍然存在,什么是不活动的BroadcastReceiver
?或者是假的.
在应用程序中,onDestroy
我没有调用任何函数来注册或取消注册以及停止服务.再一次,这个问题只出现在Android KitKat中.如果你们知道发生了什么事,请.帮忙:)
更新:我也注意到Play Music
在Kitkat上,当我将它从最近的应用程序中移开时音乐停止.这是Kitkat的错误吗?但声音/媒体播放器服务SoundCloud
甚至可以在从最近的应用程序中删除时工作.
更新:在android问题跟踪器上 记录为问题63618.阅读问题评论了解更多详情.
似乎这是一个存在的错误Android 4.4
,使用以下方法解决它:
@Override public void onTaskRemoved(Intent rootIntent) { // TODO Auto-generated method stub Intent restartService = new Intent(getApplicationContext(), this.getClass()); restartService.setPackage(getPackageName()); PendingIntent restartServicePI = PendingIntent.getService( getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI); }
所以这是一个在Service
类本身中被重写的方法.我使用的原因AlarmManager
是Kitkat
不会杀死我的服务.