Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 開發入門 >> 簡單的廣播發送與接收

簡單的廣播發送與接收

編輯:開發入門

發送端:
public class MainActivity extends Activity { //先在布局文件main.XML中定義一個Button
/*
*
* <Button
* android:layout_width="fill_parent"
* android:layout_height="wrap_content"
* android:text="@string/button_send"
* android:id="@+id/send_broadcast_button"
* />
*
*/


private Button send_broadcast_button; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentVIEw(R.layout.main);
send_broadcast_button = (Button) this.findVIEwById(R.id.send_broadcast_button);
send_broadcast_button.setOnClickListener(new SendBroadcast());
}
private class SendBroadcast implements VIEw.OnClickListener { @Override
public void onClick(VIEw v) {

Intent intent = new Intent();
intent.setAction("cn.abel.action.broadcast");

//要發送的內容
intent.putExtra("author", "Abel");

//發送 一個無序廣播
MainActivity.this.sendBroadcast(intent);
}

}
}

接收端:

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentVIEw(R.layout.main);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("cn.abel.action.broadcast");
this.registerReceiver(new MyBroadcastReciver(), intentFilter);
}
private class MyBroadcastReciver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("cn.abel.action.broadcast")) {
String author = intent.getStringExtra("author");

//在控制台顯示接收到的廣播內容
System.out.println("author==>"+author);

//在android端顯示接收到的廣播內容
Toast.makeText(MainActivity.this, author, 1).show();

//在結束時可取消廣播
//MainActivity.this.unregisterReceiver(this);
}
}

}
}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved