我在应用程序中使用服务来侦听用户按下电源按钮的次数。实施在所有设备上都工作正常。但是当我在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);
}
}
发布于 2018-03-20 16:24:35
似乎这是一个存在的错误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);
}
https://stackoverflow.com/questions/-100007692
复制相似问题