安卓设备应用只使用蜂窝网络通讯代码实现
时间: 2024-04-30 11:23:49 浏览: 127
安卓网络通信
以下是使用蜂窝网络通讯代码的示例:
1. 检查蜂窝网络是否可用
```java
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (networkInfo != null && networkInfo.isConnected()) {
// 蜂窝网络可用
} else {
// 蜂窝网络不可用
}
```
2. 发送HTTP请求
```java
URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 获取响应数据
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 处理响应数据
} else {
// HTTP请求失败
}
conn.disconnect();
```
3. 发送SMS短信
```java
SmsManager smsManager = SmsManager.getDefault();
String destinationAddress = "1234567890";
String text = "Hello World!";
smsManager.sendTextMessage(destinationAddress, null, text, null, null);
```
请注意,上述代码仅是示例代码,具体实现方式可能因不同的业务需求而异。建议在实际开发中仔细考虑各种情况,并进行必要的错误处理和异常处理。
阅读全文