四大组件之一Service

Service

为什么要学习Service

我们在做一些项目时需要让它在后台执行(如:下载,音乐播放)这个时候我们就需要Service。

什么是Service

1.Service是Android四大组件之一,和Activity的级别相当。
2.Service是可以长时运行在后台的, 是不可见,是没有界面的组件。
3.Service是运行在主线程中的。
4.Service可以跨进程调用。

如何使用Service

使用startService方式启动Service步骤
1.新建类继承Service。
2.重写onCreate方法。
(Service在创建时调用的方法,可以用来做数据初始化,Service在没有停止之前,只会执行一次。)
3.实现onBind抽象方法。
(由于Service是一个抽象类,定义了一个onBind抽象方法,return null即可,此方法在startService方式用不上,无需理会即可。)
4.重写onStartCommand方法。
(Service创建后会调用onStartCommand,此方法中可以接收调用者传递过来的参数,并且可以编写需要的逻辑代码,当重复调用Service时,onStartCommand会重复执行,onStart方法弃用)。
5.重写onDestroy方法。
(Service在退出时调用,此方法中可以编写释放资源的操作。)
6.在AndroidManifest中注册Service。
(使用< Service >标签注册,同Activity注册。)
7.在有Context环境中通过startService启动Service。
8.在有Context环境中通过stopService停止Service。

startService启动Service以及Service中耗时操作演示

1.onCreate只会执行一次,只要调用startService,onStartCommand定会执行。
2.Service运行在main线程中,做耗时操作需另开子线程。
3.通过Intent进行传参,在onStartCommand中接收参数。
4.无法获得Service对象,不能直接操作Service中的属性和方法。
5.调用stopService后,Service会执行onDestroy方法后停止。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.pc.service">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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之前需要注册一下
        <service android:name="MyService" >
        </service>
    </application>

</manifest>
package com.example.pc.service;

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

/**
 * Created by pc on 2018/3/21.
 */

public class MyService extends Service {

    public static final String TAG = "MyService";

    @Override
    public void onCreate() {
        super.onCreate();
        //Thread.currentThread().getName()显示子线程的名字
        Log.e("Service"+Thread.currentThread().getName(), "onCreate() executed");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Service", "onStartCommand() executed");
        //Service进行耗时操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<=20;i++){
                    Log.e("Service"+Thread.currentThread().getName(),i+"***");
                    try {
                        Thread.sleep(1000);
//                        stopSelf();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("Service"+Thread.currentThread().getName(), "onDestroy() executed");
    }

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

}
package com.example.pc.service;

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

public class MainActivity extends Activity implements View.OnClickListener {

    private Button startService;
    private Button stopService;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //赋ID,监听事件
        setContentView(R.layout.activity_main);
        startService = findViewById(R.id.start_service);
        stopService = findViewById(R.id.stop_service);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //启动Service
            case R.id.start_service:
                intent = new Intent(this, MyService.class);
                startService(intent);
                break;
            //关闭
            case R.id.stop_service:
                stopService(intent);
                break;
            default:
                break;
        }
    }

}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/start_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Service" />

    <Button
        android:id="@+id/stop_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Service" />

</LinearLayout>
bindService操作演示

1.新建类继承Service。
2.实现onBind抽象方法。
3.重写onCreate方法。
4.重写onUnbind方法。
5.重写onDestroy方法。
6.在AndroidManifest中注册Service。
7.在有Context环境中实现ServiceConnection接口。
8.在有Context环境中通过bindService绑定Service。
9.在有Context环境中通过unbindService绑定Service。

package com.example.pc.service;

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 ZhangsanActivity extends AppCompatActivity implements View.OnClickListener {

    private Button bindBtn;
    private Button unBindBtn;
    private Button lisiBtn;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //通过管家的中介作用,拿到TestService对象
            TestService testService = ((TestService.Guanjia) service).getServiceObject();
            testService.fly();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        bindID();
    }

    private void bindID() {
        bindBtn = findViewById(R.id.btn1);
        unBindBtn = findViewById(R.id.btn2);
        lisiBtn = findViewById(R.id.btn3);
        unBindBtn.setOnClickListener(this);
        bindBtn.setOnClickListener(this);
        lisiBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn1:
//                Intent intent = new Intent(this,TestService.class);
//                bindService(intent,serviceConnection,BIND_AUTO_CREATE);
                Intent intent = new Intent(this,MyIntentService.class);
                startService(intent);
                break;
            case R.id.btn2:
                unbindService(serviceConnection);
                break;
            case R.id.btn3:
                Intent intent1 = new Intent(this,LisiActivity.class);
                startActivity(intent1);
                break;
        }
    }
}
package com.example.pc.service;

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

/**
 * Created by pc on 2018/3/23.
 */

public class TestService extends Service {

    private String TAG = "TestService";

    private Guanjia guanjia = new Guanjia();

    class Guanjia extends Binder{
        //作用:得到当前Service的对象
        public TestService getServiceObject(){
            return TestService.this;
        }
    }

    public void fly(){
        Log.e(TAG,"开飞机");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG,"onBind...");
        return guanjia;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG,"onUnbind");
        return super.onUnbind(intent);
    }

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BinderService绑定"/>

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BinderService解绑"/>

    <Button
        android:id="@+id/btn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转到lisi"/>

</LinearLayout>
IntentService操作演示

1.新建类继承IntentService
2.实现父类的构造方法
3.重写onHandleIntent方法
4.重写Oncreat方法
5.重写onDestory方法
6.在AndroidManifest中注册Service
7.在有Context环境中实现ServiceConnection接口
8.在有Context环境中通过startService绑定Service
9.在有Context环境中通过stopService解绑Service

package com.example.pc.service;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.InputStream;

/**
 * Created by pc on 2018/3/23.
 */

public class MyIntentService extends IntentService {
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public MyIntentService(String name) {
        super(name);
    }
    public MyIntentService(){
        super("");

    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        for (int i=0;i<10;i++){
            try {
                Log.e("MyIntentService",i+"***");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.pc.service.LisiActivity">
<Button
    android:id="@+id/lisi_bind_btn"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:text="绑定Service"/>
    <Button
        android:id="@+id/lisi_unbind_btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="解绑Service"/>
</LinearLayout>
package com.example.pc.service;

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.util.Log;
import android.view.View;
import android.widget.Button;

public class LisiActivity extends AppCompatActivity implements View.OnClickListener {

    private Button bindBtn;
    private Button unbindBtn;

    private String TAG = "LisiActivity";
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG,"onServiceConnected...");
            TestService testService = ((TestService.Guanjia)service).getServiceObject();
            testService.fly();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG,"onServiceDisconnected...");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lisi);

        bindID();
    }

    private void bindID() {

        bindBtn = findViewById(R.id.lisi_bind_btn);
        unbindBtn = findViewById(R.id.lisi_unbind_btn);

        bindBtn.setOnClickListener(this);
        unbindBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.lisi_bind_btn:
                Intent intent = new Intent(this,TestService.class);
                bindService(intent,connection,BIND_AUTO_CREATE);
                break;
            case R.id.lisi_unbind_btn:
                unbindService(connection);
                break;
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值