Android學習之發送及接收廣播


1、使用標准廣播

1.1 定義廣播接收器

public class MyBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
String string=arg1.getStringExtra("data");
Toast.makeText(arg0, "received:"+string, Toast.LENGTH_SHORT).show();

}

}

1.2 修改AndriodManifest.xml,注冊廣播接收器

<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.broadcastreceiverdemo.BROADCAST"></action>
</intent-filter>
</receiver>

1.3 補充MainActivity代碼

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button)findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent("com.example.broadcastreceiverdemo.BROADCAST");
intent.putExtra("data", "hello");
sendBroadcast(intent);
}
});
}

}

2、使用本地廣播

本地廣播只能夠在應用程序的內部進行傳遞,並且廣播接收器也只能接收來自本應用程序發出的廣播,這樣就提高了數據傳播的安全性。但本地廣播無法通過靜態注冊的方式來接收。本地廣播使用LocalBroadcastManager來對廣播進行管理,並提供了發送廣播及注冊廣播接收器的方法

//定義廣播接收器

public class LocalReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
String string=arg1.getStringExtra("data");
Toast.makeText(arg0, "received:"+string, Toast.LENGTH_SHORT).show();

}

}

//MainActivity

public class MainActivity extends Activity {

private IntentFilter intentFilter;
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

intentFilter=new IntentFilter("com.example.localbroadcastdemo.LOCALBROADCAST");
localReceiver=new LocalReceiver();
//獲取實例
localBroadcastManager=LocalBroadcastManager.getInstance(this);
//注冊本地廣播監聽器
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
Button button=(Button)findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent("com.example.localbroadcastdemo.LOCALBROADCAST");
intent.putExtra("data", "hello");
//發送本地廣播
localBroadcastManager.sendBroadcast(intent);
}
});
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
localBroadcastManager.unregisterReceiver(localReceiver);
}


@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;
}

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM