欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

androidService基础(启动服务与绑定服务),

来源: 开发者 投稿于  被查看 33234 次 评论:233

androidService基础(启动服务与绑定服务),


     Service是Android中一个类,它是Android 四大组件之一,使用Service可以在后台执行耗时的操作(注意需另启子线程),其中Service并不与用户产生UI交互。其他的应用组件可以启动Service,即便用户切换了其他应用,启动的Service仍可在后台运行。一个组件可以与Service绑定并与之交互,甚至是跨进程通信。通常情况下Service可以在后台执行网络请求、播放音乐、执行文件读写操作或者与contentprovider交互等。

  本文主要讲述service服务里的启动与绑定服务。

首先,XML程序如下:

<?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=".MainActivity">
 
    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="operate"
        android:text="启动服务" />
 
    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="停止服务"
        android:onClick="operate" />
 
    <Button
        android:id="@+id/bind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="绑定服务"
        android:onClick="operate" />
 
    <Button
        android:id="@+id/unbind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="解绑服务"
        android:onClick="operate"/>
 
</LinearLayout>

创建一个service类,并写创建、启动、绑定、摧毁、解绑五个方法

代码如下:

package com.example.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 {
 
    private int i;
    public MyService() {
    }
    //创建
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("TAG","服务创建了");
    }
 
    class MyBinder extends Binder {
        //定义自己需要的方法(实现进度监控)
        public int getProcess(){
            return i;
        }
    }
 
 
    //启动方法
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("TAG","服务启动了");
        return super.onStartCommand(intent, flags, startId);
    }
 
    //解绑
    @Override
    public boolean onUnbind(Intent intent) {
        Log.e("TAG","服务解绑了");
        return super.onUnbind(intent);
    }
 
    //摧毁
    @Override
    public void onDestroy() {
        Log.e("TAG","服务摧毁了");
        super.onDestroy();
    }
 
    //绑定方法
    @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();
    }
}

然后在MainActivity里面写点击启动方法:

public void operate(View v) {
        switch (v.getId()){
            case R.id.start:
                //启动服务 :创建——启动——摧毁
                //如果服务已经创建了,后续重复启动,操作的都是同一个服务,不回在创建新 的服务,除非先摧毁他
                Intent it1=new Intent(this,MyService.class);
                startService(it1);
                break;
            case R.id.stop:
                Intent it2=new Intent(this,MyService.class);
                stopService(it2);
                break;
        }
    }

然后写绑定的方法:

注意:捆绑和解绑的对象应该是同一个对象,如果捆绑与解绑的对象不一样,则会报如下的错误:

Service not registered: com.m1910.servicetest.MainActivity$1@41ddfcc0

本篇文章捆绑与解绑的对象都是conn,定义一个全局变量:

 
    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        }
 
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
 
        }
    };

然后写解绑与捆绑的方法:

case R.id.bind:
                //绑定服务
                Intent it3=new Intent(this,MyService.class);
                bindService(it3,conn,BIND_AUTO_CREATE);
                break;
 
            case R.id.unbind:
                //解绑服务
//                unbindService(conn);
//                if (isBound) {
//                    unbindService(conn);// 解绑服务
//                    isBound = false;
//                }
                    unbindService(conn);//解绑服务
                break;

完整的程序如下:

package com.example.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;
 
public class MainActivity extends AppCompatActivity {
 
    private boolean isBound = false;
 
    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        }
 
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
 
        }
    };
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    public void operate(View v) {
        switch (v.getId()){
            case R.id.start:
                //启动服务 :创建——启动——摧毁
                //如果服务已经创建了,后续重复启动,操作的都是同一个服务,不回在创建新 的服务,除非先摧毁他
                Intent it1=new Intent(this,MyService.class);
                startService(it1);
                break;
            case R.id.stop:
                Intent it2=new Intent(this,MyService.class);
                stopService(it2);
                break;
            case R.id.bind:
                //绑定服务
                Intent it3=new Intent(this,MyService.class);
                bindService(it3,conn,BIND_AUTO_CREATE);
                break;
 
            case R.id.unbind:
                //解绑服务
//                unbindService(conn);
//                if (isBound) {
//                    unbindService(conn);// 解绑服务
//                    isBound = false;
//                }
                    unbindService(conn);//解绑服务
                break;
 
        }
    }
}

到此这篇关于android Service基础(启动服务与绑定服务)的文章就介绍到这了,更多相关android Service内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

您可能感兴趣的文章:
  • Android服务Service教程
  • Android四大组件之Service详解
  • 浅谈Android Service服务的高级技巧

用户评论