gpt4 book ai didi

android - 我如何获得 Activity ?

转载 作者:行者123 更新时间:2023-11-30 01:04:46 25 4
gpt4 key购买 nike

我在运行时请求权限,对于方法 requestPermissions() 我需要通过一个 Activity 。但是,当我在 onClick() 中调用它时,我不能只通过 this。那么,我该如何通过它呢?

我需要 Activity 的地方在 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 应用程序开发的新手。

最佳答案

简单的回答就是“this”指的是这里的Button。为了通过 Activity ,有两种方式:

  • LoginActivity.this [确定]

  • getApplicationcontext() [如果要传递应用上下文]

关于android - 我如何获得 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38978466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com