android - activity内部的通信机制: handler, 不同activity之间的通信机制:startActivityForResult

访问量: 266

先不要考虑 无顺序关系的Activity 之间的通信. 

Activity的内部:

先声明一个handler: 

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.SUCCESSFULLY_UNBINDED:
                    Toast.makeText(SettingActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

再在代码任意位置(该Activity内)抛出这个handler:

                                Message msg = Message.obtain();
                                msg.what = Constants.SUCCESSFULLY_UNBINDED;
                                msg.obj = getResources().getString(R.string.successfully_unbinded);
                                handler.sendMessage(msg);

具有先后顺序的Activity之间: 使用startActivityForResult()

先在 第一个Activity中,打开第二个Activity: 

......
public static final int GO_TO_BIND_DEVICE_PAGE = 800;

 // 打开新的Activity
    public void startBindDevice(View view){
        Intent intent = new Intent(this, ScannerActivity.class);
        intent.putExtra("isBindDevise", 1);
        startActivityForResult(intent, GO_TO_BIND_DEVICE_PAGE);

//        startActivity(intent);  不要用.
    }

    // 接受别的Activity返回的数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == GO_TO_BIND_DEVICE_PAGE && resultCode == Constants.RESULT_CODE_BIND_SUCCESS){
            Toast.makeText(this, getResources().getString(R.string.bind_account_successfully), Toast.LENGTH_SHORT).show();
        }
    }
 

然后,在第二个Activity的对应方法中: 

//  某个方法中...
        Intent intent = new Intent();
        this.setResult(Constants.RESULT_CODE_BIND_SUCCESS, intent);
        finish();

订阅/RSS Feed

Subscribe

分类/category