我正在用android开发一个自动短信回复应用程序,因此我需要每当用户选择启动该服务时,用户都应仅单击该按钮,之后广播公司才应对SMS_RECEIVED广播做出反应,但是无论何时我启动广播开始对此应用程序做出反应。请为我提供帮助。
请注意,仅在服务启动时才应接收广播接收器
这是我的MainACtivity.kt
companion object
{
private const val TAG="AnoReplier"
private val permissions= arrayOf(Manifest.permission.READ_SMS,Manifest.permission.SEND_SMS,Manifest.permission.RECEIVE_SMS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
private const val REQUEST_CODE_PERMISSIONS=1
lateinit var service:Intent
lateinit var inst:MainActivity
fun getInstance():MainActivity
{
return inst
}
}
override fun onStart() {
super.onStart()
inst=this
service=Intent(baseContext,SMSService::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
servicebutton.setOnCheckedChangeListener{ compoundButton: CompoundButton, b: Boolean ->
if(b)
{
Log.d(TAG,"True condition of toggle button")
startService(service)
Log.d(TAG,"Service started")
compoundButton.setBackgroundColor(Color.GREEN)
}
else
{
stopService(service)
compoundButton.setBackgroundColor(Color.RED)
}
}
}
}
这是我的服务类代码,在其中注册了广播
class SMSService: Service() {
lateinit var broadcastReceiver: BroadcastReceiver
private val TAG="SMS Service"
override fun onCreate() {
var filter=IntentFilter()
filter.addAction("android.provider.Telephony.SMS_RECEIVED")
var generator=SMSBroadcastGenerator()
broadcastReceiver=SMSBroadcastGenerator()
registerReceiver(broadcastReceiver,filter)
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onDestroy() {
Toast.makeText(MainActivity.getInstance(),"Background Service has started",Toast.LENGTH_SHORT).show()
unregisterReceiver(broadcastReceiver)
Log.d(TAG,"Receiver Unregistered")
super.onDestroy()
}
}
这是我的广播课的代码
class SMSBroadcastGenerator:BroadcastReceiver() {
override fun onReceive(p0: Context?, intent: Intent?) {
try {
var action:String?=intent?.action
if(action.equals("android.provider.Telephony.SMS_RECEIVED"))
{
var data=intent?.extras?.get("pdus") as Array<*>
var msg=""
for(i in 0 until data.size)
{
var format=intent?.extras?.getString("format")
var message=SmsMessage.createFromPdu(data[i] as ByteArray ,format)
msg+=message.originatingAddress
}
}
}
catch(exc:Exception)
{
Log.e("SMSBroadcast Receiver","An error occured.Details: ${exc}")
}
}
}
这是我的Maanifest.xml:-
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".SMSBroadcastGenerator">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
<service android:name=".SMSService"/>
</application>