您好,登錄后才能下訂單哦!
具體步驟:
1、初始化廣播接收器BroadcastReceiver,接收到的廣播會在該類的onReceive方法中回調
2、注冊廣播registerReceiver(BroadcastReceiver,IntentFilter);
3、發送廣播sendBroadcast(Intent);
此demo是為了驗證已經被覆蓋的Activity在接收到廣播時能否自己更新UI,下面是具體代碼:
第一步,創建MainActivity,并初始化廣播接收器BroadcastReceiver、注冊廣播
public class MainActivity extends AppCompatActivity { private TextView tipTv; public static final String ACTION_NAME = "TAG_MAIN"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tipTv = (TextView) findViewById(R.id.tipTv); findViewById(R.id.gotoTv).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivityForResult(intent, 100); tipTv.setText("等待接收廣播。。。"); } }); //注冊廣播 registerBoradcastReceiver(); } //廣播接收器 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { /** * 廣播接收器,接收到廣播的回調方法 * @param context * @param intent */ @Override public void onReceive(Context context, Intent intent) { Log.d("myp", "=== broadcast callback ==="); String action = intent.getAction(); if (action.equals(ACTION_NAME)) { //當接收到廣播時,Toast會在最上層的Activity中提示, Toast.makeText(MainActivity.this, "broadcast callback", Toast.LENGTH_SHORT).show(); String result = intent.getStringExtra("yaner"); tipTv.setText(result); //當接收到廣播時,Dialog會在接收到廣播的界面提示,并且會隨著該界面中的業務邏輯隱藏, // 由此可見,當Activity備覆蓋式,如果又出發該Activity業務邏輯的操作,會在該Activity中正常執行 initDialog(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { if (dialog != null && dialog.isShowing()) dialog.dismiss(); } }, 3 * 1000); } } }; Dialog dialog; /** * 初始化彈出框 */ private void initDialog() { dialog = new Dialog(this); dialog.setContentView(R.layout.view_dialog); dialog.show(); } /** * 注冊廣播 */ public void registerBoradcastReceiver() { IntentFilter filer = new IntentFilter();//篩選條件 filer.addAction(ACTION_NAME);//設置要注冊的廣播的標簽 //注冊廣播 registerReceiver(mBroadcastReceiver, filer); Log.d("myp", "=== broadcast regist ==="); } }
第二步,創建SecondActivity,并SecondActivity里實現觸發 能發送廣播到
MainActivity里的廣播的事件
public class SecondActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); findViewById(R.id.brodcastBtn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent mIntent = new Intent(MainActivity.ACTION_NAME); mIntent.putExtra("yaner", "接收廣播成功!!!");//接收到廣播時,攜帶的數據 //發送廣播 sendBroadcast(mIntent); Log.d("myp", "=== broadcast send ==="); } }); } }
xml布局文件比較簡單,就不給出了,運行效果:
1、點擊按鈕后,Toast提示在SecondActivity里直接提示
2、點擊按鈕后,在3秒內返回MainActivity,Dialog正常顯示,3秒過后消失
3、點擊按鈕后,在3秒后返回MainActivity,Dialog已經消失
結論:被覆蓋的Activity在接收到廣播時能自己能更新UI
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。