我在运行时请求权限,对于方法requestPermissions()
,我需要通过一个活动。但是,当我在onClick()
中调用它时,我无法通过this
。那么,我该如何通过呢?
我需要活动的地方位于onRequestPermissionsResult()
,case locationPerm:
public class LoginActivity extends AppCompatActivity implements LocationListener {
final int locationPerm = 0;
final int cameraPerm = 1;
Context context;
Activity activity;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_nav_bar);
context = this;
int locationPermissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int cameraPermissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (locationPermissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, locationPerm);
}
if (cameraPermissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, cameraPerm);
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case locationPerm: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the
} else { // permission denied,
new AlertDialog.Builder(this)
.setTitle("Location Permission")
.setMessage("Message")
.setPositiveButton("Set a custom location later", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(/* NEED ACTIVITY HERE */, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, locationPerm);
}
})
.setNegativeButton("Re-Prompt Request", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.show();
}
return;
}
case cameraPerm: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the
} else { // permission denied,
}
return;
}
}
}
很抱歉,如果这是一个简单的修复,我对Android App Development还不熟悉。
答案 0 :(得分:1)
简单的回答是“这个”指的是这里的按钮。 为了通过活动,有两种方式:
LoginActivity.this
[当然]
getApplicationcontext()
[如果要传递应用程序上下文]