我想不少人都透過 Intent 來傳送資料,並用 BroadcastReceiver 來接收該 Intent ,這是 Android 提供相當好用的一個機制。但是請注意下列兩點:
1、 Intent 是透過 Binder 來實作用來進行 inter-process commumnication,已經是和系統層面相關,所以效能上不是很好。2、任何 app 只要知道你的 intent key (字串),每個人都可以收送我們 app 所需特別 Intent ,這延伸出來的就是安全問題了。
但是有時候,我們只是想要在自己的 application (process) 內傳遞資料,若是用 BroadcastReceiver 的方法來進行,就會遇到上述所說的2個缺點。在這時候,改用新的 Android Support Library 中所提供的 LocalBroadcastManager 來傳遞資料是比較好的選擇。因為 LocalBroadcastManager 是透過 HashMap 來實作 sending/receiving intent,所以效能會比較好,而且有最好的安全性。
相關的使用方法很簡單,下列我用了一個 Intent Service 和 Activity 來作簡單的範例。
ApaulIntentService.java:
package com.apaulstudio.localbroadcast;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
public class ApaulIntentService extends IntentService{
public static final String ACTION="mycustomaction";
private static final String AUTHOR = "Apaul";
public ApaulIntentService() {
super("ApaulIntentService");
Log.d(AUTHOR,"service started");
}
@Override
protected void onHandleIntent(Intent arg0) {
Intent in=new Intent(ACTION);
Log.d(AUTHOR,"sending broadcast");
// Start to send local intent
LocalBroadcastManager.getInstance(this).sendBroadcast(in);
}
}
MyLocalBroadcastManager.java:
package com.apaulstudio.localbroadcast;
… import android.support.v4.content.LocalBroadcastManager;
public class MyLocalBroadcastActivity extends Activity implements OnClickListener{
TextView tv;
Button bt;
@Override
protected void onPause() {
super.onPause();
// Unregister the local receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
}
@Override
protected void onResume() {
super.onResume();
// Register a local receiver
IntentFilter iff= new IntentFilter(ApaulIntentService.ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, iff);
}
// Prepare a BroadcastReceiver
private BroadcastReceiver onNotice= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
tv.setText(new Date().toString());
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.tvResults);
bt= (Button)findViewById(R.id.btStart);
bt.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.btStart){
Intent i= new Intent(this, ApaulIntentService.class);
startService(i);
}
}
}
沒有留言 :
張貼留言