英文:
Android Java Can't display requestPermission in fragment
问题
我使用大量日志测试了我的应用,似乎我的应用在 ActivityCompat.requestPermissions 处卡住了,并且没有显示任何消息。我认为问题可能出在 getActivity() 上,因为我在一个 Fragment 中。
@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
result = view.findViewById(R.id.tab3Result);
progressBar = view.findViewById(R.id.tab3ProgressBar);
view.findViewById(R.id.tab3GetLocation).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION_PERMISSION);
} else {
getCurrentLocaiton();
}
}
});
}
英文:
I tested my application with a lot of logs and it seems that my application stuck at ActivityCompat.requestPermissions and it doesn't display any message. I think the problem might be getActivity() because I am in a Fragment.
@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
result = view.findViewById(R.id.tab3Result);
progressBar = view.findViewById(R.id.tab3ProgressBar);
view.findViewById(R.id.tab3GetLocation).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION_PERMISSION);
} else {
getCurrentLocaiton();
}
}
});
}
答案1
得分: 1
首先,我想指出有一个拼写错误:
getCurrentLocaiton();
除此之外:
可能是您的上下文有问题?我的意思是,如果问题仅是拼写错误,那么这完全不相关,所以首先修复拼写错误。
getApplicationContext() 指的是整个应用程序上下文。
替代方法是 getContext(),它指的是您所在的特定视图。
我正在阅读相关内容,并找到了一些可能有用的信息。
https://developer.android.com/training/permissions/requesting //您需要在上下文中请求的部分。
由于您位于一个片段中,您可能需要在片段内请求权限。
英文:
First I'd like to point out there is a typo:
getCurrentLocaiton();
Other than that:
Could it be your context? I mean this is totally irrelevant if the issue is simply the typo so fix that first.
getApplicationContext() refers to the entire application context.
The alternative is getContext() which refers to the specific view that you're in.
I'm reading about it and found some perhaps useful information.
https://developer.android.com/training/permissions/requesting //the part that you need to request in context.
Then I read this:
https://stackoverflow.com/questions/10641144/difference-between-getcontext-getapplicationcontext-getbasecontext-and
Since you're in a fragment, you may need to request permission inside the fragment.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论