使用 com.qw:soulpermission:1.2.2 庫來簡化動(dòng)態(tài)權(quán)限請求的過程井氢,可以讓代碼更加簡潔产镐。下面是一個(gè)示例代碼佩微,展示了如何使用 SoulPermission 庫來請求電話權(quán)限(READ_PHONE_STATE)曹铃。
- 在 build.gradle 文件中添加依賴
dependencies {
implementation 'com.qw:soulpermission:1.2.2'
}
- 在 AndroidManifest.xml 中聲明權(quán)限
<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
}
});
}
}