连接远程Service

1.新建远程服务器端继承Service类

import android.app.Service;

2.在AndroidManifest.xml配置 具体位置参见前篇文

action name本质上就是一个字符串没有特殊要求


            
                
            

3.编写客户端的mainactivity代码

客户端的main-xml




    

main-activity 这里只是将绑定方法和解绑方法搭建上,但是并未具体实现其中内容,下面(最后)会对具体内容进行实现

注意这里的Intent用的是隐式意图内容物跟服务器端的action内容保持一致

import android.content.ComponentName;
import android.content.Context;
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.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private EditText et_main_find;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_main_find = findViewById(R.id.et_main_find);
    }

    private ServiceConnection conn;

    public void bindRemoteService(View v) {
        Intent intent = new Intent("com.example.servicedemo.servicedemo.RemoteService.Action");
        if (conn == null) {
            conn = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

                }

                @Override
                public void onServiceDisconnected(ComponentName componentName) {

                }
            };
            bindService(intent, conn, Context.BIND_AUTO_CREATE);
            Toast.makeText(this, "绑定service", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "已经绑定service", Toast.LENGTH_SHORT).show();
        }


    }

    public void invokeRemoteService(View v) {

    }

    public void unbindRemoteService(View v) {
        if (conn != null) {
            unbindService(conn);
            conn = null;
            Toast.makeText(this, "已经解绑service", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "尚未绑定service", Toast.LENGTH_SHORT).show();
        }
    }
}

造一个实体类实现可打包接口Parcelable

import android.os.Parcel;
import android.os.Parcelable;


public class Godv implements Parcelable {
    private int id;
    private String name;
    private double price;

    public Godv() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    protected Godv(Parcel in) {
        //这块顺序需要跟打包顺序一致
        id = in.readInt();
        name = in.readString();
        price = in.readDouble();
    }

    public static final Creator CREATOR = new Creator() {
        //解包方法 读取包中的数据并封装成对象
        @Override
        public Godv createFromParcel(Parcel in) {

            return new Godv(in);
        }

        //返回指定大小的对象容器
        @Override
        public Godv[] newArray(int size) {
            return new Godv[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    //将当前对象属性数据打包 写入到包对象中
    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeInt(id);
        parcel.writeString(name);
        parcel.writeDouble(price);
    }
}

新建aidl文件两个

Godv.aidl

package com.example.servicedemo;
parcelable Godv;

IGodvManager.aidl

package com.example.servicedemo;

import com.example.servicedemo.Godv;
interface IGodvManager {
 //写的接口方法 
   Godv getGodvById(int id);
}

aidl文件写完 点击make_project  此时会发现gen目录下多了一个文件 里面主要声明接口与方法 这里就不再详细说明

连接远程Service_第1张图片 连接远程Service_第2张图片

服务器端RemoteService代码

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.IBinder;
import android.os.RemoteException;


import java.io.FileDescriptor;
import java.io.PrintWriter;

public class RemoteService extends Service {
    public RemoteService() {
        super();
    }

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

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

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

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

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

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }

    //再调用的时候会返回对象补全代码 绑定
    @Override
    public IBinder onBind(Intent intent) {
        return new GodvServices();
    }

    //解绑
    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
    }

    @Override
    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
        super.dump(fd, writer, args);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
    }
//写内部类继承 IGodvManager.Stub 自动生成文件里面的

    class GodvServices extends IGodvManager.Stub {


        @Override
        public Godv getGodvById(int id) throws RemoteException {
            return new Godv(id, "godv", 20.0);
        }
    }
}

将服务器中的实体类和aidl两个文件连带着包原封不动的复制到客户端再生成一个通信类

连接远程Service_第3张图片

最后将客户端的代码补全

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.servicedemo.Godv;
import com.example.servicedemo.IGodvManager;


public class MainActivity extends AppCompatActivity {
    private EditText et_main_find;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_main_find = findViewById(R.id.et_main_find);
    }

    private ServiceConnection conn;
    private IGodvManager iGodvManager;

    public void bindRemoteService(View v) {
        Intent intent = new Intent("android.intent.action.RESPOND_VIA_MESSAGE");
        intent.setPackage("com.example.servicedemo");
        if (conn == null) {
            conn = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                    iGodvManager = IGodvManager.Stub.asInterface(iBinder);
                }

                @Override
                public void onServiceDisconnected(ComponentName componentName) {

                }
            };
            bindService(intent, conn, Context.BIND_AUTO_CREATE);
            Toast.makeText(this, "绑定service", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "已经绑定service", Toast.LENGTH_SHORT).show();
        }


    }

    public void invokeRemoteService(View v) throws RemoteException {
        if (iGodvManager != null) {
            int id = Integer.parseInt(et_main_find.getText().toString());
            Godv godv = iGodvManager.getGodvById(id);
            Toast.makeText(this, godv.toString(), Toast.LENGTH_SHORT).show();
        }
    }

    public void unbindRemoteService(View v) {
        if (conn != null) {
            unbindService(conn);
            conn = null;
            iGodvManager = null;
            Toast.makeText(this, "已经解绑service", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "尚未绑定service", Toast.LENGTH_SHORT).show();
        }
    }
}

工程结构

连接远程Service_第4张图片 连接远程Service_第5张图片

你可能感兴趣的:(安卓基础学习,android)