将数据返回到另一个活动

时间:2017-03-24 20:17:46

标签: android android-intent

我有两个活动A和B我正在使用一个按钮指向活动B我设法写了一个代码,所以它代码在5秒后自动转回活动A而没有任何按钮 但现在我想要它返回时将数据返回到A如何完成 我在A中编写代码来接收数据,但不知道在活动B中添加什么

活动A ::

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button two = (Button) findViewById(R.id.button2);
        Recieve = (TextView) findViewById(R.id.textView4);
        two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               // Intent Intent = new Intent(MainActivity.this, Gps.class);

                //startActivity( Intent);
                sendMessage();
            }
        });
    }

   public void sendMessage() {
        Intent intent = new Intent(MainActivity.this, Hello.class);

        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            Response = data.getStringExtra("key");

            Recieve.setText("msg is " + Response);

        }
    }

活动B ::

public class Hello extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello);



        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                final Intent i = new Intent(Hello.this, MainActivity.class);
                Hello.this.startActivity(i);
                Hello.this.finish();
            }
        }, 5000);
    }
}

0 个答案:

没有答案