高版本无法接收全局静态广播,也可以直接将targetvision版本降低至较低版本,例如api26.
安卓广播基础教程:
http://www.manew.com/thread-100075-1-1.html
教程中使用的方式是安卓低版本的,如果是高版本的直接使用教程里的方式是接收不到广播的,如 8.0及以上版本
安卓高版本静态广播
安卓静态广播:
1:创建对应的类并继承广播接口,实现onReceive方法
2:在安卓清单中配置广播接收
3:Intent对象中setComponent
广播类
package com.jing.broadcasttest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class mBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Callme", Toast.LENGTH_SHORT).show();
}
}
安卓清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jing.broadcasttest">
<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=".mBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="callme" />
</intent-filter>
</receiver>
</application>
</manifest>
发送广播
package com.jing.broadcasttest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("callme");
intent.setComponent(new ComponentName("com.jing.broadcasttest","com.jing.broadcasttest.mBroadcastReceiver"));
//ComponentName 参数1:接收方App包名,参数2:接收类名
sendBroadcast(intent);
}
});
}
}
网友评论