我正在为Android Marshmallow开发一个应用程序(API LEvel 23)。
我有一个包含ListView的Activity 我使用BaseView适配器填充ListView。
每当我在ListView中按下按钮时,我想启动一个Activity 但是,此活动需要访问相机,在最新的Android版本中,这意味着我应该在运行时请求相机权限 使用Activity的相机将是ZXing活动。
这是活动代码:
public class ProviderListActivity extends AppCompatActivity {
public boolean can_access_camera = false;
public final int got_camera = PackageManager.PERMISSION_DENIED;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider_list);
ListView listView = (ListView) findViewById(R.id.ProviderListView);
CardsDBHelper dbHelper = new CardsDBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
listView.setAdapter(new ProviderListAdapter(this, db));
}
public void start_scan(){
if (have_camera_permission()){
start_scan_activity();
} else {
Log.d("ProviderListActivity", "I CANNOT ACCESS THE CAMERA");
}
}
public void start_scan_activity(){
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
public boolean have_camera_permission(){
//Check for permissions
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_DENIED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, got_camera);
} else {
can_access_camera = true;
}
return can_access_camera;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case got_camera: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
can_access_camera = true;
} else {
can_access_camera = false;
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
我的适配器中的getView()
方法是:
public View getView(int position, View convertView, final ViewGroup parent) {
Button grid_button;
if (convertView == null) {
// if it's not recycled, initialize some attributes
grid_button = new Button(mContext);
grid_button.setText("Hello Text");
Drawable d = mContext.getDrawable(R.drawable.circle);
grid_button.setCompoundDrawablesRelativeWithIntrinsicBounds(null,d,null,null);
grid_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//What do I need to put inside here?
}
});
} else {
grid_button = (Button) convertView;
}
return grid_button;
}
您可能已经注意到Adapter获得了额外的db参数 这是一个SQLite数据库对象,它在Adapter中使用,但这不相关。
我不确定如何使用onClick
覆盖来调用我的扫描活动
我尝试将父Activity作为参数传递给适配器并调用scan方法,但我得到以下异常:
java.lang.IllegalArgumentException: Can only use lower 8 bits for requestCode`
有没有人能解决我的问题?
答案 0 :(得分:4)
您收到java.lang.IllegalArgumentException: Can only use lower 8 bits for requestCode
错误,因为-1(PackageManager.PERMISSION_DENIED)
方法使用requestCode
requestPermissions
。
要使其有效,请使用 1 与 255 之间的任何requestCode
。
public final int got_camera = 24;