Intent在Activity中的使用

2017-04-20 • AndroidNo Comments

1.显式的打开另一个Activity

Intent intent = new Intent(MainActivity.this, MiaoActivity.class);
startActivity(intent);

2.隐式的打开Activity

Intent intent = new Intent("love.illya.activitytest.ACTION_START");
intent.addCategory("love.illya.activitytest.MY_CATEGORY");
startActivity(intent);

3.打开电话应用

Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:5203334"));
startActivity(intent);

4.打开网页

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://nocilol.com"));
startActivity(intent);

5.打开Activity并传递参数

String data = "miaomiaomiaomiao";
Intent intent = new Intent(MainActivity.this, MiaoActivity.class);
intent.putExtra("cat_voice", data);
startActivity(intent);

//接收方
Intent intent = getIntent();
String data = intent.getStringExtra("cat_voice");

6.以监听关闭模式打开Activity

Intent intent = new Intent(MainActivity.this, MiaoActivity.class);
startActivityForResult(intent, 1);

//重写监听回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode){
        case 1:
            if (resultCode == RESULT_OK)
            {
                String returnString = data.getStringExtra("data_return");
                Log.d("MainActivity", returnString);
            }

            break;
    }
}

//关闭时提交返回值
@Override
public void onBackPressed() {
    Intent intent = new Intent();
    intent.putExtra("data_return", "Miaomiaomiao");
    setResult(RESULT_OK, intent);
    finish();
}

粤公网安备 44011102000950号