咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

10、Android调用web3j接口查询余额

启动 ganache-gui

打开就可以了,设置一下HOSTNAMEganache_conf.png

API

1
implementation ('org.web3j:core:3.3.1-android')

这个库完全实现了以太坊的 Json-RPC 客户端的协议,包含HTTP和IPC,我们就用HTTP的就可以了, Documentation

代码

直接贴 Web3j 的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public void test(){
Web3j web3 = Web3jFactory.build(new HttpService("http://192.168.0.92:7545"));
try {
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().sendAsync().get();
String clientVersion = web3ClientVersion.getWeb3ClientVersion();

Log.e(TAG, "clientVersion: "+clientVersion);

EthCoinbase coinbase = web3.ethCoinbase().sendAsync().get();
String address = coinbase.getAddress();
Log.e(TAG, "coinbase address: " + address );

EthBlockNumber blockNumber = web3.ethBlockNumber().sendAsync().get();
Log.e(TAG, "BlockNumber: "+blockNumber.getBlockNumber() );

BigInteger balance = web3.ethGetBalance(address, DefaultBlockParameterName.LATEST).sendAsync().get().getBalance();

Log.e(TAG, "balance :" + balance.toString());
Log.e(TAG, "balance getLowestSetBit:" + balance.getLowestSetBit());
Log.e(TAG, "balance longValue:" + balance.longValue());

} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}