我在应用程序中使用服务来侦听用户按下电源按钮的次数。实施在所有设备上都工作正常。但是当我在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 17:22:06
我有这个完美的解决方案,你可以参考下:
@Override
public void onDestroy() {
startService(new Intent(yourcontext, YourService.class));
}
https://stackoverflow.com/questions/-100007692
复制相似问题