2017-07-10 61 views
0

我是Android新手。我正在製作一個樣本。我打算讓用戶打開藍牙。詢問表單顯示,但onActivity結果不起作用。爲什麼?ActivityForResult不起作用

這裏是我的代碼:

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(); 
} 

}

回答

1

您的請求碼應大於零,但RESULT_OK = -1所以儘量給請求代碼大於0,

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

Src

+0

是的。謝謝=) – DanMan

1

RESULT_OK是-1並且startActivityForResultexp ects requestCode> = 0。

RESULT_OK

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(在API級別1添加)。

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(); 
    }