码迷,mamicode.com
首页 > 移动开发 > 详细

Android-startService后台运行

时间:2018-12-07 14:51:13      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:view   nts   ret   操作   rac   oid   开启   and   xtend   

什么时候使用startService?

答:APP在后台长时间运行并执行业务的时候,可以用服务,主要是看服务的特点(在后台长时间运行);

 

Service相关代码:

package liudeli.service1.service;

import android.app.Service;

import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService4 extends Service {

    private final static String TAG = MyService4.class.getSimpleName();

    private final static int RUN = 1;
    private final static int NOT_RUN = 0;

    private int runState;

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

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        runState = RUN;
        new Thread(new BackgroundRun()).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        runState = NOT_RUN;
    }

    /**
     * startService 不能直接执行耗时操作,需要通过异步去执行耗时操作,Service只负责长时间到在后台服务运行
     * Service是开启主线程的,Service与Activity很类似,都是开启运行主线程的
     */
    class BackgroundRun implements Runnable {

        @Override
        public void run() {
            while (runState == RUN) {
                Log.d(TAG, "Background Run ......");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

MainActivity4相关代码:

    public void startService(View view) {
        startService(new Intent(this, MyService4.class));
    }

    public void stopService(View view) {
        stopService(new Intent(this, MyService4.class));
    }

 

Log日志,Service去启动线程一秒执行一次:

12-06 22:54:07.489 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:08.490 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:09.495 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:10.500 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:11.507 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:12.508 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:13.509 8204-8301/liudeli.service1 D/MyService4: Background Run ......

Android-startService后台运行

标签:view   nts   ret   操作   rac   oid   开启   and   xtend   

原文地址:https://www.cnblogs.com/android-deli/p/10082321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!