How would one go about starting and stopping this camera (or preview?) with the same onClick button? Starting the camera was no issue, but now also closing the camera, with the same button is proving to be more difficult for a newbie like me.
When pressing the button a second time, the program crashes now, which is not ideal.
public class MainActivity extends AppCompatActivity {
PreviewView previewView;
public int REQUEST_CODE_PERMISSIONS = 101;
public final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previewView = findViewById(R.id.previewView);
Button captureButton = findViewById(R.id.buttonPreview);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (allPermissionsGranted()) {
startCamera();
} else {
ActivityCompat.requestPermissions(MainActivity.this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (allPermissionsGranted()) {
startCamera();
} else {
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
public boolean allPermissionsGranted() {
for (String permission : REQUIRED_PERMISSIONS) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
public void startCamera() {
ListenableFuture cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = (ProcessCameraProvider) cameraProviderFuture.get();
Preview preview = new Preview.Builder().build();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
ImageAnalysis imageAnalysis =
new ImageAnalysis.Builder()
.setTargetResolution(new Size(1280, 720))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
Camera camera = cameraProvider.bindToLifecycle(
((LifecycleOwner) this),
cameraSelector,
preview,
imageAnalysis);
} catch (InterruptedException | ExecutionException e) {
}
}, ContextCompat.getMainExecutor(this));
}
}
Just need to create a boolean or int variable such as:
boolean ifCameraStarted=false;
When your called startCamera() you change this variable to true,and when you stopcamera change it to false;
When you click the button,you judge with this variable if it is true or false and do different things
booleam ifStarted=false;
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ifStarted==false){
startcamer();
}else{
stopcamer();
}
}
}
Related
My requirement is that I have to built a video recording app using Android JAVA in which user will save his 30 seconds of video which will be sent to the another server. User will use the video recording only for once.
I just want user to see the timer starting from 0 to 30 seconds so just after when he presses the Start Recording button.
How can I do so? Please help me. Sharing my code below.
public class VideoKycActivity extends AppCompatActivity implements ImageAnalysis.Analyzer, View.OnClickListener {
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
PreviewView previewView;
private VideoCapture videoCapture;
private Button bRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previewView = findViewById(R.id.previewView);
bRecord = findViewById(R.id.bRecord);
bRecord.setText("start recording"); // Set the initial text of the button
bRecord.setOnClickListener(this);
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
startCameraX(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}, getExecutor());
}
Executor getExecutor() {
return ContextCompat.getMainExecutor(this);
}
#SuppressLint("RestrictedApi")
private void startCameraX(ProcessCameraProvider cameraProvider) {
cameraProvider.unbindAll();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
Preview preview = new Preview.Builder()
.build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
// Video capture use case
videoCapture = new VideoCapture.Builder()
.setVideoFrameRate(30)
.build();
// Image analysis use case
ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build();
imageAnalysis.setAnalyzer(getExecutor(), this);
//bind to lifecycle:
cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview, videoCapture);
}
#Override
public void analyze(#NonNull ImageProxy image) {
// image processing here for the current frame
Log.d("TAG", "analyze: got the frame at: " + image.getImageInfo().getTimestamp());
image.close();
}
#SuppressLint("RestrictedApi")
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bRecord:
if (bRecord.getText() == "start recording"){
bRecord.setText("stop recording");
recordVideo();
} else {
bRecord.setText("start recording");
videoCapture.stopRecording();
}
break;
}
}
#SuppressLint("RestrictedApi")
private void recordVideo() {
if (videoCapture != null) {
long timestamp = System.currentTimeMillis();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, timestamp);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4");
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
videoCapture.startRecording(
new VideoCapture.OutputFileOptions.Builder(
getContentResolver(),
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
contentValues
).build(),
getExecutor(),
new VideoCapture.OnVideoSavedCallback() {
#Override
public void onVideoSaved(#NonNull VideoCapture.OutputFileResults outputFileResults) {
Toast.makeText(VideoKycActivity.this, "Video has been saved successfully.", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(int videoCaptureError, #NonNull String message, #Nullable Throwable cause) {
Toast.makeText(VideoKycActivity.this, "Error saving video: " + message, Toast.LENGTH_SHORT).show();
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
showProgressBar to the user or show message
}
public void onFinish() {
recordVideo();
}
}.start();
I make an app to read barcode. I use surfaceview and camerasource on it. I want to show the result in activity dialog and when come back restart surfaceview and camera source so I add setTheme in the first line in onCreate Method like this
setTheme(android.R.style.Theme_DeviceDefault_Light_Dialog);
The problem is the first activity appears in black screen how to show first activity and I want to show the other parts of first activity under the dialog box
this is the whole on create method code for the first activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.cameraPreview);
txtShow = (TextView) findViewById(R.id.txtShow);
startBarcode();
}
public void startBarcode() {
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(800, 600)
.setAutoFocusEnabled(true)
.build();
//Events
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
txtShow.post(new Runnable() {
#Override
public void run() {
//stop camera
cameraSource.stop();
//create vibrate
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
//set result for Text View
txtShow.setText(qrCodes.valueAt(0).displayValue);
final String code = txtShow.getText().toString();
// surfaceView.setTop(200);
Intent intent = new Intent(MainActivity.this,InfoActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("code",code);
startActivity(intent);
final MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.barcode);
mp.start();
I make an app to read barcode numbers and I used a surface view with a camera source in it. The app send the value to another activity which is shown as a dialog.
I make other activity as dialog but the problem the surface view is stopped. I tried many solutions until this works which is to put these lines in onCreate method .
setTheme(android.R.style.Theme_DeviceDefault_Dialog);
requestWindowFeature(Window.FEATURE_NO_TITLE);
with adding these two lines in onCreate method the surface view didn't stop and it works but the problem is the dialog shown in black screen also the parent when the dialog is shown it turns all to black. how to fix this problem.
I also modified manifest to process that and I add the following
<activity android:name=".InfoActivity"
android:excludeFromRecents="true"
android:label="#string/app_name"
android:launchMode="singleInstance"
android:theme="#style/Theme.AppCompat.Light.Dialog">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
these the whole code of the class
public class MainActivity extends AppCompatActivity {
SurfaceView surfaceView;
BarcodeDetector barcodeDetector;
CameraSource cameraSource;
TextView txtShow, itemName, itemPrice, itemQuantity;
TextView txtNameDialog, txtPriceDialog, txtQuantityDialog;
final int RequestCameraPermissionId = 1001;
String code;
RequestQueue requestQueue;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case RequestCameraPermissionId: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.cameraPreview);
txtShow = (TextView) findViewById(R.id.txtShow);
itemName = (TextView) findViewById(R.id.itemName);
itemPrice = (TextView) findViewById(R.id.itemPrice);
itemQuantity = (TextView) findViewById(R.id.itemQuantity);
startBarcode();
}
public void startBarcode() {
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(800, 600)
.setAutoFocusEnabled(true)
.build();
//Events
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
txtShow.post(new Runnable() {
#Override
public void run() {
//stop camera
cameraSource.stop();
//create vibrate
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
//set result for Text View
txtShow.setText(qrCodes.valueAt(0).displayValue);
final String code = txtShow.getText().toString();
// surfaceView.setTop(200);
final MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.barcode);
mp.start();
Button getInfo = (Button) findViewById(R.id.getInfo);
Intent intent = new Intent(MainActivity.this,InfoActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I made an application for barcode detector so I used SurfaceView to handle camerasource. After camera detects barcode and returns its value I make it to stop. There is no function to restart the camera source and surface view on any event just one fuction which is camersource.start();
It starts but the problem it works in the background and I can't see anything how to fix this problem? and display surfaceview and camera source again.
here is the whole code of the activity onCreate Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.cameraPreview);
txtShow = (TextView) findViewById(R.id.txtShow);
startBarcode();
}
public void startBarcode() {
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(800, 600)
.setAutoFocusEnabled(true)
.build();
//Events
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Make Request Runtime Permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
return;
}
try {
cameraSource.start();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
txtShow.post(new Runnable() {
#Override
public void run() {
//create vibrate
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
//set result for Text View
txtShow.setText(qrCodes.valueAt(0).displayValue);
// surfaceView.setTop(200);
cameraSource.stop();
final MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.barcode);
mp.start();
to restart after cameraSource.stop() you need:
cameraSource.start(surfaceView.getHolder());
After code captured you may stop camera source and restart OnCreate methode again. or you can call the activity again by using Intent like:
Intent intent= new Intent (getBaseContext,MainActivity.class); // your activity
startActivity(intent);
i am making an android app on my music player in which i have populated all the songs in my device using a listview,but in android 6.0 my app crashes as i open it.It doesn't crash anymore when i give it storage permissions manually in app info,and then my songs are displayed.
I have used the android 6.0 request permissions,and it results in asking the user for asking access to storage,but then it doesn't shows the list anymore.I am stuck on this...!
MainActivity.java
public class MainActivity extends AppCompatActivity implements MediaPlayerControl {
private ArrayList<Song> songList;
private ListView songView;
private MusicController controller;
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
private boolean paused=false, playbackPaused=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songView = (ListView) findViewById(R.id.song_list);
songList = new ArrayList<Song>();
//Android 6.0
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
} else {
}
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1002);
}
}
//Android 6.0
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case 1002:
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
getSongList();
// List songs in Alphabetical Order
Collections.sort(songList, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
setController();
}else{
}
return;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_shuffle:
musicSrv.setShuffle();
break;
case R.id.action_end:
stopService(playIntent);
musicSrv = null;
System.exit(0);
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
if(playIntent==null) {
playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
#Override
protected void onPause() {
super.onPause();
paused=true;
}
#Override
protected void onResume() {
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
protected void onStop() {
controller.hide();
super.onStop();
}
#Override
protected void onDestroy() {
stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}controller.show(0);
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
You can use this android library for to make handling runtime permissions a whole lot easier.
If your Activity subclasses PermisoActivity, requesting a permission is as simple as:
Permiso.getInstance().requestPermissions(new Permiso.IOnPermissionResult() {
#Override
public void onPermissionResult(Permiso.ResultSet resultSet) {
if (resultSet.areAllPermissionsGranted()) {
// Permission granted!
} else {
// Permission denied.
}
}
#Override
public void onRationaleRequested(Permiso.IOnRationaleProvided callback, String... permissions) {
Permiso.getInstance().showRationaleInDialog("Title", "Message", null, callback);
}
}, Manifest.permission.READ_EXTERNAL_STORAGE);
Gradle
dependencies {
compile 'com.greysonparrelli.permiso:permiso:0.2.0'
}
You can add multiple permissions also please visit link shared. You can get All information in details.
This code will allow you to request permission at run time by checking if the permission has been granted and if not, ask the user to enable the permission.
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSION_RESPONSE);
}
The permission being checked for in this case is to do with location services. Just replace ACCESS_COARSE_LOCATION with whatever permission you wish to ask for.