美文网首页
Android服务Service

Android服务Service

作者: 刘洋浪子 | 来源:发表于2017-02-24 19:10 被阅读85次

一、普通服务

1 . 定义服务

package com.ysy.mythreaddemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {
    public MyService () {
    }


    @Override
    public void onCreate () {
        super.onCreate ();
    }

    @Override
    public int onStartCommand (Intent intent, int flags, int startId) {
        return super.onStartCommand (intent, flags, startId);
    }

    @Override
    public IBinder onBind (Intent intent) {
        throw new UnsupportedOperationException ("Not yet implemented");
    }

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

}

2 . 启动和停止服务

  • 启动服务
            Intent service = new Intent (this,MyService.class);
            startService (service);
  • 停止服务
    stopService (service);

3 . 绑定和解绑服务、调用服务中的方法。

  • 绑定服务前的准备
    在服务中定义一个公共的继承Binder类,并实现一个自定义的接口(为了调用服务中的方法)的MyBinder类,在服务的onBind()方法中创建MyBinder对象并返回。
    public class MyBinder extends Binder implements IService{

        @Override
        public void startDownload () {
            Log.d ("ysy","start download!");
        }

        @Override
        public int getProgress () {
            Log.d ("ysy","get progress!");
            return 0;
        }
    }
    @Override
    public IBinder onBind (Intent intent) {
        return new MyBinder ();
    }

在活动中创建实现ServiceConnection接口的类,用于绑定服务。

 public class MyConnection implements ServiceConnection{

        @Override
        public void onServiceConnected (ComponentName name, IBinder service) {
            MyService.MyBinder mService = (MyService.MyBinder) service;
            mService.startDownload ();
            int progress = mService.getProgress ();
            Log.d ("ysy","progress "+progress);
        }

        @Override
        public void onServiceDisconnected (ComponentName name) {

        }
    }
  • 绑定服务
       conn = new MyConnection ();
       Intent service = new Intent (this,MyService.class);
       bindService (service,conn,BIND_AUTO_CREATE);
  • 解绑服务
    unbindService (conn);

  • 调用服务中的方法

        @Override
        public void onServiceConnected (ComponentName name, IBinder service) {
            MyService.MyBinder mService = (MyService.MyBinder) service;
            mService.startDownload ();
            int progress = mService.getProgress ();
            Log.d ("ysy","progress "+progress);
        }

4 . 服务的几个规则

  • 服务可以被多次启动,每次启动都会执行onStartCommand()方法
  • 服务可以多次绑定,但只会执行一次onBind()方法。
  • 服务只能解绑一次,解绑多次会出错
  • 服务的onCreate()方法只会在第一次启动或者第一次绑定时调用。
  • 服务的onDestory()方法只会在停止服务的时候,或者在未启动但绑定状态下,解绑时调用。

二、前台服务

  • 前台服务与普通服务的区别是,前台服务启动起来之后,会在系统的状态栏一直有个图标显示,下拉状态之后会看到更详细的信息。
  • 前台服务的定义与普通服务定义的不同是,前台服务会在普通服务的onCreate()方法中添加以下代码。
        Intent intent = new Intent (this,MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity (this,0,intent,0);
        Notification build = new NotificationCompat.Builder (this)
                .setContentTitle ("this is title")
                .setContentText ("this is content")
                .setSmallIcon (R.mipmap.ic_launcher)
                .setWhen (System.currentTimeMillis ())
                .setContentIntent (pi)
                .build ();
        startForeground (1,build);
  • 前台服务的启动与普通服务的启动相同。

三、在服务中做耗时操作

  • 服务是运行在主线程中的,android规定不能在主线程中做耗时操作。
  • 使用IntentService可以在服务中做耗时操作,定义如下:
package com.ysy.mythreaddemo;

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

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class MyIntentService extends IntentService {
    // TODO: Rename actions, choose action names that describe tasks that this
    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    private static final String ACTION_FOO = "com.ysy.mythreaddemo.action.FOO";
    private static final String ACTION_BAZ = "com.ysy.mythreaddemo.action.BAZ";

    // TODO: Rename parameters
    private static final String EXTRA_PARAM1 = "com.ysy.mythreaddemo.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.ysy.mythreaddemo.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
     */
    // TODO: Customize helper method
    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);
    }

    /**
     * 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
     */
    // TODO: Customize helper method
    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);
            }
        }
        Log.d ("ysy","Thread is "+Thread.currentThread ().getId ());
    }

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

    /**
     * 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");
    }

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


}

  • 可以将耗时操作放在MyIntentService的onHandleIntent ()方法中,这个方法中的代码是运行在子线程中。

相关文章

  • Android服务的启动模式

    Android 服务两种启动方式的区别 关键字:Android Service服务的启动和停止方式 Service...

  • Android 学习之Service

    什么是Service? Service,俗名服务。在Android系统中,Service与Activity就...

  • Android Service

    Android Service(服务) 服务的定义服务是Android中实现后台运行的解决方案。 android多...

  • IntentService学习-Service/Handler相

    前言 Service服务是Android四大组件之一,在Android中有着举足重轻的作用。Service服务是工...

  • Android Service学习笔记

    参考:Android Service完全解析,关于服务你所需知道的一切(上)Android Service完全解析...

  • Android Start Service与Bind Servi

    1.什么是Service Service是Android四大组件之一,是系统服务。Service是运行在后台的服务...

  • Service(服务)

    Service为Android四大组件之一 目录 什么是Service? 服务的基本用法 Android-8.0的...

  • Service 使用方法详解

    Service 是Android四大组件之一(Activity 活动,Service 服务,ContentProv...

  • service

    服务是什么 “Service” 意思即“服务”的意思, Service是Android中实现程序后台运行的解决方案...

  • Service和线程的区别

    服务(Service) Service是android的一种机制,当它运行的时候如果是Local Service,...

网友评论

      本文标题:Android服务Service

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