首先,通过Intent 构建出当前的“意图”,然后调用 startActivity()或startActivityForResult()方法将活动启动起来,
SecondActivity代码如下
package com.qihui.myapplication10; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class SecondActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("Se","线程id是:"+getTaskId()); setContentView(R.layout.activity_second); Intent intent=getIntent(); String data=intent.getStringExtra("param1"); Log.d("SecondActivity",data); Button buttons= (Button) findViewById(R.id.buttons); buttons.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Intent intent=new Intent(SecondActivity.this,MainActivity.class); // intent.putExtra("param1","data1"); // intent.putExtra("param2","data2"); // startActivity(intent); android.os.Process.killProcess(android.os.Process.myPid()); ActivityCollector.finishAll();//销毁所有活动 } }); } public static void actionStart(Context context,String data1,String data2){ Intent intent=new Intent(context,SecondActivity.class); intent.putExtra("param1",data1); intent.putExtra("param2",data2); context.startActivity(intent); } }
我们在SecondActivity中添加一个 actionStart()方法,在这个方法中完成了Intent的构建,另外所有SecondActivity中需要的数据都是通过actionStart()方法参数传递过来的,然后把它存储到intent中,最后调用startActivity()方法启动SecondActivity。
现在,只需要一行代码就可以启动SecondActivity,如下:
package com.qihui.myapplication10; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class FirstActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); Button buttonf= (Button) findViewById(R.id.buttonf); buttonf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SecondActivity.actionStart(FirstActivity.this,"hello SecondActivity","data2"); } }); } }
养成良好的习惯,给你编写的每个活动都添加此类的启动方法,这样不仅可以让启动活动变得简单,还可以节省传递数据的沟通。