下面列出了怎么用android.support.v4.content.LocalBroadcastManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onResume() {
super.onResume();
setListViewPositionFromPositionsCache();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(newBroadcastReceiver,
new IntentFilter(AppEventAction.NEW_MSG_BROADCAST));
// setActionBarTabCount(newMsgTipBar.getValues().size());
getNewMsgTipBar().setOnChangeListener(new TopTipsView.OnChangeListener() {
@Override
public void onChange(int count) {
// ((MainTimeLineActivity) getActivity()).setMentionsWeiboCount(count);
// setActionBarTabCount(count);
}
});
checkUnreadInfo();
}
@Override
protected void onReset() {
super.onReset();
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(changeReceiver);
changeReceiver = null;
// stop loader
onStopLoading();
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor = null;
}
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// Saving reg id to shared preferences
storeRegIdInPref(refreshedToken);
// sending reg id to your server
sendRegistrationToServer(refreshedToken);
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(Constants.REGISTRATION_COMPLETE);
registrationComplete.putExtra("token", refreshedToken);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// Saving reg id to shared preferences
storeRegIdInPref(refreshedToken);
// sending reg id to your server
sendRegistrationToServer(refreshedToken);
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(REGISTRATION_COMPLETE);
registrationComplete.putExtra("token", refreshedToken);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
final void newPluginFound(PluginInfo info, boolean persistNeedRestart) {
// 更新最新插件表
PluginTable.updatePlugin(info);
// 更新可加载插件表
insertNewPlugin(info);
// 清空插件的状态(解禁)
PluginStatusController.setStatus(info.getName(), info.getVersion(), PluginStatusController.STATUS_OK);
if (IPC.isPersistentProcess()) {
persistNeedRestart = mNeedRestart;
}
// 输出一个日志
if (LOGR) {
LogRelease.i(PLUGIN_TAG, "p.m. n p f n=" + info.getName() + " b1=" + persistNeedRestart + " b2=" + mNeedRestart);
}
// 通知本进程:通知给外部使用者
Intent intent = new Intent(RePluginConstants.ACTION_NEW_PLUGIN);
intent.putExtra(RePluginConstants.KEY_PLUGIN_INFO, info);
intent.putExtra(RePluginConstants.KEY_PERSIST_NEED_RESTART, persistNeedRestart);
intent.putExtra(RePluginConstants.KEY_SELF_NEED_RESTART, mNeedRestart);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
}
@Override
public void onResume() {
super.onResume();
setListViewPositionFromPositionsCache();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(newBroadcastReceiver,
new IntentFilter(AppEventAction.NEW_MSG_BROADCAST));
// setActionBarTabCount(newMsgTipBar.getValues().size());
getNewMsgTipBar().setOnChangeListener(new TopTipsView.OnChangeListener() {
@Override
public void onChange(int count) {
// ((MainTimeLineActivity) getActivity()).setMentionsCommentCount(count);
// setActionBarTabCount(count);
}
});
checkUnreadInfo();
}
@Override
public void didEnterRegion(Region region) {
RegionName regName = RegionName.parseString(region.getUniqueId());
if (regName.isApplicationRegion()) {
Log.d(Constants.TAG, "didEnterRegion " + region);
if (regName.getEventType() == ActionBeacon.EventType.EVENT_NEAR_YOU) {
try {
mBeaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
Log.e(Constants.TAG, "Error start ranging region: " + regName, e);
}
}
if (regName.getEventType() == ActionBeacon.EventType.EVENT_ENTERS_REGION) {
Intent intent = new Intent();
intent.setAction(Constants.NOTIFY_BEACON_ENTERS_REGION);
intent.putExtra("REGION", (Parcelable)region);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
}
}
public static void startService(Context context, Class<? extends ChildService> clazz) {
synchronized (monitor) {
if (sRunning) {
Intent intent = new Intent(ACTION_ADD_SERVICE);
intent.putExtra(EXTRA_SERVICE_CLASS, clazz);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
} else if (!sServiceMap.containsKey(clazz)) {
ChildService instance;
try {
instance = clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
sServiceMap.put(clazz, instance);
if (!sCreated) context.startService(new Intent(context, BathService.class));
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mIsMovie = getArguments().getBoolean(MOVIE, false);
mType = getArguments().getInt(TYPE, FileSource.FILE);
if (mType == FileSource.UPNP) {
contentListAdapter = new ArrayAdapter<ContentItem>(getActivity(),
android.R.layout.simple_list_item_1);
}
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver, new IntentFilter("onBackPressed"));
}
@Override
public void didExitRegion(Region region) {
RegionName regName = RegionName.parseString(region.getUniqueId());
if (regName.isApplicationRegion()) {
Log.d(Constants.TAG, "didExitRegion " + region);
if (regName.getEventType() == ActionBeacon.EventType.EVENT_NEAR_YOU) {
try {
mBeaconManager.stopRangingBeaconsInRegion(region);
// set "far" proximity
mDataManager.updateBeaconDistance(regName.getBeaconId(), 99);
} catch (RemoteException e) {
Log.e(Constants.TAG, "Error stop ranging region: " + regName, e);
}
}
if (regName.getEventType() == ActionBeacon.EventType.EVENT_LEAVES_REGION) {
Intent intent = new Intent();
intent.setAction(Constants.NOTIFY_BEACON_LEAVES_REGION);
intent.putExtra("REGION", (Parcelable) region);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent); }
}
}
@Override
public void onCompleted(Request request, int progress, int size) {
if (request == null) return;
if (mComicChapterDBHelper == null) {
mComicChapterDBHelper = ComicChapterDBHelper.getInstance(HHApplication.getInstance());
}
ComicChapter comicChapter = mComicChapterDBHelper.findByChapterId(request.getChid());
if (comicChapter == null) return;
comicChapter.setDownloadPosition(progress);
comicChapter.setPageCount(size);
comicChapter.setDownloadStatus(Constants.DOWNLOAD_FINISHED);
mComicChapterDBHelper.update(comicChapter);
if (mNotificationUtil == null) {
mNotificationUtil = NotificationUtil.getInstance(HHApplication.getInstance());
}
mNotificationUtil.finishedNotification(comicChapter);
//发送本地广播
Intent intent = new Intent(DownloadManagerService.ACTION_RECEIVER);
intent.putExtra("comicChapter", comicChapter);
intent.putExtra("state", Constants.DOWNLOAD_FINISHED);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
/**
* Calculates the speed from current location object.
* If location has speed, this one will be used else the speed will be calculated from current
* and last position.
*/
private void calculateSpeed(Location location){
double newTime= System.currentTimeMillis();
double newLat = location.getLatitude();
double newLon = location.getLongitude();
if(location.hasSpeed()){
Log.i(LOG_TAG, "Location has speed");
speed = location.getSpeed();
} else {
Log.i(LOG_TAG, "Location has no speed");
double distance = calculationBydistance(newLat,newLon,oldLat,oldLon);
double timeDifferent = (newTime - curTime) / 1000; // seconds
speed = (float) (distance / timeDifferent);
curTime = newTime;
oldLat = newLat;
oldLon = newLon;
}
Intent localIntent = new Intent(BROADCAST_ACTION_SPEED_CHANGED)
// Add new step count
.putExtra(EXTENDED_DATA_CURRENT_SPEED, speed);
// Broadcasts the Intent to receivers in this app.
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
Log.i(LOG_TAG, "New speed is " + speed + "m/sec " + speed * 3.6 + "km/h" );
}
/** onResume event, should be called from the main activity */
public void onResume() {
this._isResumed = true;
// Check in preferences if there is a token
String token = this.sharedPreferences.getString(UserApp.SESSION_TOKEN_KEY, null);
if (token != null) {
// Use the fixed token with the API
setToken(token);
user = deserializeUser();
this.callCallbacks(true, null);
} else {
this.callCallbacks(false, null);
}
LocalBroadcastManager.getInstance(this.activity).registerReceiver(this.loginReceiver, new IntentFilter(UserApp.ACTION_SESSION_LOGIN));
LocalBroadcastManager.getInstance(this.activity).registerReceiver(logoutReceiver, new IntentFilter(UserApp.ACTION_SESSION_LOGOUT));
LocalBroadcastManager.getInstance(this.activity).registerReceiver(userUpdateReceiver, new IntentFilter(UserApp.ACTION_USER_UPDATE));
}
private void showSuccessfulNotification(final WeiboSendTask task) {
Notification.Builder builder = new Notification.Builder(SendRepostService.this)
.setTicker(getString(R.string.send_successfully))
.setContentTitle(getString(R.string.send_successfully)).setOnlyAlertOnce(true).setAutoCancel(true)
.setSmallIcon(R.drawable.send_successfully).setOngoing(false);
Notification notification = builder.getNotification();
final int id = tasksNotifications.get(task);
NotificationUtility.show(notification, id);
handler.postDelayed(new Runnable() {
@Override
public void run() {
NotificationUtility.cancel(id);
stopServiceIfTasksAreEnd(task);
}
}, 3000);
LocalBroadcastManager.getInstance(SendRepostService.this).sendBroadcast(
new Intent(AppEventAction.buildSendRepostSuccessfullyAction(oriMsg)));
}
@Override
public void onMessageReceived(Message message) {
Log.i(TAG, "onMessageReceived: ");
// direct messages carrying a Device name represent device handshakes
if (message.getContent().get("device_name") != null) {
Peer peer = new Peer(message.getSenderId(),
(String) message.getContent().get("device_name"));
peer.setNearby(true);
peersAdapter.addPeer(peer);
// any other direct bridgefyFile should be treated as such
} else {
Log.i(TAG, "onMessageReceived: sending broadcast to "+message.getSenderId());
LocalBroadcastManager.getInstance(getBaseContext()).sendBroadcast(
new Intent(message.getSenderId())
.putExtra(INTENT_EXTRA_MSG, message));
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//startService(new Intent(this, FileListenerService.class));
setContentView(R.layout.activity_download_record);
IntentFilter mFilter = new IntentFilter();
mFilter.addAction("download_progress_refresh");
LocalBroadcastManager.getInstance(this).registerReceiver(downloadStatus, mFilter);
ButterKnife.bind(this);
initData();
initView();
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
showNetSpeed();
}
}, 0, 1000);
}
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(LocalBroadcastConstants.INTENT_HISTORY_CHANGED);
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, intentFilter);
}
/**
* Prepares for flashing process.
* <p/>
* <p>>Unregisters DFU receiver, sets activity state to the find device state,
* registers callbacks requisite for flashing and starts flashing.</p>
*/
protected void initiateFlashing() {
if(dfuResultReceiver != null) {
LocalBroadcastManager.getInstance(MBApp.getApp()).unregisterReceiver(dfuResultReceiver);
dfuResultReceiver = null;
}
setActivityState(FlashActivityState.FLASH_STATE_FIND_DEVICE);
registerCallbacksForFlashing();
startFlashing();
}
@Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
prefs = this.getSharedPreferences(AimsicdService.SHARED_PREFERENCES_BASENAME, 0);
prefs.registerOnSharedPreferenceChangeListener(this);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter(updateOpenCellIDMarkers));
if (!mBound) {
// Bind to LocalService
Intent intent = new Intent(this, AimsicdService.class);
bindService(intent, mConnection, BIND_AUTO_CREATE);
}
loadPreferences();
loadEntries();
if (mCompassOverlay != null) {
mCompassOverlay.enableCompass();
}
if (mMyLocationOverlay != null) {
mMyLocationOverlay.enableMyLocation();
}
}
@Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(launcherBroadcastReceiver);
if (isBoundToConnectionService) {
unbindService();
}
super.onDestroy();
}
@Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager
.getInstance(this)
.unregisterReceiver(sdkBroadcastReceiver);
}
/**
* Function to play next page
*/
public synchronized void nextPage() {
pageNumber++;
if(pageNumber == 605 ){
LocalBroadcastManager.getInstance(this)
.sendBroadcast(new Intent(AppConstants.MediaPlayer.INTENT)
.putExtra(AppConstants.MediaPlayer.OTHER_PAGE, 2));
pageNumber = 1 ;
}
prepareVersesToPlay();
}
@Override
public void onResume() {
super.onResume();
mWallet = WalletManager.getSelectedWallet();
onAccountUpdated();
AccountUpdater.setInterval(TronWalletApplication.ACCOUNT_UPDATE_FOREGROUND_INTERVAL, true);
LocalBroadcastManager.getInstance(getContext()).registerReceiver(mAccountUpdatedBroadcastReceiver, new IntentFilter(AccountUpdater.ACCOUNT_UPDATED));
LocalBroadcastManager.getInstance(getContext()).registerReceiver(mPricesUpdatedBroadcastReceiver, new IntentFilter(PriceUpdater.PRICES_UPDATED));
}
protected void sendBroadcastMessage(String type, String key, boolean b) {
Intent intent = new Intent(type);
intent.putExtra(key, b);
Log.e(TAG, "Send message: " + type + ", " + key + ", " + String.valueOf(b));
LocalBroadcastManager.getInstance(main_context).sendBroadcast(intent);
}
@Override
public void onDestroy() {
weMessage.get().getMessageManager().unhookCallbacks(callbackUuid);
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(createChatBroadcastReceiver);
if (isBoundToConnectionService){
unbindService();
}
super.onDestroy();
}
@Override
public void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(LocalBroadcastConstants.INTENT_NAME_ROOM_CHANGED);
intentFilter.addAction(LocalBroadcastConstants.INTENT_BRAND_MODEL_CHANGED);
intentFilter.addAction(LocalBroadcastConstants.INTENT_CHANNEL_DETAILS_CHANGED);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver, intentFilter);
}
public void unregisterBroadcastReceiver() {
if (mBroadcastReceiver != null) {
LocalBroadcastManager.getInstance(getApplicationContext())
.unregisterReceiver(mBroadcastReceiver);
mBroadcastReceiver = null;
}
setReloadListener(null);
setRefreshListener(null);
}
@Override
public void onDestroy() {
Log.e(TAG, "on Destroy");
LocalBroadcastManager.getInstance(this).unregisterReceiver(mFoundResourceReceiver);
resetGlobals();
super.onDestroy();
}
@Override
public void onStart(Request request) {
ComicChapter comicChapter = mComicChapterDBHelper.findByChapterId(request.getChid());
if (comicChapter == null) return;
comicChapter.setDownloadStatus(Constants.DOWNLOAD_START);
mComicChapterDBHelper.update(comicChapter);
mNotificationUtil.showNotification(DownloadManagerService.this, comicChapter);
//发送本地广播
Intent intent = new Intent(DownloadManagerService.ACTION_RECEIVER);
intent.putExtra("comicChapter", comicChapter);
intent.putExtra("state", Constants.DOWNLOAD_START);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
@Override
public void onDestroy() {
weMessage.get().getMessageManager().unhookCallbacks(callbackUuid);
LocalBroadcastManager.getInstance(this).unregisterReceiver(contactSelectBroadcastReceiver);
if (isBoundToConnectionService){
unbindService();
}
super.onDestroy();
}