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();
}
}
點擊運行 結果:

自己動手試一試,你也可以!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/229223.html
標籤:其他
上一篇:Android 讀寫權限例外處理
下一篇:Android 開發兩年面試總結
