Android Service的初步解析

2017-03-08  本文已影响0人  弱小口

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


cycle.jpg

首先我们来看一下通过startService方式启动Service时,Service的生命周期。
MyService.java
<pre>
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;
  }
}

</pre>
添加启动和停止服务的代码
<pre>
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;
}
</pre>
在布局文件中添加以下代码
<pre>
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="startService"/>
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stopService"/>
</pre>
在Androidmanifest.xml中注册Service
<pre>
<service android:name=".MyService"/>
</pre>
运行程序后,点击startService按钮,在logcat中可以看到onCreate()和onStartCommand()先后被执行。


first.jpg

当Service启动后,再次点击startService按钮,只会执行onStartCommand()而不会执行onCreate()。只有Service第一次启动的时候才会执行onCreate()。当点击stopService时,Service会停止运行,执行onDestroy()。
下面我们再看一下通过bindService方式绑定Service的生命周期。首先我们添加绑定和解绑两个按钮,用于绑定和解绑Service。
在布局文件中添加按钮
<pre>
<Button
android:id="@+id/btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bindService"/>
<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="unbindService"/>
</pre>
源码中添加绑定和解绑按钮的监听函数
<pre>
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;
</pre>
对MyService.java进行以下修改:
<pre>
@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();
        }
}

</pre>
当点击绑定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
<pre>
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;

/**

</pre>
MainActivity.java
<pre>
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;
    }
}

}
</pre>
Androidmanifest
<pre>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="linuszhao.js.one.jsservice">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".MyService"/>
</application>

</manifest>
</pre>
activity_main.xml
<pre>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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">

<Button
    android:id="@+id/btn1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="startService"/>
<Button
    android:id="@+id/btn2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="stopService"/>
<Button
    android:id="@+id/btn3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="bindService"/>
<Button
    android:id="@+id/btn4"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="unbindService"/>

</LinearLayout>

</pre>

上一篇下一篇

猜你喜欢

热点阅读