博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android之startActivity、startActivityForResult和setResult详解
阅读量:5462 次
发布时间:2019-06-15

本文共 6355 字,大约阅读时间需要 21 分钟。

[PS:还是以GOOGLE原生的BluetoothChat为例]

1. startActivitystartActivityForResult的区别

startActivity( ) 仅仅是跳转到目标页面,若是想跳回当前页面,则必须再使用一次startActivity( )。

startActivityForResult( ) 可以一次性完成这项任务,当程序执行到这段代码的时候,假若从T1Activity跳转到下一个Text2Activity,

而当这个Text2Activity调用了finish()方法以后,程序会自动跳转回T1Activity,并调用前一个T1Activity中的onActivityResult( )方法。

例如在BluetoothChat类中,对跳转到DeviceListActivity类采用的是startActivityForResult( ) 方式:

  @Override    public boolean onOptionsItemSelected(MenuItem item) {        Intent serverIntent = null;        switch (item.getItemId()) {        case R.id.secure_connect_scan:            // Launch the DeviceListActivity to see devices and do scan            serverIntent = new Intent(this, DeviceListActivity.class);            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);            return true;        case R.id.insecure_connect_scan:            // Launch the DeviceListActivity to see devices and do scan            serverIntent = new Intent(this, DeviceListActivity.class);            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);            return true;        case R.id.discoverable:            // Ensure this device is discoverable by others            ensureDiscoverable();            return true;        }        return false;    }

在DeviceActivity中则使用setResult()方法返回值:

  // The on-click listener for all devices in the ListViews    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {        public void onItemClick(AdapterView
av, View v, int arg2, long arg3) { // Cancel discovery because it's costly and we're about to connect mBtAdapter.cancelDiscovery(); // Get the device MAC address, which is the last 17 chars in the View String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity setResult(Activity.RESULT_OK, intent); finish(); } };

但是,要注意,如果在startActivityForResult跳转到的Activity里面设置setResult,结果并不会马上返回给parent的Activity,只有当前Activity被finish,

结果才会被发送给parent的onActivityResult去处理:

  public void onActivityResult(int requestCode, int resultCode, Intent data) {        if(D) Log.d(TAG, "onActivityResult " + resultCode);        switch (requestCode) {        case REQUEST_CONNECT_DEVICE_SECURE:            // When DeviceListActivity returns with a device to connect            if (resultCode == Activity.RESULT_OK) {                connectDevice(data, true);            }            break;        case REQUEST_CONNECT_DEVICE_INSECURE:            // When DeviceListActivity returns with a device to connect            if (resultCode == Activity.RESULT_OK) {                connectDevice(data, false);            }            break;        case REQUEST_ENABLE_BT:            // When the request to enable Bluetooth returns            if (resultCode == Activity.RESULT_OK) {                // Bluetooth is now enabled, so set up a chat session                setupChat();            } else {                // User did not enable Bluetooth or an error occurred                Log.d(TAG, "BT not enabled");                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();                finish();            }        }    }

 2. setResult()的退出时机

这里的一个例子是提前调用setResult()设置好退出机制,以应对用户按"BACK"的情况:

  @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // Setup the window        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);        setContentView(R.layout.device_list);        // Set result CANCELED in case the user backs out        setResult(Activity.RESULT_CANCELED);        // Initialize the button to perform device discovery        Button scanButton = (Button) findViewById(R.id.button_scan);        scanButton.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                doDiscovery();                v.setVisibility(View.GONE);            }        });        // Initialize array adapters. One for already paired devices and        // one for newly discovered devices        mPairedDevicesArrayAdapter = new ArrayAdapter
(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter
(this, R.layout.device_name); // Find and set up the ListView for paired devices ListView pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mDeviceClickListener); // Find and set up the ListView for newly discovered devices ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices Set
pairedDevices = mBtAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) { findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) { mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); } }

 

posted on
2014-12-19 10:12 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/jayhust/p/4173274.html

你可能感兴趣的文章
test
查看>>
MKReverseGeocoder 过时,IOS5中使用CLGeocoder
查看>>
@DataProvider Method 参数传递
查看>>
The Tao to Excellent 2
查看>>
Redis 命令
查看>>
Cocos2d-js 3.0 颜色变换(调整sprite/图片的色调)
查看>>
织梦仿站第一课
查看>>
java step1:基础知识3
查看>>
Hadoop 发行版本 Hortonworks 安装详解(二) 安装Ambari
查看>>
Vue系列之 => webpack结合vue使用
查看>>
JSR356标准Java WebSocket实现多人 or 单人聊天室demo
查看>>
PHP sha1()函数
查看>>
阿里云 EDAS-HSF 用户指南
查看>>
HashMap实现原理分析
查看>>
Symantec AntiVirus企业版联机客户机端卸载密码(转)
查看>>
jQuery中的ajax
查看>>
BPM实例分享:H3如何调试V3
查看>>
程序员讨论《黑客帝国》(一)真实与虚拟
查看>>
flex布局
查看>>
【C++ 拾遗】C++'s most vexing parse
查看>>