1, 안드로이드 방송 정적 등록 및 등록 동적으로 분할
도 2를 참조하면, 다음은 간단한 정적 등록의 예
- 연속 만들기
BroadcastReceiver
하위 범주를
public class DeviceBootReceiver extends BroadcastReceiver {
private static final String TAG = DeviceBootReceiver.class.getName();
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "开机了:" + intent.getAction());
}
}
전화 수신이 클래스의 기능은 라디오에서 전환됩니다.
- 에서는
AndroidManifest.xml
하는 요소 레지스터
<receiver android:name=".DeviceBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
action
값 태그는 여기에서 시작 방송, 방송의 유형과 일치하는 데 사용됩니다.
휴대 전화가 켜져있을 때 시스템에서 메시지를받을 수 있도록.
마찬가지로, 우리는 또한 응용 프로그램이 설치 제거 응용 프로그램, USB 플러그 및 기타 방송 시스템을 모니터링 할 수 있습니다. 그냥 action
약간 다른 값.
<receiver android:name=".OtherStateReceiver">
<intent-filter>
<!--电量过低-->
<action android:name="android.intent.action.BATTERY_LOW" />
<!--USB连接-->
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<!--USB断开-->
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
<!--软件包安装-->
<action android:name="android.intent.action.PACKAGE_ADDED" />
<!--软件包卸装-->
<action android:name="android.intent.action.PACKAGE_REMOVED" />
</intent-filter>
</receiver>
위의 방송 부팅뿐만 아니라, 다른 방송사 등의 등록이 성공적 것을 제공하는 API 레벨 <26 (Android8.0 이하)
. 구글은받는 프로그램 영구 메모리 자원의 소모를 방지하기 위해, 몇 가지 금지 Manifest declared receiver
. 우리는 당신이 동적 등록을 사용해야들을 계속하고 싶다.
(3) 다음은 동적 등록의 예이다 :
public class SystemBroadcastReceiverActivity extends AppCompatActivity {
private SystemBroadcastReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_system_broadcast_receiver);
IntentFilter filter = new IntentFilter();
//USB连接
filter.addAction(Intent.ACTION_POWER_CONNECTED);
//USB断开
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
receiver = new SystemBroadcastReceiver();
registerReceiver(receiver, filter);
}
private class SystemBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println(intent.getAction());
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
그런 다음 AndroidManifest.xml
레지스터 Activity
캔을.
4, 사용자 정의 방송
그 수신 방송되는 시스템 앞에, 우리는 또한 같은 응용 프로그램 또는 다른 응용 프로그램에서 사용자 정의 된 방송 및 수신을 보낼 수 있습니다.
다음은 사용자 정의 방송의 정적 등록은 다음과 같습니다
- a의 설립
Activity
, a는Button
, 방송 클릭을 보내
public class CustomSenderActivity extends AppCompatActivity {
public static final String BROADCAST_ACTION = "com.hncj.android.manifest.CustomSenderActivity";
public static final String BROADCAST_CONTENT = "broadcast_content";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_sender);
}
@SuppressLint("WrongConstant")
public void sendBroadcast(View view) {
Intent intent = new Intent();
intent.setAction(BROADCAST_ACTION);
intent.putExtra(BROADCAST_CONTENT, "我发送了广播,你看收没收到?");
//解决API26及以上的Android静态注册的Receiver收不到广播
//第一种解决方案:设置标志 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
intent.addFlags(0x01000000); //不论是一个应用自己发自己收还是一个应用发一个应用收,都可以实现效果
//第二种解决方案:指定包名(这里是一个应用,自己发,自己收,都在一个包下)
//intent.setPackage(getPackageName()); //如果是给另一个应用发广播 则写成intent.setPackage("另一个项目应用接收者的包名");
//第三种解决方案: 明确指定包名,类名
//intent.setComponent(new ComponentName(this, CustomReceiver.class)); //如果是给另一个应用发广播 则写成 intent.setComponent(new ComponentName("另一个应用接收者包名", "另一个应用接收者类名"));
//发送广播
sendBroadcast(intent);
}
}
- 레이아웃 파일
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="40dp">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="sendBroadcast"
android:background="#008080"
android:textSize="30dp"
android:text="发送广播"></Button>
</LinearLayout>
- 수신자
public class CustomReceiver extends BroadcastReceiver {
private static final String TAG = CustomReceiver.class.getName();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "我收到了来自" + action + "的广播");
}
}
AndroidManifest.xml
파일
<activity android:name=".manifest.CustomSenderActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".manifest.CustomReceiver">
<intent-filter>
<action android:name="com.hncj.android.manifest.CustomSenderActivity" />
</intent-filter>
</receiver>
여기에 현재 프로젝트의받는 사람뿐만 아니라 다른 프로젝트에서받는 사람이 코드는 기본적으로 동일합니다.
관련 API :
질서 방송을 보내기 :
<!--广播中携带数据-->
Bundle bundle = new Bundle();
bundle.putString("username", "nacy");
sendOrderedBroadcast(intent, null, null, null, Activity.RESULT_OK, null, bundle);
우선 수신자를 설정합니다 (--1000-1000를) 즉, 더 높은 우선 순위를받을 수있는 수신자 정의, 빨리 수신 된 방송
<receiver android:name=".manifest.CustomReceiver">
<!--priority可以设置优先级-->
<intent-filter android:priority="9">
<action android:name="com.hncj.android.manifest.CustomSenderActivity" />
</intent-filter>
</receiver>
방송의 종료 :
<!--广播不再向下传递-->
abortBroadcast();
데이터 방송을 제거합니다 :
//取出Bundle对象,类似于一个map
Bundle bundle = getResultExtras(true);
허가를받은 설정받는 사람 :()
- 먼저 보낸 사람이
AndroidManifest.xml
사용 권한 (패키지 이름 + 권한 이름)을 선언합니다
<permission android:name="com.hncj.android.RECEIVER_PERMISSION" />
- 정의 권한받는 사람이 보낼 수있는 시간이 필요합니다 :
sendOrderedBroadcast(intent, Manifest.permission.RECEIVER_PERMISSION, null, null, Activity.RESULT_OK, null, bundle);
- 필요에의 수신자
AndroidManifest.xml
권한 :
<uses-permission android:name="com.hncj.android.RECEIVER_PERMISSION" />
보낸 사람의 권한을 설정 :( 누가 저를 줄 수 있습니다)
- 첫 번째받는 사람에
AndroidManifest.xml
권한을 선언합니다
<permission android:name="com.hncj.android.SENDER_PERMISSION" />
- 설명 권리 송신자는 수신자 탭을 가지고 :
<receiver android:name=".manifest.CustomReceiver" android:permission="com.hncj.android.SENDER_PERMISSION">
<intent-filter android:priority="9">
<action android:name="com.hncj.android.manifest.CustomSenderActivity" />
</intent-filter>
</receiver>
- 보낸 사람의
AndroidManifest.xml
사용 권한
<uses-permission android:name="com.hncj.android.SENDER_PERMISSION" />
동적 정의 방송 만 액션 지정 콘텐츠에, 상술 한 동적 등록 예가 등록한다.