標籤:android 廣播 一 初接觸
廣播也是通過intent來傳遞的。
廣播分為有序廣播和標準廣播。
標準廣播是發送廣播後,所有的廣播接受者都可以去接收。
有序廣播是發送廣播後,由高優先順序的先接收廣播,處理後再往後廣播,同時高優先順序的接受者可以中斷廣播。
廣播註冊可以分為動態註冊和靜態註冊。下面就先將靜態註冊。靜態註冊是建立廣播接收者時,是通過new----->other------->Brodcast Receiver來實現的。AS會自動幫我們在Manifext.xml裡註冊好,我們只需要添加intent-filter及在裡面加入action即可。
下面的例子是靜態注入,發送一條標準廣播,然後接收。
1、MainActivity
package com.yuanlp.sendbroadcast;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View view){ Intent intent=new Intent("com.yuanlp.sendBroadcast.MY_BROADCAST"); //設定intent的action sendBroadcast(intent); //發送廣播 }}
2、 activity_main.xml裡
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.yuanlp.sendbroadcast.MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click" android:text="發送廣播" tools:layout_editor_absoluteX="137dp" tools:layout_editor_absoluteY="136dp"/></android.support.constraint.ConstraintLayout>
3、MyReceiver
package com.yuanlp.sendbroadcast;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"接收到廣播",Toast.LENGTH_SHORT).show(); }}
4、Manifext.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.yuanlp.sendbroadcast"> <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=".MyReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.yuanlp.sendBroadcast.MY_BROADCAST"></action> </intent-filter> </receiver> </application></manifest>
運行程式後,在點擊按鈕後,自訂的廣播 接受者會受到廣播,並彈出toast
本文出自 “YuanGuShi” 部落格,請務必保留此出處http://cm0425.blog.51cto.com/10819451/1942565
Android 廣播接受者