Anroid四大组件service之本地服务

         服务是Android四大组件之一,与Activity一样,代表可执行程序。但Service不像Activity有可操作的用户界面,它是一直在后台运行。用通俗易懂点的话来说:

如果某个应用要在运行时向用户呈现可操作的信息就应该选择Activity,如果不是就选择Service。

Service的生命周期如下:

Service只会被创建一次,也只会被销毁一次。那么,如何创建本地服务呢?

 

 

实现代码如下:

package temp.com.androidserivce;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by Administrator on 2017/8/18.
 */

public class Myservice extends Service {
    @Override
    public void onCreate() {
        Log.i("test", "服务被创建");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i("test", "服务被启动");
        new Thread(new myRunnable(startId)).start();
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {
        Log.i("test", "服务被销毁");
        super.onDestroy();
    }

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

    class myRunnable implements Runnable {
        int startId;

        public myRunnable(int startId) {
            this.startId = startId;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                SystemClock.sleep(1000);
                Log.i("test", i + "");
             }
            //停止服务
            //stopSelf();
            stopSelf(startId);
            //当用无参数的停止服务时,将会销毁第一次所启动的服务;
            //当用带参数的停止服务时,将会销毁最末次所启动的服务;

        }
    }
}

要声明服务,就必须在manifests中进行配置

<manifest ... >
  ...
  <application ... >
      <service android:name=".Myservice" android:exported="true"/>

...

</application>

</manifest>
android:exported="true" 设置了这个属性就表示别人也可以使用你的服务。
还有一个需要注意的小点,在Myservice中可以看见我启动时用了一个子线程去帮我实现工作,那么我为什么没有直接把for循环的那段代码写在onStartCommand方法中呢,
是因为写在onStartCommand
中将会报ANR程序无响应的错误。就是当你所有的事情都去交给主线程做时,就会造成主线程内存溢出,它就会炸了。这个时候也可以用IntentService来取代Service。
package temp.com.androidserivce;

import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

/**
 * Created by Administrator on 2017/8/18.
 */

public class MyService2 extends IntentService {
    public MyService2() {
        super("");
    }
    public MyService2(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        for (int i = 0; i <10 ; i++) {
            SystemClock.sleep(1000);
            Log.i("test",i+"");
        }
    }
}

使用这个相对而言会比较简单。IntentService是Service的子类。它使用工作线程逐一处理所有启动请求。




 

posted @ 2017-10-21 22:48  彭艳  阅读(427)  评论(0编辑  收藏  举报