標籤:android廣播和介面互動回調訊息處理
/**
* Upload 檔案上傳廣播接收器
*
* @author jiangbing
* @time 2015-7-14 上午11:49:29
*/
public class FileUploadReceiver extends BroadcastReceiver {
private static final String TAG = "FileUploadReceiver";
private static final String registerName = "com.http.server.web.action.broadcast";
private static Map<Context, FileUploadReceiver> mReceiverMap = new HashMap<Context, FileUploadReceiver>();
OnFileUploadListener mFileUploadListener;
public FileUploadReceiver(OnFileUploadListener fileUploadListener) {
this.mFileUploadListener = fileUploadListener;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(registerName)) {
String fileName = intent.getStringExtra("fileName");
mFileUploadListener.fileUpload(fileName);
// 在控制台顯示接收到的廣播內容
System.out.println("author==>" + fileName);
// 在android端顯示接收到的廣播內容
Toast.makeText(context, fileName, Toast.LENGTH_SHORT).show();
}
}
/**
* 檔案上傳註冊廣播
*
* @param context
* @param fileUploadListener
* @author jiangbing
* @time 2015-7-14 下午12:12:12
*/
public static void register(Context context, OnFileUploadListener fileUploadListener) {
if (mReceiverMap.containsKey(context)) {
return;
}
FileUploadReceiver receiver = new FileUploadReceiver(fileUploadListener);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(registerName);
context.registerReceiver(receiver, intentFilter);
mReceiverMap.put(context, receiver);
}
/**
* 登出檔案上傳廣播
*
* @param context
* @author jiangbing
* @time 2015-7-14 下午12:13:37
*/
public static void unregister(Context context) {
FileUploadReceiver receiver = mReceiverMap.remove(context);
if (receiver != null) {
context.unregisterReceiver(receiver);
receiver = null;
}
}
}
/-----------回調介面檔案--------------/
/**檔案上傳介面 回調接收檔案名稱
* @author jiangbing
* @time 2015-7-14 上午11:50:49
*/
public interface OnFileUploadListener {
void fileUpload(String fileName);
}
/----主介面Activity 類實現介面-------/
public class MainActivity extends Activity implements OnFileUploadListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//註冊廣播
FileUploadReceiver.register(this, this);
}
/**
* 接收pc上傳資料到服務檔案
*/
@Override
public void fileUpload(String fileName) {
if (!TextUtils.isEmpty(fileName)) {
fileList.add(fileName);
transmissionAdapter.updateUploadFileData(fileList);
updateSdCardProgress();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
//在Activity銷毀時候登出廣播訊息
FileUploadReceiver.unregister(getApplicationContext());
}
}
/-----------發送廣播-----------/
//發送 一個無序廣播
Intent intent = new Intent();
intent.setAction("com.http.server.web.action.broadcast");
//要發送的內容
intent.putExtra("fileName", fileName );
mContext.sendBroadcast(intent);
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Android廣播和介面互動回調訊息處理