使用 com.qw:soulpermission:1.2.2 库来简化动态权限请求的过程,可以让代码更加简洁。下面是一个示例代码,展示了如何使用 SoulPermission 库来请求电话权限(READ_PHONE_STATE)。
- 在 build.gradle 文件中添加依赖
dependencies {
implementation 'com.qw:soulpermission:1.2.2'
}
- 在 AndroidManifest.xml 中声明权限
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
- 在 MainActivity 中编写代码
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import com.qw.soul.permission.SoulPermission;
import com.qw.soul.permission.bean.Permission;
import com.qw.soul.permission.bean.Special;
import com.qw.soul.permission.callbcak.CheckRequestPermissionListener;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Request READ_PHONE_STATE permission
requestPhoneStatePermission();
}
private void requestPhoneStatePermission() {
SoulPermission.getInstance().checkAndRequestPermission(Manifest.permission.READ_PHONE_STATE, new CheckRequestPermissionListener() {
@Override
public void onPermissionOk(Permission permission) {
// Permission is granted
Log.d("Permissions", "READ_PHONE_STATE permission is granted.");
// Proceed with your app logic here
}
@Override
public void onPermissionDenied(Permission permission) {
// Permission is denied
Log.d("Permissions", "READ_PHONE_STATE permission is denied.");
// Show some message to the user explaining why you need this permission
// Optionally, you can redirect the user to the app settings
}
});
}
}