ActivityForResult不起作用

时间:2017-07-10 14:57:05

标签: android android-activity bluetooth

我是android新手。我正在制作一个样本。我打算让用户打开蓝牙。问表单显示但onActivity结果不起作用。为什么呢?

这是我的代码:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, RESULT_OK);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Toast.makeText(this, "onActivityResult", Toast.LENGTH_SHORT).show();
}

}

2 个答案:

答案 0 :(得分:1)

您的请求代码应大于零,但RESULT_OK = -1,因此请尝试提供超过0的请求代码,

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 101);

Src

答案 1 :(得分:1)

RESULT_OK为-1且startActivityForResult需要requestCode> = 0.

RESULT_OK(在API级别1中添加)

int RESULT_OK
Standard activity result: operation succeeded.

Constant Value: -1 (0xffffffff)

方法startActivityForResult(在API级别1中添加)

void startActivityForResult (Intent intent, int requestCode)

Parameters
intent  Intent: The intent to start.
requestCode int: If >= 0, this code will be returned in onActivityResult() when the activity exits.

Throws
android.content.ActivityNotFoundException

您应该根据requestCode处理响应。

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Can use switch case also if more requestCode
        if (requestCode == 100) {
             // do something
        } else if (requestCode == 101) {
             // do something
        } else {
             // do something
        }
        Toast.makeText(this, "onActivityResult", Toast.LENGTH_SHORT).show();
    }