Android中Service服务详解(二)

2019-12-10 19:18:58王冬梅
易采站长站为您分析Android中Service服务,在前面一篇的基础上进一步分析了Android Service的绑定服务与解绑服务的相关使用技巧,需要的朋友可以参考下  

本文详细分析了Android中Service服务。,具体如下:

在前面文章《Android中Service服务详解(一)》中,我们介绍了服务的启动和停止,是调用Context的startService和stopService方法。还有另外一种启动方式和停止方式,即绑定服务和解绑服务,这种方式使服务与启动服务的活动之间的关系更为紧密,可以在活动中告诉服务去做什么事情。

为了说明这种情况,做如下工作:

1、修改Service服务类MyService

package com.example.testservice;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
  //创建自己的绑定服务业务逻辑
  class MusicBinder extends Binder{
    public void ready(){
      Log.d("MyService", "----ready Method---");
    }
    public void play(){
      Log.d("MyService", "----play Method---");
    }
  }
  private MusicBinder musicBinder = new MusicBinder();
  @Override
  public IBinder onBind(Intent arg0) {
    Toast.makeText(this, "服务的onBind方法被调用", Toast.LENGTH_SHORT).show();
    return musicBinder;
  }
  /**
   * 服务第一次创建的时候调用
   */
  @Override
  public void onCreate() {
    super.onCreate();
    Toast.makeText(this, "服务的onCreate方法被调用", Toast.LENGTH_SHORT).show();
  }
  /**
   * 服务每一次启动的时候调用
   */
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "服务的onStartCommand方法被调用", Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent, flags, startId);
  }
  @Override
  public void onDestroy() {
    Toast.makeText(this, "服务的onDestroy方法被调用", Toast.LENGTH_SHORT).show();
    super.onDestroy();
  }
}

在服务类中,添加了内部类MusicBinder,在该内部类中,我们模拟了两个方法。同时在onBind方法中返回我们内部类实例。

2、修改布局文件activity_main.xml

<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >
  <Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="启动服务" />
  <Button
    android:id="@+id/button2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="停止服务" />
  <Button
    android:id="@+id/button3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="绑定服务" />
  <Button
    android:id="@+id/button4"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="解绑服务" />
</LinearLayout>