package com.lidaochen.test001; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; 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 v) { Intent intent = new Intent(); intent.setAction("com.lidaochen.custom"); intent.putExtra("name", "新聞聯播天天晚上7點準時開播!"); // 發送無序廣播 sendBroadcast(intent); } }
package com.lidaochen.test002; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class ReceiveCustomReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. // 終止廣播 (這裏終止了廣播,當前廣播接受者依然能夠收到數據) abortBroadcast(); // 接收無序廣播 攜帶的數據 String content = intent.getStringExtra("name"); Toast.makeText(context, content, Toast.LENGTH_SHORT).show(); Log.e("收到數據:", content); } }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.lidaochen.test002"> <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=".ReceiveCustomReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.lidaochen.custom"></action> </intent-filter> </receiver> </application> </manifest>