Service的使用

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


    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="启动服务"
        />
    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止服务"
        />
    <Button
        android:id="@+id/bind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="绑定服务"
        />
    <Button
        android:id="@+id/unbindService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="解除服务"
        />

</LinearLayout>
package com.example.imocc_service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    //IBinder
    //ServicerConnection用于绑定客户端和服务端
    //进度监控
private ServiceConnection conn = new ServiceConnection() {
    //当客户端正常连接着服务时,执行服务的绑定操作会被调用
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.e("TAG","慕课");
        MyService.MyBinder mb = ( MyService.MyBinder)service;
        int step = mb.getProcess();
        Log.e("TAG","当前进度是:" + step);
    }
    //当客户端和服务端的连接丢失了
    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};
  private Button button1,button2,button3,button4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initiv();
        oeEven();

    }

    private void oeEven() {
        //启动服务
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MyService.class);
                startService(intent);
            }
        });
        //启动服务:创建--》启动--》销毁
        //如果服务已经创建了,后续重复启动,操作的都是同一个服务,不会再重新创建了,除非你先销毁它
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(MainActivity.this,MyService.class);
                stopService(intent2);
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            //绑定服务:最大的作用是用来实现对Service执行的任务进行进度监控
            //TODO:BIND_AUTO_CREATE代表如果服务不存在则创建一个
            //如果服务不存在:onCreat-->onBind-->onUnbind-->onDestory(此时服务没有在后台运行,并且它会随着Activity的摧毁而解绑并销毁)
            //服务已经存在:那么bindService方法只能使onBind方法被调用,而unBindService方法只能使onUnbind被调用
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent(MainActivity.this,MyService.class);
                bindService(intent3, conn,BIND_AUTO_CREATE);
            }
        });
        button4.setOnClickListener(new View.OnClickListener() {
            //解绑服务
            @Override
            public void onClick(View v) {
                unbindService(conn);
            }
        });

    }

    private void initiv() {
        button1 = findViewById(R.id.start);
        button2 = findViewById(R.id.stop);
        button3 = findViewById(R.id.bind);
        button4 = findViewById(R.id.unbindService);
    }


}
package com.example.imocc_service;

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

public class MyService extends Service {
    public MyService() {
    }
private int i;
    //创建
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("TAG","服务创建了");

        //开启一个线程(从1数到100),用于模拟耗时的任务
        new Thread(){
            @Override
            public void run() {
                super.run();
                try{
                    for(i = 1;i<= 100; i++){
                        sleep(1000);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //启动
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("TAG","服务启动了");
        return super.onStartCommand(intent, flags, startId);
    }

    //绑定
    //IBinder:在android中用于远程操作对象的一个基本接口
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
     //   throw new UnsupportedOperationException("Not yet implemented");
        Log.e("TAG","服务绑定了");
        return new MyBinder();
    }

    /**对于onBind方法而言,要求返回IBinder对象
     * 实际上,我们会自己定义一个内部类,集成Binder类
     */

    class MyBinder extends Binder{
        //定义自己需要的方法(实现进度监控)
        public int getProcess(){
            return i;
        }

    }


    //解绑
    @Override
    public boolean onUnbind(Intent intent) {
        Log.e("TAG","服务解绑了");
        return super.onUnbind(intent);
    }
    //摧毁

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("TAG","服务摧毁了");
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值