Android Service的初步解析

Service是一个应用程序组件代表应用程序执行一个长时间操作的行为,虽然不与用户交互或供应功能供其它应用程序使用。每个服务类必须有一个相应的包的AndroidManifest.xml中 声明。它用于处理一些不干扰用户使用的后台操作。如下载,网络获取。播放音乐,他可以通过INTENT来开启,同时也可以绑定到宿主对象(调用者例如ACTIVITY上)来使用。
Service可以通过startService和bindService两种方式来启动,其运行周期如图所示:


Android Service的初步解析_第1张图片
cycle.jpg

首先我们来看一下通过startService方式启动Service时,Service的生命周期。
MyService.java


public class MyService extends Service {

private static String TAG = "MyStartService";
private MyBinder myBinder = new MyBinder();

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
   // Log.d(TAG,"onStartCommand() execute");
    new Thread(new Runnable() {
        @Override
        public void run() {
            Log.d(TAG,"onStartCommand() execute");
        }
    }).start();
    return super.onStartCommand(intent, flags, startId);
}

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

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


添加启动和停止服务的代码

switch (view.getId()) {
case R.id.btn1:
Intent startIntent = new Intent(this,MyService.class);
startService(startIntent);
break;
case R.id.btn2:
Intent stopIntent = new Intent(this,MyService.class);
stopService(stopIntent);
break;
default:
break;
}

在布局文件中添加以下代码

android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="startService"/>
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stopService"/>

在Androidmanifest.xml中注册Service



运行程序后,点击startService按钮,在logcat中可以看到onCreate()和onStartCommand()先后被执行。


first.jpg

当Service启动后,再次点击startService按钮,只会执行onStartCommand()而不会执行onCreate()。只有Service第一次启动的时候才会执行onCreate()。当点击stopService时,Service会停止运行,执行onDestroy()。
下面我们再看一下通过bindService方式绑定Service的生命周期。首先我们添加绑定和解绑两个按钮,用于绑定和解绑Service。
在布局文件中添加按钮


android:id="@+id/btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bindService"/>
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="unbindService"/>

源码中添加绑定和解绑按钮的监听函数

case R.id.btn3:
Intent bindIntent = new Intent(this,MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);
break;
case R.id.btn4:
unbindService(connection);
break;

对MyService.java进行以下修改:

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

}
class MyBinder extends Binder{
        public void printLog(){
           // Log.d(TAG,"execute printLog()...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG,"execute printLog()...");
                }
            }).start();
        }
}


当点击绑定Service按钮时,Service会执行onCreate()和onBind(),其中onBind()调用printLog()。当点击解绑Service按钮,Service会解除绑定,执行onDestory()方法。


2222.jpg

当Service被startService和bindService同时启动时,单纯的stopService和unbindService都不能停止Service。只有stopService和unbindService按钮都被点击后才能结束Service。文章最后我会把Demo的源码分享给大家,有兴趣的小伙伴可以试一试。
最后还有一点需要提醒大家注意,Service和Activity一样都是运行在主线程中的,所以Service中不能运行耗时操作,否则会产生阻塞,报ANR错误。如果需要执行耗时操作,可以将耗时操作放到线程中去处理。
下面是demo的源代码:
MyService.java


package linuszhao.js.one.jsservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

/**

  • Created by linus on 2017/3/7.
    */
    public class MyService extends Service {

    private static String TAG = "MyStartService";
    private MyBinder myBinder = new MyBinder();

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    // Log.d(TAG,"onStartCommand() execute");
    new Thread(new Runnable() {
    @Override
    public void run() {
    Log.d(TAG,"onStartCommand() execute");
    }
    }).start();
    return super.onStartCommand(intent, flags, startId);
    }

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

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

    }
    class MyBinder extends Binder{
    public void printLog(){
    // Log.d(TAG,"execute printLog()...");
    new Thread(new Runnable() {
    @Override
    public void run() {
    Log.d(TAG,"execute printLog()...");
    }
    }).start();
    }
    }
    }


MainActivity.java

package linuszhao.js.one.jsservice;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

private Button btn1;
private Button btn2;
private Button btn3;
private Button btn4;
private MyService.MyBinder myBinder;
private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        myBinder = (MyService.MyBinder) iBinder;
        myBinder.printLog();
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn1 = (Button) findViewById(R.id.btn1);
    btn2 = (Button) findViewById(R.id.btn2);
    btn3 = (Button) findViewById(R.id.btn3);
    btn4 = (Button) findViewById(R.id.btn4);
    btn1.setOnClickListener(this);
    btn2.setOnClickListener(this);
    btn3.setOnClickListener(this);
    btn4.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId())  {
        case R.id.btn1:
            Intent startIntent = new Intent(this,MyService.class);
            startService(startIntent);
            break;
        case R.id.btn2:
            Intent stopIntent = new Intent(this,MyService.class);
            stopService(stopIntent);
            break;
        case R.id.btn3:
            Intent bindIntent = new Intent(this,MyService.class);
            bindService(bindIntent,connection,BIND_AUTO_CREATE);
            break;
        case R.id.btn4:
            unbindService(connection);
            break;
        default:
            break;
    }
}

}


Androidmanifest


package="linuszhao.js.one.jsservice">


    
        
            
            
        
    
    



activity_main.xml


xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="linuszhao.js.one.jsservice.MainActivity">

你可能感兴趣的:(Android Service的初步解析)