📅  最后修改于: 2023-12-03 15:09:10.752000             🧑  作者: Mango
本文将介绍如何构建一个简单的比特币价格追踪器 Android 应用程序。应用程序将向用户显示当前的比特币价格以及最近的价格历史记录。
本应用程序将使用以下技术:
首先,在 Android Studio 中创建一个新项目。可以选择空白活动或基于模板的活动之一作为起点。
在 AndroidManifest.xml 文件中添加以下网络权限:
<uses-permission android:name="android.permission.INTERNET" />
这将允许应用程序与 Coinbase 或 CoinDesk API 进行通信。
编写布局文件,定义用户界面元素。此应用程序将使用以下元素:
布局文件示例:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/bitcoin_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/price_history"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
定义数据模型来存储比特币价格和历史记录。此应用程序将使用以下模型:
public class BitcoinPrice {
private String mCurrency;
private double mAmount;
public BitcoinPrice(String currency, double amount) {
mCurrency = currency;
mAmount = amount;
}
public String getCurrency() {
return mCurrency;
}
public double getAmount() {
return mAmount;
}
@Override
public String toString() {
return mCurrency + " " + mAmount;
}
}
public class PriceHistory {
private List<BitcoinPrice> mPrices;
public PriceHistory(List<BitcoinPrice> prices) {
mPrices = prices;
}
public List<BitcoinPrice> getPrices() {
return mPrices;
}
public void addPrice(BitcoinPrice price) {
mPrices.add(price);
}
}
为了获取比特币价格,可以使用 Coinbase 或 CoinDesk 提供的 API。
使用以下代码从 Coinbase 获取比特币价格:
public class BitcoinPriceFetcher {
private static final String COINBASE_API_URL = "https://api.coinbase.com/v2/prices/BTC-USD/spot";
public static BitcoinPrice fetchBitcoinPrice() throws IOException, JSONException {
String response = fetchUrl(COINBASE_API_URL);
JSONObject json = new JSONObject(response);
String currency = json.getJSONObject("data").getString("base");
double amount = json.getJSONObject("data").getDouble("amount");
return new BitcoinPrice(currency, amount);
}
private static String fetchUrl(String urlString) throws IOException {
URL url = new URL(urlString);
InputStream stream = url.openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
}
}
使用以下代码从 CoinDesk 获取比特币价格:
public class BitcoinPriceFetcher {
private static final String COINDESK_API_URL = "https://api.coindesk.com/v1/bpi/currentprice/USD.json";
public static BitcoinPrice fetchBitcoinPrice() throws IOException, JSONException {
String response = fetchUrl(COINDESK_API_URL);
JSONObject json = new JSONObject(response);
String currency = json.getJSONObject("bpi").getJSONObject("USD").getString("code");
double amount = json.getJSONObject("bpi").getJSONObject("USD").getDouble("rate_float");
return new BitcoinPrice(currency, amount);
}
private static String fetchUrl(String urlString) throws IOException {
URL url = new URL(urlString);
InputStream stream = url.openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
}
}
为了获取价格历史记录,可以使用 Coinbase 提供的 API。
使用以下代码从 Coinbase 获取价格历史记录:
public class PriceHistoryFetcher {
private static final String COINBASE_API_URL = "https://api.coinbase.com/v2/prices/BTC-USD/historic?period=day";
public static PriceHistory fetchPriceHistory() throws IOException, JSONException {
String response = fetchUrl(COINBASE_API_URL);
JSONObject json = new JSONObject(response);
JSONArray data = json.getJSONArray("data");
List<BitcoinPrice> prices = new ArrayList<>();
for (int i = 0; i < data.length(); i++) {
String currency = data.getJSONObject(i).getString("currency");
double amount = data.getJSONObject(i).getDouble("amount");
BitcoinPrice price = new BitcoinPrice(currency, amount);
prices.add(price);
}
return new PriceHistory(prices);
}
private static String fetchUrl(String urlString) throws IOException {
URL url = new URL(urlString);
InputStream stream = url.openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
}
}
在活动中使用以下代码,以显示比特币价格和历史记录:
public class MainActivity extends AppCompatActivity {
private BitcoinPrice mBitcoinPrice;
private PriceHistory mPriceHistory;
private TextView mBitcoinPriceTextView;
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBitcoinPriceTextView = findViewById(R.id.bitcoin_price);
mRecyclerView = findViewById(R.id.price_history);
new FetchBitcoinPriceTask().execute();
new FetchPriceHistoryTask().execute();
}
private void updateUi() {
mBitcoinPriceTextView.setText(mBitcoinPrice.toString());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(new PriceHistoryAdapter(mPriceHistory.getPrices()));
}
private class FetchBitcoinPriceTask extends AsyncTask<Void, Void, BitcoinPrice> {
@Override
protected BitcoinPrice doInBackground(Void... voids) {
try {
return BitcoinPriceFetcher.fetchBitcoinPrice();
} catch (IOException | JSONException e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(BitcoinPrice bitcoinPrice) {
mBitcoinPrice = bitcoinPrice;
updateUi();
}
}
private class FetchPriceHistoryTask extends AsyncTask<Void, Void, PriceHistory> {
@Override
protected PriceHistory doInBackground(Void... voids) {
try {
return PriceHistoryFetcher.fetchPriceHistory();
} catch (IOException | JSONException e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(PriceHistory priceHistory) {
mPriceHistory = priceHistory;
updateUi();
}
}
}
在本文中,介绍了如何使用 Java 和 Android Studio 来构建比特币价格追踪器 Android 应用程序。应用程序使用 Coinbase 或 CoinDesk 提供的 API 来获取比特币价格和历史记录,并显示在用户界面上。