1趋艘、添加權(quán)限
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
MainActivity中的代碼
public class MainActivity extends AppCompatActivity {
private static final int PERMISSIONS_REQUEST_CAMERA = 454;
private Context mContext;
static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
findViewById(R.id.text).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkSelfPermission();
}
});
}
/**
* 檢查權(quán)限
*/
void checkSelfPermission() {
if (ContextCompat.checkSelfPermission(mContext, PERMISSION_CAMERA)!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{PERMISSION_CAMERA}, PERMISSIONS_REQUEST_CAMERA);
} else {
startWallpaper();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSIONS_REQUEST_CAMERA: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startWallpaper();
} else {
Toast.makeText(mContext, getString(R.string._lease_open_permissions), Toast.LENGTH_SHORT).show();
}
return;
}
}
}
/**
* 選擇壁紙
*/
void startWallpaper() {
final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
Intent chooser = Intent.createChooser(pickWallpaper, getString(R.string.choose_wallpaper));
startActivity(chooser);
}
}