Android - BroadcastReceiver 廣播

南花_發表於2020-12-02

Android - 廣播

靜態:

編寫主類 sendBroadcast(intent);
編寫接收類繼承 BroadcastReceiver 重寫onReceive方法
寫AndroidManifest.xml

主類:

public class MainActivity extends Activity {
	Button button_send;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        button_send = (Button) findViewById(R.id.button_send);
        button_send.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
					Intent intent = new Intent();
					intent.setAction("FM895");
					sendBroadcast(intent);
			}
		});
    }
}

接收類

public class MyReceive extends BroadcastReceiver {
	@Override
	public void onReceive(Context arg0, Intent arg1) {
		Log.e("__________","OK");
	}
}

AndroidManifest.xml

<receiver android:name="com.example.venbo.MyReceive">
   <intent-filter>
       <action android:name="FM895">
       </action>
   </intent-filter>
</receiver>

點選按鈕檢視結果:
在這裡插入圖片描述

動態:

編寫主類:例項化IntentFilter物件,新增.addAction,註冊廣播接收
編寫按鈕點選事件:例項化Intent,設定.setAction,.putExtra放內容,sendBroadcast傳送
編寫接收類,觸發Toast提示;

Java主類:

public class MainActivity extends Activity {

	Button button_send;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        		//例項化IntentFilter物件
                 IntentFilter filter = new IntentFilter();
                 filter.addAction("FM895");
                 MyReceive myReceive = new MyReceive();
                 //註冊廣播接收
                registerReceiver(myReceive,filter);
        
        button_send = (Button) findViewById(R.id.button_send);
        button_send.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
					Intent intent = new Intent();
					intent.setAction("FM895");
					intent.putExtra("information","雷霆嘎巴!");
					sendBroadcast(intent);
			}
		});
    }
}

接收類:

public class MyReceive extends BroadcastReceiver {
	@Override
	public void onReceive(Context arg0, Intent arg1) {
		Toast t = Toast.makeText(arg0,"動態廣播:"+ arg1.getStringExtra("information"), Toast.LENGTH_SHORT);
		t.setGravity(Gravity.TOP,0,0);
		t.show();
	}
}

點選執行 結果:
在這裡插入圖片描述
自己動手試一試,你也可以!

相關文章