美文网首页
Service知识

Service知识

作者: eagleif | 来源:发表于2018-08-10 11:00 被阅读12次
  1. Service的两种启动模式
  • startService()
Intent intent = new Intent(this, MyService.class);
startService(intent);
  • bindService
        Intent  intent = new Intent(this, MyService.class);
        startService(intent);
        ServiceConnection conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.d("TAG", "onServiceConnected");
                MyService.MyBinder myBinder = (MyService.MyBinder) iBinder;
                service = myBinder.getService();
                isBind = true;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.d("TAG", "onServiceDisconnected");
            }
        };
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
  1. 自定义Service
public class MyService extends Service {
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "MyService---->onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "MyService---->onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d("TAG", "MyService---->onBind");
        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("TAG","MyService---->onUnbind");
        return super.onUnbind(intent);
    }

    public class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TAG", "MyService---->onDestroy");
    }
}

既startService又bindService

从中可以看出onCreate只执行一次,onCreate不管startService或者bindService多少次都只执行一次onCreate()

  1. startService和bindService的区别
    startService没有和Activity绑定,Activity销毁了之后service还是能够运行;bindService启动时Service和Activity进行了绑定,如果Activity销毁了,那么Service会自动进行解绑和调用Service的onDestroy()方法
  2. IntentService
  • IntentService的定义
package com.example.ulabor.testproject;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.util.Log;

import java.util.concurrent.Executors;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * helper methods.
 */
public class MyIntentService extends IntentService {
    private static final String ACTION_FOO = "com.example.ulabor.testproject.action.FOO";
    private static final String ACTION_BAZ = "com.example.ulabor.testproject.action.BAZ";

    private static final String EXTRA_PARAM1 = "com.example.ulabor.testproject.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.example.ulabor.testproject.extra.PARAM2";

    public MyIntentService() {
        super("MyIntentService");
    }

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    public static void startActionFoo(Context context, String param1, String param2) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_FOO);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TAG", "onDestroy");
    }


    /**
     * Starts this service to perform action Baz with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    public static void startActionBaz(Context context, String param1, String param2) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_BAZ);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionFoo(param1, param2);
            } else if (ACTION_BAZ.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionBaz(param1, param2);
            }
        }
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        try {
            try {
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(1000);
                    Log.d("TAG", "i---》" + i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

最主要的就是onHandleIntent()方法对传入的参数进行处理;从中可以看出在handleActionFoo方法中,调用 Thread.sleep(1000);来进行耗时操作模拟,Service自己循环了10次之后自动销毁。能够在onHandleIntent()方法中进行耗时操作。因为Service的onCreate()和onStartCommand方法是在主线程运行的,所以不能够在这里进行耗时操作。IntentService是窜行操作,不是并行操作,也就是任务是一步一步完成的,如下图

执行如下代码:

        for (int j = 0; j < 2; j++) {
            MyIntentService.startActionFoo(this, "a", "b");
        }

运行结果

image.png

相关文章

  • Android Service用法知识点的讲解

    Android Service 学习Service相关知识点: android service 的基础知识,生命周...

  • Service知识

    Service的两种启动模式 startService() bindService 自定义Service 从中可以...

  • 关于Android的Service知识点,你知道吗?

    目录 学习Service相关知识点: 概述; Service生命周期; Service的基本用法; 服务。 问:达...

  • Service(七) - 远程Service

    1. 概述 前边几篇文章记录了Service的基础知识点:Service基本用法、Service与Acti...

  • Service相关知识

    先从生命周期说起吧: 首先他有三个生命周期,分别是:onCreate(),onStartCommand(),onD...

  • Service知识总结

    1. 概述 想必做过Android开发的同学应该都用过Service,然而有木有想过比较全面的掌握Service相...

  • Service知识汇总

    Service概述 由于手机屏幕的限制,通常情况下在同一时刻仅有一个应用程序处于激活状态,并能够显示在手机屏幕上,...

  • Service相关知识

    一. 简介 Service 是一个可以在后台执行长时间运行操作而不提供用户界面的应用组件。Service可由其他应...

  • Service相关知识

    1、Service简单概述 2、Service在清单文件中的声明 3、Service生命周期 4、Service启...

  • Android Binder IPC 概述

    背景知识Binder驱动Service ManagerBinder框架

网友评论

      本文标题:Service知识

      本文链接:https://www.haomeiwen.com/subject/yhkkbftx.html