下面列出了android.support.v4.content.LocalBroadcastManager#getInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test(timeout = 5000)
public void testStop() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
BroadcastReceiver serviceBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
int action = bundle.getInt("action");
if (action == LocationServiceImpl.MSG_ON_SERVICE_STOPPED) {
latch.countDown();
}
}
};
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(InstrumentationRegistry.getTargetContext());
lbm.registerReceiver(serviceBroadcastReceiver, new IntentFilter(LocationServiceImpl.ACTION_BROADCAST));
proxy.start();
proxy.stop();
latch.await();
lbm.unregisterReceiver(serviceBroadcastReceiver);
}
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter();
filter.addAction(MyTaskService.ACTION_DONE);
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
manager.registerReceiver(mReceiver, filter);
}
@Override
public void onCreate() {
super.onCreate();
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Chat Service started");
}
mResponder = new ElizaResponder();
mBroadcastManager = LocalBroadcastManager.getInstance(this);
processIncoming(null);
}
/**
* Constructs a SessionTracker to track the Session object passed in.
* If the Session is null, then it will track the active Session instead.
*
* @param context the context object.
* @param callback the callback to use whenever the Session's state changes
* @param session the Session object to track
* @param startTracking whether to start tracking the Session right away
*/
public SessionTracker(Context context, Session.StatusCallback callback, Session session, boolean startTracking) {
this.callback = new CallbackWrapper(callback);
this.session = session;
this.receiver = new ActiveSessionBroadcastReceiver();
this.broadcastManager = LocalBroadcastManager.getInstance(context);
if (startTracking) {
startTracking();
}
}
/**
* The constructor.
*/
public AccessTokenTracker() {
Validate.sdkInitialized();
this.receiver = new CurrentAccessTokenBroadcastReceiver();
this.broadcastManager = LocalBroadcastManager.getInstance(
FacebookSdk.getApplicationContext());
startTracking();
}
@Override
public void onPause() {
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());
manager.unregisterReceiver(mOnProfileInfoUploadListener);
manager.unregisterReceiver(mOnProfileInfoUpdateListener);
super.onPause();
}
/**
* Creates a new UiLifecycleHelper.
*
* @param activity the Activity associated with the helper. If calling from a Fragment,
* use {@link android.support.v4.app.Fragment#getActivity()}
* @param callback the callback for Session status changes, can be null
*/
public UiLifecycleHelper(Activity activity, Session.StatusCallback callback) {
if (activity == null) {
throw new IllegalArgumentException(ACTIVITY_NULL_MESSAGE);
}
this.activity = activity;
this.callback = callback;
this.receiver = new ActiveSessionBroadcastReceiver();
this.broadcastManager = LocalBroadcastManager.getInstance(activity);
}
/**
* Constructs a SessionTracker to track the Session object passed in.
* If the Session is null, then it will track the active Session instead.
*
* @param context the context object.
* @param callback the callback to use whenever the Session's state changes
* @param session the Session object to track
* @param startTracking whether to start tracking the Session right away
*/
public SessionTracker(Context context, Session.StatusCallback callback, Session session, boolean startTracking) {
this.callback = new CallbackWrapper(callback);
this.session = session;
this.receiver = new ActiveSessionBroadcastReceiver();
this.broadcastManager = LocalBroadcastManager.getInstance(context);
if (startTracking) {
startTracking();
}
}
/**
* Creates a new UiLifecycleHelper.
*
* @param activity the Activity associated with the helper. If calling from a Fragment,
* use {@link android.support.v4.app.Fragment#getActivity()}
* @param callback the callback for Session status changes, can be null
*/
public UiLifecycleHelper(Activity activity, Session.StatusCallback callback) {
if (activity == null) {
throw new IllegalArgumentException(ACTIVITY_NULL_MESSAGE);
}
this.activity = activity;
this.callback = callback;
this.receiver = new ActiveSessionBroadcastReceiver();
this.broadcastManager = LocalBroadcastManager.getInstance(activity);
// Make sure we've loaded default settings if we haven't already.
Settings.loadDefaultsFromMetadataIfNeeded(activity);
}
@Override
public void onResume() {
super.onResume();
// Register the broadcast receiver.
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(receiver, filter);
}
/**
* Creates a new UiLifecycleHelper.
*
* @param activity the Activity associated with the helper. If calling from a Fragment,
* use {@link android.support.v4.app.Fragment#getActivity()}
* @param callback the callback for Session status changes, can be null
*/
public UiLifecycleHelper(Activity activity, Session.StatusCallback callback) {
if (activity == null) {
throw new IllegalArgumentException(ACTIVITY_NULL_MESSAGE);
}
this.activity = activity;
this.callback = callback;
this.receiver = new ActiveSessionBroadcastReceiver();
this.broadcastManager = LocalBroadcastManager.getInstance(activity);
}
private void buildBroadcast() {
if (!isSendBroadcast) {
return;
}
localBroadcastManager = LocalBroadcastManager.getInstance(this);
localIntent = new Intent(ACTION);
}
/**
* Constructs a SessionTracker to track the Session object passed in.
* If the Session is null, then it will track the active Session instead.
*
* @param context the context object.
* @param callback the callback to use whenever the Session's state changes
* @param session the Session object to track
* @param startTracking whether to start tracking the Session right away
*/
public SessionTracker(Context context, Session.StatusCallback callback, Session session, boolean startTracking) {
this.callback = new CallbackWrapper(callback);
this.session = session;
this.receiver = new ActiveSessionBroadcastReceiver();
this.broadcastManager = LocalBroadcastManager.getInstance(context);
if (startTracking) {
startTracking();
}
}
private void switchScreenOn(){
Intent intent = new Intent(BrowserActivity.BROADCAST_ACTION_SCREEN_ON);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(getApplicationContext());
bm.sendBroadcast(intent);
}
void initializeService() {
/**-------------定位---------------*/
locationListener = new MyLocationListener();
mLocationClient = new LocationClient(getApplicationContext()); //声明LocationClient类
mLocationClient.registerLocationListener(locationListener); //注册监听函数
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
int span = 5000;
option.setScanSpan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
option.setOpenGps(true);//可选,默认false,设置是否使用gps
option.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
option.setCoorType("bd09ll");
mLocationClient.setLocOption(option);
/**-------------周边雷达---------------*/
//实例化
radarSearchManager = RadarSearchManager.getInstance();
radarNearbyOption = new RadarNearbySearchOption();
radarNearbyOption.pageCapacity(50);
radarNearbyOption.sortType(RadarNearbySearchSortType.distance_from_far_to_near);
radarNearbyOption.pageNum(0);
radarNearbyOption.radius(5000);
/**-------------鹰眼轨迹--------------*/
//实例化轨迹服务客户端
lbsTraceClient = new LBSTraceClient(getApplicationContext());
// 设置定位模式
lbsTraceClient.setLocationMode(LocationMode.High_Accuracy);
//位置采集周期
int gatherInterval = 5;
//打包周期
int packInterval = 30;
//设置位置采集和打包周期
lbsTraceClient.setInterval(gatherInterval, packInterval);
//轨迹服务类型(0 : 不上传位置数据,也不接收报警信息; 1 : 不上传位置数据,但接收报警信息;2 : 上传位置数据,且接收报警信息)
traceType = 2;
//轨迹监听器
myOnTrackListener = new MyOnTrackListener();
lbsTraceClient.setOnTrackListener(myOnTrackListener);
/**-------------地理围栏---------------*/
//OnTrackListener接口的实现类,实现轨迹监听器回调方法
//轨迹服务中地理围栏监听器
myOnGeoFenceListener = new MyOnGeoFenceListener();
//Entity监听器
myOnEntityListener = new MyOnEntityListener();
lbsTraceClient.setOnGeoFenceListener(myOnGeoFenceListener);
lbsTraceClient.setOnEntityListener(myOnEntityListener);
/**--------------广播------------------*/
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
myServiceReceiver = new myServiceReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("cc.bitlight.broadcast.service.start");
intentFilter.addAction("cc.bitlight.broadcast.service.stop");
intentFilter.addAction("cc.bitlight.broadcast.track.queryhistorytrack");
intentFilter.addAction("cc.bitlight.broadcast.geofence.query");
intentFilter.addAction("cc.bitlight.broadcast.mytemp");
mLocalBroadcastManager.registerReceiver(myServiceReceiver, intentFilter);
}
private void registPayResultBroadcast() {
mBroadcastManager = LocalBroadcastManager.getInstance(mContext.getApplicationContext());
IntentFilter filter = new IntentFilter(WECHAT_PAY_RESULT_ACTION);
mBroadcastManager.registerReceiver(mReceiver, filter);
}
/**
* Creates Box2D world, reads layout definitions for the given level, and initializes the game
* to the starting state.
*/
public void resetForLevel(Context context, int level) {
Vector2 gravity = new Vector2(0.0f, -1.0f);
boolean doSleep = true;
world = new World(gravity, doSleep);
world.setContactListener(this);
gameState.statusMgr = LocalBroadcastManager.getInstance(context);
Intent scoreIntent = new Intent(ArcadeCommon.ACTION_STATUS)
.putExtra(ArcadeCommon.STATUS_RESET_SCORE, true)
.putExtra(ArcadeCommon.STATUS_LEVEL, level)
.putExtra(ArcadeCommon.STATUS_LIVES, gameState.totalBalls - gameState.ballNumber);
gameState.statusMgr.sendBroadcast(scoreIntent);
layout = FieldLayout.layoutForLevel(level, world);
world.setGravity(new Vector2(0.0f, -layout.getGravity()));
ballsAtTargets = new HashSet<Body>();
scheduledActions = new PriorityQueue<ScheduledAction>();
gameTime = 0;
// Map bodies and IDs to FieldElements, and get elements on whom tick() has to be called.
bodyToFieldElement = new HashMap<Body, FieldElement>();
fieldElementsByID = new HashMap<String, FieldElement>();
List<FieldElement> tickElements = new ArrayList<FieldElement>();
for(FieldElement element : layout.getFieldElements()) {
if (element.getElementId()!=null) {
fieldElementsByID.put(element.getElementId(), element);
}
for(Body body : element.getBodies()) {
bodyToFieldElement.put(body, element);
}
if (element.shouldCallTick()) {
tickElements.add(element);
}
}
fieldElementsToTick = tickElements.toArray(new FieldElement[0]);
fieldElementsArray = layout.getFieldElements().toArray(new FieldElement[0]);
delegate = null;
String delegateClass = layout.getDelegateClassName();
if (delegateClass!=null) {
if (delegateClass.indexOf('.')==-1) {
delegateClass = "com.homescreenarcade.pinball.fields." + delegateClass;
}
try {
delegate = (Delegate)Class.forName(delegateClass).newInstance();
}
catch(Exception ex) {
throw new RuntimeException(ex);
}
}
else {
// Use no-op delegate if no class specified, so that field.getDelegate() is non-null.
delegate = new BaseFieldDelegate();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new LoggingExceptionHandler());
setContentView(R.layout.activity_main);
// App bar
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
int stackTopIndex = getSupportFragmentManager().getBackStackEntryCount() - 1;
if (stackTopIndex >= 0) {
toolbar.setTitle(getSupportFragmentManager().getBackStackEntryAt(stackTopIndex).getName());
} else {
toolbar.setTitle(R.string.app_name);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Disable fullscreen mode
getSupportActionBar().show();
getWindow().getDecorView().setSystemUiVisibility(0);
}
}
});
waltDevice = WaltDevice.getInstance(this);
// Create front page fragment
FrontPageFragment frontPageFragment = new FrontPageFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, frontPageFragment);
transaction.commit();
logger = SimpleLogger.getInstance(this);
broadcastManager = LocalBroadcastManager.getInstance(this);
// Add basic version and device info to the log
logger.log(String.format("WALT v%s (versionCode=%d)",
BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE));
logger.log("WALT protocol version " + WaltDevice.PROTOCOL_VERSION);
logger.log("DEVICE INFO:");
logger.log(" " + Build.FINGERPRINT);
logger.log(" Build.SDK_INT=" + Build.VERSION.SDK_INT);
logger.log(" os.version=" + System.getProperty("os.version"));
// Set volume buttons to control media volume
setVolumeControlStream(AudioManager.STREAM_MUSIC);
requestSystraceWritePermission();
// Allow network operations on the main thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
private void unregisterLocalBroadcastManager() {
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(mApplicationContext);
manager.unregisterReceiver(mBroadcastReceiver);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBroadcastMgr = LocalBroadcastManager
.getInstance(getApplicationContext());
setContentView(R.layout.main);
}