我的活动是否"活跃"?



我的应用程序仅包含一个活动(启动模式= singletask),其中包含一个ViewPager。在该应用程序中,用户通过警报管理器安排警报。当触发这些警报时,广播接收器将在状态栏中创建通知(应用程序是否打开)。

每当发出通知并且活动位于前景时,我想在活动中更新活动中的循环系统。如果该活动在背景中是否在背景中(根本不存在),则无需将其称为正面或打开它只是为了更新RecyClerview。

如何在打电话之前检查我的活动是否存在,说" myActivity.updatemyrecyclerview()"?(我对如何检查是否在前景中有一个想法,我认为这不是问题。)

您可以使用广播接收器进行活动。您可以发送广播,如果您的活动是"活着的",并且已注册以接收广播,则可以从那里触发RecyClerview更新。

当您创建这样的通知时,发送广播

Intent intent = new Intent("key_to_identify_the_broadcast");
Bundle bundle = new Bundle();
bundle.putBoolean("updateRecyclerView",true);
intent.putExtra("bundle_key_for_intent", bundle);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

,在您要接收此意图的活动中,您可以使用广播接收器

  private final BroadcastReceiver mHandleMessageReceiver = new 
  BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {
    Bundle bundle = 
        intent.getExtras().getBundle("bundle_key_for_intent");
        if(bundle!=null){
            boolean shouldRefresh = bundle.getBoolean("updateRecyclerView");
            if(shouldRefresh){
               //Refresh your recyclerView
            }
        }
 }
};

您需要注册并取消接收器的工作

在您的颜色方法中,您可以注册此接收器以接收广播

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    IntentFilter filter = new IntentFilter("key_to_identify_the_broadcast");
    LocalBroadcastManager.getInstance(this)
    .registerReceiver(mHandleMessageReceiver,filter);
}

您还需要在活动暂停之前取消注册

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    try {
     LocalBroadcastManager.getInstance(this)
         .unregisterReceiver(mHandleMessageReceiver);
  } catch (Exception e) {
    Log.e("UnRegister Error", "> " + e.getMessage());
  }
}

最新更新