如何使用接口在两个活动之间进行通信

时间:2021-11-03 22:23:25

I am trying to make listener interface between two activities Act1 and Act2. Act1 will start Act2. If there is some event occurred in Act2, it will inform it to Act1. Problem is that I am starting new activity using Intent, so how Act1 will assign itself as listener to Act2's interface?

我试图在两个活动Act1和Act2之间建立监听器接口。 Act1将启动Act2。如果Act2中发生了某些事件,它会通知Act1。问题是我正在使用Intent开始新的活动,那么Act1如何将自己指定为Act2接口的监听器?

Act1.java

public class Act1 extends ActionBarActivity implements
        ActionBar.OnNavigationListener {

    ActionBar actionbar;
    Intent pizzaIntent;
    boolean visibleFirstTime = true;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menutab);

        //set actionbar here
    }

@Override
    public boolean onNavigationItemSelected(int arg0, long arg1)// item pos,
                                                                // itemid
    {
        switch (arg0) {
        case 0:
            if(this.visibleFirstTime == false)
            {
            if(pizzaIntent == null)
            {
                pizzaIntent = new Intent(this,Act2.class);
                //how to call setChangeListener?
            }
            startActivity(pizzaIntent);
            }
            else
                this.visibleFirstTime = false;
            break;
        case 1:
            System.out.println("selected: " + arg0);
            break;
        case 2:
            System.out.println("selected: " + arg0);
            break;
        case 3:
            System.out.println("selected: " + arg0);
            break;
        default:
            break;
        }
        return true;
    }
}

Act2.java

public class Act2 extends Activity {

     selectionChangeListener listener;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pizza_slice_selection);
    }

    public void setChangeListener(selectionChangeListener listener)
    {
        this.listener = listener;
    }

    private interface selectionChangeListener
    {
        public void selectionMadeAtIndex(int index);
    }
}

Note: Please don't suggest me to use fragments. I want to use activities currently.

注意:请不要建议我使用碎片。我想目前使用的活动。

3 个解决方案

#1


28  

Have you considered using LocalBroadcastManager?

您是否考虑过使用LocalBroadcastManager?

In Act1's onCreate:

在Act1的onCreate中:

act2InitReceiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            // do your listener event stuff
        }
    };
LocalBroadcastManager.getInstance(this).registerReceiver(act2InitReceiver, new IntentFilter("activity-2-initialized"));

In Act1's onDestroy:

在Act1的onDestroy中:

LocalBroadcastManager.getInstance(this).unregisterReceiver(act2InitReceiver);

In Act2's onCreate:

在Act2的onCreate中:

LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("activity-2-initialized"));

Give me a comment if the code doesn't compile, I'm writing it by hand.

如果代码没有编译,请给我评论,我是手工编写的。

#2


61  

I would suggest to create a model class. Let me give you an example:

我建议创建一个模型类。让我给你举个例子:

Model class:

public class CustomModel {

    public interface OnCustomStateListener {
        void stateChanged();
    }

    private static CustomModel mInstance;
    private OnCustomStateListener mListener;
    private boolean mState;

    private CustomModel() {}

    public static CustomModel getInstance() {
        if(mInstance == null) {
            mInstance = new CustomModel();
        }
        return mInstance;
    }

    public void setListener(OnCustomStateListener listener) {
        mListener = listener;
    }

    public void changeState(boolean state) {
        if(mListener != null) {
            mState = state;
            notifyStateChange();
        }
    }

    public boolean getState() {
        return mState;
    }

    private void notifyStateChange() {
        mListener.stateChanged();
    }
}

And here's how you would use this:

以下是您将如何使用它:

// Imports
public class MainActivity extends Activity implements OnCustomStateListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CustomModel.getInstance().setListener(this);

        boolean modelState = CustomModel.getInstance().getState();
        Log.d(TAG, "Current state: " + String.valueOf(modelState));

        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }

    @Override
    public void stateChanged() {
        boolean modelState = CustomModel.getInstance().getState();
        Log.d(TAG, "MainActivity says: Model state changed: " + 
            String.valueOf(modelState));
    }
}

Changing the member state in second activity:

在第二个活动中更改成员状态:

// Imports
public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CustomModel.getInstance().changeState(true);
    }
}

LogCat output:

Current state: false

当前状态:false

MainActivity says: Model state changed: true

MainActivity说:模型状态改变了:是的

#3


-1  

The easiest way is to use static object, like this:

最简单的方法是使用静态对象,如下所示:

class Act1 extends Activity {
  static String msg1 = "Hi";
}

class Act2 extends Activity {
  String msg2;
  public onCreate() {
     msg2 = Act1.msg1;
  }
}

Avoid complexity, keep it simple and stupid.

避免复杂性,保持简单和愚蠢。

#1


28  

Have you considered using LocalBroadcastManager?

您是否考虑过使用LocalBroadcastManager?

In Act1's onCreate:

在Act1的onCreate中:

act2InitReceiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            // do your listener event stuff
        }
    };
LocalBroadcastManager.getInstance(this).registerReceiver(act2InitReceiver, new IntentFilter("activity-2-initialized"));

In Act1's onDestroy:

在Act1的onDestroy中:

LocalBroadcastManager.getInstance(this).unregisterReceiver(act2InitReceiver);

In Act2's onCreate:

在Act2的onCreate中:

LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("activity-2-initialized"));

Give me a comment if the code doesn't compile, I'm writing it by hand.

如果代码没有编译,请给我评论,我是手工编写的。

#2


61  

I would suggest to create a model class. Let me give you an example:

我建议创建一个模型类。让我给你举个例子:

Model class:

public class CustomModel {

    public interface OnCustomStateListener {
        void stateChanged();
    }

    private static CustomModel mInstance;
    private OnCustomStateListener mListener;
    private boolean mState;

    private CustomModel() {}

    public static CustomModel getInstance() {
        if(mInstance == null) {
            mInstance = new CustomModel();
        }
        return mInstance;
    }

    public void setListener(OnCustomStateListener listener) {
        mListener = listener;
    }

    public void changeState(boolean state) {
        if(mListener != null) {
            mState = state;
            notifyStateChange();
        }
    }

    public boolean getState() {
        return mState;
    }

    private void notifyStateChange() {
        mListener.stateChanged();
    }
}

And here's how you would use this:

以下是您将如何使用它:

// Imports
public class MainActivity extends Activity implements OnCustomStateListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CustomModel.getInstance().setListener(this);

        boolean modelState = CustomModel.getInstance().getState();
        Log.d(TAG, "Current state: " + String.valueOf(modelState));

        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }

    @Override
    public void stateChanged() {
        boolean modelState = CustomModel.getInstance().getState();
        Log.d(TAG, "MainActivity says: Model state changed: " + 
            String.valueOf(modelState));
    }
}

Changing the member state in second activity:

在第二个活动中更改成员状态:

// Imports
public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CustomModel.getInstance().changeState(true);
    }
}

LogCat output:

Current state: false

当前状态:false

MainActivity says: Model state changed: true

MainActivity说:模型状态改变了:是的

#3


-1  

The easiest way is to use static object, like this:

最简单的方法是使用静态对象,如下所示:

class Act1 extends Activity {
  static String msg1 = "Hi";
}

class Act2 extends Activity {
  String msg2;
  public onCreate() {
     msg2 = Act1.msg1;
  }
}

Avoid complexity, keep it simple and stupid.

避免复杂性,保持简单和愚蠢。