活动到活动回调侦听器



让我们假设两个活动Activity1Activity2。我需要从methodAct2Activity2内部)调用方法methodAct1()Activity1内部)。我认为它应该使用回调侦听器工作——我不想使用EventBus libs!

我使用以下代码获得java.lang.NullPointerException

接口:

public interface MyListener {
    public void listen();
}

创建事件的活动:

public class Activity2 extends Activity {
    private MyListener  myListener;
    public void setUpListener(MyListener myListener) {
        this.myListener = myListener;
    }
    private void doWork(){
        //do stuff 
        myListener.listen();
    }
}

当工作完成时,我想获得该事件的活动:

public class Activity1 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Activity2 activity2 = new Activity2();
        activity2.setUpListener(new setUpListener() {
            @Override
            public void listen() {
                // get the event here
            }
        });
    }
}

这是绝对不可能的。您永远不会自己创建新的"活动"。不能同时运行两个"活动"。

如果您希望另一个"活动"根据您以前的"活动"所需内容来执行某项操作,则需要将其添加到"意向"中。

Intent intent = new Intent(this, Activity2.class);
intent.putExtra("data field", "data value");
startActivity(intent);

如果你想通过回调获得特定的功能,那么你可能会想到Fragments。通过这种方式,您可以运行相同的"活动",它可以告诉各个片段他们需要做什么。

NPE的发生是因为您的语句:

Activity2 activity2 = new Activity2(); <--

你永远不应该这样做,相反,你应该在活动1:中这样做

Intent intent = new Intent(this, Activity2.class);
intent.putExtra("dataKey", "dataValue");
startActivityForResult(pickContactIntent, CALLBACK_REQUEST);

startActivityForResult()提供从活动2到活动1的回调,您必须覆盖活动1:中的结果

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == CALLBACK_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // The Intent's data Uri identifies which contact was selected.
            // Do something with the contact here (bigger example below)
        }
    }
}

您可以用这样的方法来做到这一点。。。。

public class Activity2 extends AppCompatActivity {
    private static MyListener  myListener;
    public static void setUpListener(MyListener Listener) {
        myListener = Listener;
    }
    public void doWork(View view) {
        myListener.listen();
    }
}

public class Activity1 extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Activity2.setUpListener(new MyListener() {
            @Override
            public void listen() {
                Log.d("Hello", "Hello World");
            }
        });
    }
    public void goToAnotherActivity(View view) {
        startActivity(new Intent(Activity1.this, Activity2.class));
    }
}

尽管这不是最好的方法,而且为了使用这种机制,需要创建activity1。

你可以这样做>-步骤01:实现共享接口


public interface SharedCallback {
    public String getSharedText(/*you can define arguments here*/);
}
  • 步骤02:实现共享类

final class SharedMethode {
    private static Context mContext;
    private static SharedMethode sharedMethode = new SharedMethode();
    private SharedMethode() {
        super();
    }
    public static SharedMethode getInstance() {
        return sharedMethode;
    }
    public void setContext(Context context) {
        if (mContext != null)
            return;
        mContext = context;
    }
    public boolean contextAssigned() {
        return mContext != null;
    }
    public Context getContext() {
        return mContext;
    }
    public void freeContext() {
        mContext = null;
    }
}

-步骤03:在第一个活动中玩代码


public class FirstActivity extends Activity implements SharedCallback {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);
        // call playMe from here or there
        playMe();
    }
    private void playMe() {
        SharedMethode.getInstance().setContext(this);
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }
    @Override
    public String getSharedText(/*passed arguments*/) {
        return "your result";
    }
}
  • 步骤04:在SecondActivity中完成游戏

public class SecondActivity extends Activity {
    private SharedCallback sharedCallback;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);
        if (SharedMethode.getInstance().contextAssigned()) {
            if (SharedMethode.getInstance().getContext() instanceof SharedCallback)
                sharedCallback = (SharedCallback) SharedMethode.getInstance().getContext();
            // to prevent memory leak. no further needs
            SharedMethode.freeContext();
        }
        // You can now call your implemented methodes from anywhere at any time
        if (sharedCallback != null)
            Log.d("TAG", "Callback result = " + sharedCallback.getSharedText());
    }
        @Override
        protected void onDestroy() {
        sharedCallback = null;
        super.onDestroy();
    }
}

您还可以实现一个backword回调(从First到Second),从SecondAvitivity获得一些结果,或者调用一些方法

最新更新