專案參考:第二十一讲:Broadcast Receiver 使用入门
AndroidManifest:
//插入在/activity之後
/activity
/activity
//設定receiver存在的class
receiver android:name="recive"
intent-filter
//設定receiver存在的class中的 broadcast action 可以多重設定
action android:name="show_toast" /
action android:name="show_dialog" /
/intent-filter
/receiver
/application
//以及/application之前
//以及/application之前
//左右箭頭 < >自己記得加 註解記得拿掉~
主程式MainActivity.java :
public class MainActivity extends Activity {
private Button toast;
private Button Adialog;
private String toastss = "toast";
private String dialogss = "dialog";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toast = (Button)this.findViewById(R.id.bt1);
Adialog = (Button)this.findViewById(R.id.bt2);
toast.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent("toast");
intent.setAction("show_toast");
intent.putExtra("hello",toastss);
sendBroadcast(intent);
}
});
Adialog.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent("toast");
intent.setAction("show_dialog");
intent.putExtra("hello",dialogss);
sendBroadcast(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
副程式recive.java :
public class recive extends BroadcastReceiver {
private Toast toast;
private AlertDialog show;
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("show_toast")){
String toastv = intent.getExtras().getString("hello");
Log.e("show_toast", toastv+"Say Hello to Yaoyao !!!!!");
//toast = Toast.makeText(getApplicationContext(),toastv,Toast.LENGTH_LONG);
//toast.setDuration(Toast.LENGTH_LONG);// show的時間長短正規寫法 LONG長 SHORT短
// 3個屬性分別為Gravity,x座標,y座標
//toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP,0,100);
//toast.show();
}
if(intent.getAction().equals("show_dialog")){
String dialog = intent.getExtras().getString("hello");
Log.e("show_dialog", dialog+"Say Hello to Yaoyao !!!!!");
//show = new AlertDialog.Builder(this).setTitle(dialog)
//.setMessage("您好")
//.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//public void onClick(DialogInterface dialog, int which) {
//}
//}).show();
}
}
}
執行結果:
後記:本來想用Broadcast 來啟動開啟toast 跟 alertdialog 但是
我另外一個副程式 是 public class recive extends BroadcastReceiver
不是activity所以不能設定view
不過我會補完 這是下一個目標~
沒有留言:
張貼留言