安卓开发之无序广播
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>