我想在非活动类中使用回调方法来关闭当前在活动堆栈上属于扩展活动的任何活动PacketActivity
public class PacketActivity extends AppCompatActivity {
//...
}
这是我在非活动类中的回调方法,使用对我的主要活动的静态引用来发送意图
// Sends an intent telling activities that extend PacketActivity to
// call finish()
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
if(newState == 0){
Intent intent = new Intent();
intent.putExtra("closeActivity",0);
MainActivity.mMainActivity.sendBroadcast(intent);
}
}
我的广播接收器已在PacketActivity
中注册,但永远不会调用onReceive
方法。知道为什么吗?感谢。
public class PacketActivity extends AppCompatActivity {
private static final String TAG = PacketActivity
.class
.getSimpleName();
protected static final String NAME_OF_ACTION = "closeActivity";
// Declare a custom broadcast receiver
protected BroadcastReceiver broadcastReceiver =
new BroadcastReceiver() {
// Listens for the intent indicating that this activity,
// and importantly, any extending activity should be closed.
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG,"Intent received");
if (intent.getAction().equals(NAME_OF_ACTION)) {
Log.v(TAG,"Closing activity");
finish();
}
}
};
// Register the broadcast receiver in the onCreate
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.v(TAG,"onCreate");
Log.v(TAG,"Registering receiver");
registerReceiver(broadcastReceiver,
new IntentFilter(NAME_OF_ACTION));
}
// Unregister the receiver in the onPause method to prevent
// memory leak
@Override
public void onPause(){
super.onPause();
Log.v(TAG,"onPause");
Log.v(TAG,"Unregistering receiver");
unregisterReceiver(broadcastReceiver);
}
}
修改
我尝试添加这样的动作字符串,没有结果
// Sends an intent telling activities that extend PacketActivity to
// call finish()
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
if(newState == 0){
Intent intent = new Intent("closeActivity"); // Add action string to intent
MainActivity.mMainActivity.sendBroadcast(intent);
}
}
答案 0 :(得分:1)
您正在播放的Intent
没有操作字符串。它什么都不匹配。特别是,它与IntentFilter
的{{1}}不匹配。
此外,请不要将系统广播用于进程内事件总线。使用NAME_OF_ACTION
,合适的LocalBroadcastManager
对象,greenrobot的EventBus或类似的东西。