永远不会结束marshmallow android的后台服务

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了永远不会结束marshmallow android的后台服务相关的知识,希望对你有一定的参考价值。

我一直致力于我需要不断运行后台服务的项目。

我的代码在android O和Lollipop设备上运行良好。

但我遇到了Marshmallow设备的问题。当用户杀死应用程序时,我的服务已停止。

我读过和Optimize for Doze and App Standby

main activity.Java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pingService = new PingService(this);
        mServiceIntent = new Intent(this, PingService.class);
        if (!isMyServiceRunning(PingService.class)) {
            startService(mServiceIntent);
        }

    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                Log.i ("isMyServiceRunning?", true+"");
                return true;
            }
        }
        Log.i ("isMyServiceRunning?", false+"");
        return false;
    }

    @Override
    protected void onDestroy() {
        stopService(mServiceIntent);
        Log.i("MAINACT", "onDestroy!");
        super.onDestroy();
    }

ping service.Java

@Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O )
            startMyOwnForeground();
        else if(Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
            Log.i("onCreate","Innn");
            startMyOwnForeground();
        }else{
            Log.i("onCreate","in start Forground");
            startForeground(1, new Notification());
        }

    }


    private void startMyOwnForeground(){
        String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
        String channelName = "My Background Service";
        NotificationChannel chan = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            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)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setContentTitle("App is running in background")
                    .setPriority(NotificationManager.IMPORTANCE_MIN)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .build();
            startForeground(2, notification);
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        Log.i("onStartCommand","in onStartCommand");
        startTimer();
        return START_STICKY;
    }

    public PingService(Context context) {
        this.context = context;
    }

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


    public void startTimer() {
        Log.i("startTimer","startTimer");
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, to wake up every 1 second
        timer.schedule(timerTask, 1000, 1000); //
    }

    /**
     * it sets the timer to print the counter every x seconds
     */
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                Log.i("in timer", "in timer ++++  "+ (counter++));
            }
        };
    }

    /**
     * not needed
     */
    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("EXIT", "ondestroy!");
        Intent broadcastIntent = new Intent(this, RestarterBroadcast.class);
        sendBroadcast(broadcastIntent);
        stoptimertask();

    }

restart而B rod cast.Java

@Override
    public void onReceive(Context context, Intent intent) {
        Log.i(RestarterBroadcast.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context, PingService.class));
        } else {
            Log.i(RestarterBroadcast.class.getSimpleName(), "In");
            context.startService(new Intent(context, PingService.class));
        }
//        context.startService(new Intent(context, PingService.class));
    }

任何人都可以指导我在Marshmallow的永无止境的服务的最佳体验和解决方案吗?

我还想从我的应用程序中为用户提供最佳体验

帮助将不胜感激

谢谢

答案

服务将重新启动或仅在未明确停止的情况下继续工作。在你的情况下 - 你正在阻止它

@Override protected void onDestroy() { stopService(mServiceIntent); Log.i("MAINACT", "onDestroy!"); super.onDestroy(); }

只需从活动中删除onDestroy()方法即可。

以上是关于永远不会结束marshmallow android的后台服务的主要内容,如果未能解决你的问题,请参考以下文章

javax.mail无法在Marshmallow或更高版本的系统上运行

我的应用不会显示在 android.intent.action.VIEW 的选择器对话框中,只有在 Marshmallow 上具有 mime 类型 video/*

Android 6.0 (MarshMallow) 上的 HttpURLConnnection 请求失败

何时在运行时请求 Android Marshmallow 6.0 的权限?

构建永远不会结束

等待本地主机...永远不会结束