• Android中使用GRPC


    笔者所用开发环境:Win7 x64,Android Studio3.2.1,JDK1.8,Gradle 4.6

    0.编写.proto文件、编译.proto生成对应Java源文件,具体步骤略(参考上一篇文章https://www.cnblogs.com/areful/p/10404506.html)

    1.新建Android app项目,将上一步生成的Java源文件复制到项目根目录。修改build.gradle:

    ...
    buildscript {
        ...
        dependencies {
            ...
            classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.6'
        }
    }
    ...
    

    2.修改app/build.gradle:

    apply plugin: 'com.android.application'
    apply plugin: 'com.google.protobuf'
    
    ...
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:28.0.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    
        implementation 'io.grpc:grpc-netty-shaded:1.15.1'
        implementation 'io.grpc:grpc-netty:1.15.1'
        implementation 'io.grpc:grpc-core:1.15.1'
        implementation 'io.grpc:grpc-protobuf:1.15.1'
        implementation 'io.grpc:grpc-stub:1.15.1'
        implementation 'io.grpc:grpc-alts:1.15.1'
        implementation 'io.netty:netty-tcnative-boringssl-static:2.0.18.Final'
        implementation 'com.google.protobuf:protobuf-java-util:3.0.0-beta-1'
    }
    

    3.添加app需要权限:

        <uses-permission android:name="android.permission.INTERNET" />
    

    4.app中调用GRPC:

    package cn.areful.sample.grpc;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    
    import io.grpc.examples.helloworld.HelloWorldClient;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            HelloWorldClient client = new HelloWorldClient("10.102.54.2", 50051);
            try {
                client.greet("World!");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    client.shutdown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    } 
    

    5.先Java中运行Server端(参见https://www.cnblogs.com/areful/p/10404506.html),再运行app,logcat:

  • 相关阅读:
    SQLite的总结与在C#的使用
    Linq中比较字符串类型的日期
    C#中委托,匿名函数,lamda表达式复习
    MYSQL中SUM (IF())
    C#在属性中用Lambda语法
    Mysql绿色版安装和遇到的问题
    FormsAuthentication权限管理
    存储过程中高性能安全式SQL拼接
    JavaScript实现搜索联想功能
    JavaScript组成
  • 原文地址:https://www.cnblogs.com/areful/p/10405266.html
Copyright © 2020-2023  润新知