首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android服务:START_STICKY不适用于Kitkat吗?

Android服务:START_STICKY不适用于Kitkat吗?
EN

Stack Overflow用户
提问于 2018-03-20 08:03:19
回答 2查看 0关注 0票数 0

我在应用程序中使用服务来侦听用户按下电源按钮的次数。实施在所有设备上都工作正常。但是当我在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);
    }

}
EN

Stack Overflow用户

发布于 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);

}
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100007692

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档