扯淡前言
已经很久没有写文章了,最近有人问我怎么断片(篇),我发现...不扯淡了,开始讲自定义权限广播
思路
就是利用Android中可以自定义权限对广播增加了一层安全保护
举个栗子
上菜(贴代码,简单明了)
·广播的定义(这边是静态注册)
class CustomReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, data: Intent?) {
if(data != null) {
var param = data.getStringExtra("message")
var result:String?
result = String.format("get the receiver for %s", param)
Toast.makeText(context, result, Toast.LENGTH_SHORT).show()
}
}
}
·AndroidManifest.xml的配置
<uses-permission android:name="jason.com.receiver" ></uses-permission>
<permission android:protectionLevel="normal" android:name="jason.com.receiver"></permission>
<application
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=".CustomReceiver" android:permission="jason.com.receiver">
<intent-filter>
<action android:name="com.jason.message"/>
<category android:name="receiver" />
</intent-filter>
</receiver>
</application>
·广播的调用(当然这个是全局的广播,如果仅限制自己app内部使用,推荐本地广播LocalBroadcastManager)
class MainActivity : AppCompatActivity() {
private lateinit var sendBtn:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sendBtn = findViewById(R.id.btn_send)
sendBtn.setOnClickListener {
var intent = Intent("com.jason.message")
intent.addCategory("receiver")
intent.putExtra("message","custom test")
sendOrderedBroadcast(intent, "jason.com.receiver")
}
}
}
没啦!就是这么简单,毕竟只是个栗子,如果这个栗子有错误欢迎指正
网友评论