kotlin如何使用Websocket发送监听到的短信数据到服务器
package com.example.sms_cqa
import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.telephony.SmsMessage
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import okhttp3.*
import java.text.SimpleDateFormat
import java.util.*
private const val TAG = "MyBroadcastReceiver"
class MainActivity : AppCompatActivity() {
val listener = EchoWebSocketListener()
val request: Request = Request.Builder()
.url("ws://网址/api")
.addHeader("Authorization","Bearer gSGIgfdsosGIYgfds").build()
val client = OkHttpClient()
val websocket = client.newWebSocket(request, listener)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 判断并获取权限
var smsPermissions = arrayOf("Manifest.permission.RECEIVE_SMS")
var isSmsGranted =
android.content.pm.PackageManager.PERMISSION_DENIED == ActivityCompat.checkSelfPermission(
this,
Manifest.permission.RECEIVE_SMS
)
if (isSmsGranted) {
ActivityCompat.requestPermissions(this, smsPermissions, 1)
}
smsPermissions = arrayOf("Manifest.permission.READ_SMS")
isSmsGranted =
android.content.pm.PackageManager.PERMISSION_DENIED == ActivityCompat.checkSelfPermission(
this,
Manifest.permission.READ_SMS
)
if (isSmsGranted) {
ActivityCompat.requestPermissions(this, smsPermissions, 1)
}
// 注册广播接收器
val br: BroadcastReceiver = MyBroadcastReceiver()
val filter = IntentFilter().apply {
addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED)
addAction("android.provider.Telephony.SMS_RECEIVED")
priority = 1000
}
registerReceiver(br, filter)
}
}
class EchoWebSocketListener : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
// 发送
}
override fun onMessage(webSocket: WebSocket, text: String) {
// 接收
// logger.e("onMessage","onMessage: " + text);
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
// 远程端暗示没有数据交互时回调
// webSocket.close(1000, null)
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
//服务器关闭后
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
//服务器中断
Log.e("onFailure","onFailure: " + t.toString()+response.toString())
}
}
private class MyBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val objs = intent.extras!!["pdus"] as Array<Any>?
for (obj in objs!!) {
val pdu = obj as ByteArray
val sms: SmsMessage = SmsMessage.createFromPdu(pdu)
// 短信的内容
var message = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()) + "\n发件人:" + sms.getOriginatingAddress() + "\n" + sms.getMessageBody()
}
}
}
这个值我有点不知道怎么传
有时候问题出的很简单,但让你费心费力还找不到!!!!
因为message加了换行,所以出毛病了!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论