自訂廣播(BroadcastReceiver)事件 --Android開發

來源:互聯網
上載者:User

標籤:nbsp   註冊   round   height   inf   version   idm   launch   pre   

本例示範自訂廣播事件。我們需要做的是,在主活動中寫發送廣播的代碼,然後在接收廣播的類中寫接收廣播的代碼。1、主活動中點擊按鈕後發送廣播MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("com.thanlon.diyAction");//自訂廣播的類型
//        sendBroadcast(intent);//直接發送廣播

intent.putExtra("info_key", "廣播傳遞的參數");//發送帶參數的廣播;
sendBroadcast(intent, "com.thanlon.permission.name");//需要帶指定許可權的接受者才能接收到廣播
    }
}
2、寫一個接收廣播的類。MyBroadcastReceiver.java:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("thanlon", "收到自訂廣播");
String info = intent.getStringExtra("info_key");//接受廣播帶的參數
Log.d("thanlon", info);
}
}
3、在AndroidManifest.xml中配置自訂廣播類型和自訂接收者的許可權(註冊廣播)。AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="thonlon.example.cn.diybroadcastreceiverdemo">
<!--自訂接收者許可權-->
<permission android:name="com.thanlon.permission.name" />
<!--配置接收者許可權-->
<uses-permission android:name="com.thanlon.permission.name" />
<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=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.thanlon.diyAction" />
</intent-filter>
</receiver>
</application>
</manifest>
 4、在logcat下查看廣播接受者是否接收到廣播。

  很明顯正確接收到廣播並且接收到了 廣播傳遞的參數。

自訂廣播(BroadcastReceiver)事件 --Android開發

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.