安卓使用START_STICKY启动前台服务

3
我无法理解有关Android服务的新特性。在Google文档中,自oreo以后,当应用程序处于后台时,开发人员必须使用前台服务来启动服务。
我找到了以下描述:“从Android O开始,如果您的应用程序处于后台(请检查上述三个条件),您的应用程序被允许创建和运行一些分钟的后台服务。过了几分钟,您的应用程序将进入空闲阶段。当您的应用程序进入空闲阶段时,系统将停止所有后台服务,就像您的服务调用Service.stopSelf()一样。”
我无法理解即使我使用START_STICKY启动服务,它是否不会重新启动?我知道如果我使用START_STICKY启动服务,它将在关闭后恰好重新启动。为什么我需要为某些需求(例如位置更新)使用JobScheduler?有人能解释一下吗?我无法很好地理解谷歌文档。
我现在在galaxy note 8 api26手机上进行测试。我在应用程序启动时使用startService启动服务,并在关闭应用程序后重新启动。旧版本之间有什么区别?
谢谢。

主要原因是电池寿命。在旧版的Android中,开发者利用这个问题让他们的应用程序在设备上不停地运行而且永远不会被杀死,从而耗尽设备的电池寿命。需要启动前台服务的原因是让用户知道您的应用正在运行,并且可以随时终止它。 - Pierre
我知道了,但如果我从活动中使用startservice会发生什么?我发现在应用程序关闭后它会再次启动。我无法看到任何编程问题。 - ahmetvefa53
我已经在应用程序启动时通过startservice启动了服务,但什么也没有发生。如果我从后台启动它,是会抛出错误的。 - ahmetvefa53
我添加了它,但我还没有开始前台。 - ahmetvefa53
我没有看到你在启动服务时添加一个Action,但是你在StartCommand中调用了intent.getAction()。尝试添加一个Action serviceIntent.setAction("some.action"); - Pierre
显示剩余4条评论
1个回答

0
    public class MyActivity2 extends Activity {

    private Intent serviceIntent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        serviceIntent = new Intent(this, MyService.class);
        serviceIntent.putExtra("name", "ahmet vefa saruhan");
        startService(serviceIntent);
        findViewById(R.id.textview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(new Intent(getApplicationContext(),MyService.class));
            }
        });
    }
}

    public class MyService extends Service {

    private String myaction;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("MYSERVICE STATUS: "," ONSTARTCOMMAND action : " + ((intent != null && intent.getStringExtra("name") != null) ? intent.getStringExtra("name") : "yok") + " OLD ACTION : "+(myaction != null ? myaction : "yok"));
        Log.d("MYTHREAD name : ",Thread.currentThread().getName());
        //intent.putExtra("name","isim değişti");
        myaction = (intent != null) ? intent.getAction() : null;
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
       Log.d("MYSERVICE STATUS: "," ONCREATED");
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startMyOwnForeground()
    {
        String NOTIFICATION_CHANNEL_ID = "example.permanence";
        String channelName = "Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }

    @Override
    public void onDestroy() {
        Log.d("MYSERVICE STATUS: "," ONDESTROYED");
        super.onDestroy();
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.d("MYSERVICE STATUS: "," onTaskRemoved");
        super.onTaskRemoved(rootIntent);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接