Http远程控制App

Http远程控制App
最近有项目需求通过远程http来控制android app,首先需要在app中内嵌http服务,开始考虑用jetty,后来发现有更加轻量级的NanoHttpd组件,GitHub地址:https://github.com/NanoHttpd/nanohttpd
用起来比较轻便,最终通过在启动app时启动一个Service 实例化NanoHttpd ,在开发中遇到一个问题就是App有多个Activity, Service 调用Activity 中的方法,可能大家想到最简单的做法是通过广播来实现,因为 Service和Activity属于两个进程,在android中最简单的进程调用就是通过广播来实现。
在这里插入图片描述
但是有个问题就是广播延迟比较严重,为了解决延迟问题。最终选择了通过两个AIDL 接口来实现,用一个AIDL作另一个的会调接口。具体做法如下:
IClientCallBack.aidl

// IClientCallBack.aidl
package com.test.application;

// Declare any non-default types here with import statements

interface IClientCallBack {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    int getResult(String action);
}

IGetData.aidl

// IGetData.aidl
package com.test.application;
import com.test.application.IClientCallBack;

// Declare any non-default types here with import statements

interface IGetData {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
   void register(IClientCallBack callback);
}

MainService .java

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import com.test.application.IClientCallBack;
import com.test.application.IGetData;

import java.io.IOException;

/**
 * MainService.
 */
public class MainService extends Service{

    MainService mainService;
    /**
     * HttpServer.
     */
    public static HttpServer mHttpServer = null;
    public static IClientCallBack callBack;

    @Nullable
    @Override
    public IBinder onBind(final Intent intent) {
        return mBinder;
    }

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

    @Override
    public void onCreate() {
    }

    @Override
    public void onDestroy() {
    }
    
    /*
     * MsgBinder.
     */
    public class MsgBinder extends Binder {
        /**
         * Service.
         * @return Service
         */
        public MainService getService() {
            return MainService.this;
        }
    }

    IGetData.Stub  mBinder= new IGetData.Stub(){
        @Override
        public void register(IClientCallBack mcallback) throws RemoteException {
            callBack = mcallback;
            mHttpServer.setCallBack(callBack);
        }
    };

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值