Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have to ask for a permission when starting the app, however, the rest of the app start working before there is an answer to the dialog box which leads to the problem that the activity does not get the permission to use it until it is restarted even if the permission is granted.
How can I wait for a response before continuing with the rest of the app?
I faced the same issue in one of my apps, I needed to have all permissions ready on a virtual assistant chat screen. I collect Location, Audio and Storage permissions in a dummy Activity with some checkboxes that reflect their status. When my app has all three essential permissions, then, I make it jump from the dummy Activity to the main Chat Activity.
I'm pasting the entire Dummy Activity code here, it might need some cleanup, so just take what you need:
public class bootActivity extends Activity {
Context ctx;
private CheckBox checkboxLocation;
private CheckBox checkboxAudioRecording;
private CheckBox checkboxStorage;
private Activity thisActivity;
private String[] permissionsArray=new String[]{Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE,};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app.loge("BOOTING....START");
setContentView(R.layout.activity_boot);
thisActivity=this;
app.setBootingTRUE(getApplicationContext());
ctx=getApplicationContext();
//BIND UI
checkboxLocation=(CheckBox)findViewById(R.id.checkboxlocation);
checkboxLocation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true) {
if (needPermissionLocation()) {
app.loge("Requesting LOCATION permission");
ActivityCompat.requestPermissions(thisActivity, permissionsArray,appPermissionsCallbackConstant);
}
}
refreshUI();
if((!needPermissionLocation())&&(!needPermissionRecordAudio())&&(!(needPermissionStorage()))){
launchApp();
}
}
});
checkboxAudioRecording=(CheckBox)findViewById(R.id.checkboxaudiorecording);
checkboxAudioRecording.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true) {
if (needPermissionRecordAudio()) {
app.loge("Requesting RECORDING permission");
ActivityCompat.requestPermissions(thisActivity, permissionsArray, appPermissionsCallbackConstant);
}
}
refreshUI();
if((!needPermissionLocation())&&(!needPermissionRecordAudio())&&(!(needPermissionStorage()))){
launchApp();
}
}
});
checkboxStorage=(CheckBox)findViewById(R.id.checkboxstorage);
checkboxStorage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true) {
if (needPermissionStorage()) {
app.loge("Requesting STORAGE permissions");
ActivityCompat.requestPermissions(thisActivity, permissionsArray, appPermissionsCallbackConstant);
}
}
refreshUI();
if((!needPermissionLocation())&&(!needPermissionRecordAudio())&&(!(needPermissionStorage()))){
launchApp();
}
}
});
Intent intent = getIntent();
String action = intent.getAction();
Uri data = intent.getData();
if(data!=null) {
app.logy("URI:" + data.toString());
String userinput=data.getQueryParameter("input");
app.logy("User Input: "+userinput);
if(userinput!=null) {
//app.setBootingFALSE(getApplicationContext());
app.setDeeplinkInput(ctx,userinput);
app.logy("USER INPUT: " + userinput);
}
}
if(action!=null) {
app.logy("ACTION:" + action);
}
// checkPermissions(); //launches app if permissions are OK, if not, updates permission status on the checkboxes
app.logy("BOOTING....END");
}//end onCreate
boolean needPermissionLocation(){
return ((ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)||
(ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED));
}
boolean needPermissionRecordAudio(){
return (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED);
}
boolean needPermissionStorage(){
return ((ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)&&
(ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==appPermissionsCallbackConstant){
app.loge("BootActivity.onRequestPermissionsResult");
refreshUI();
if((!needPermissionLocation())&&(!needPermissionRecordAudio())&&(!needPermissionStorage())){
launchApp();
}
}
}
void refreshUI(){
app.loge("refreshUI()");
//Refresh CHECKBOXES with permissions
if(needPermissionRecordAudio())
checkboxAudioRecording.setChecked(false);
else
checkboxAudioRecording.setChecked(true);
if(needPermissionLocation())
checkboxLocation.setChecked(false);
else
checkboxLocation.setChecked(true);
if(needPermissionStorage())
checkboxStorage.setChecked(false);
else
checkboxStorage.setChecked(true);
}
void launchApp(){
app.loge("BootActivity.LaunchApp()");
Intent i = new Intent(bootActivity.this, MainActivity.class);
startActivity(i);
finish();
}
final int appPermissionsCallbackConstant=1111;
void checkPermissions(){
app.loge("BootActivity.checkPermissions()");
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)&&
(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)&&
(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)&&
(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)&&
(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)){
app.loge("All permissions are OK");
checkboxAudioRecording.setChecked(true);
checkboxLocation.setChecked(true);
checkboxStorage.setChecked(true);
launchApp();
}
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
checkboxAudioRecording.setChecked(false);
app.loge("Requesting RECORD_AUDIO PERMISSION");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO},appPermissionsCallbackConstant);
}
else{
checkboxAudioRecording.setChecked(true);
}
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)||
(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
app.loge("Requesting LOCATION PERMISSIONS");
checkboxLocation.setChecked(false);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},appPermissionsCallbackConstant);
}
else{
checkboxLocation.setChecked(true);
}
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)||
(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)){
checkboxStorage.setChecked(false);
app.loge("Requesting STORAGE READ/WRITE PERMISSION");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},appPermissionsCallbackConstant);
}
else{
checkboxStorage.setChecked(true);
}
}
#Override
protected void onResume() {
super.onResume();
app.loge("BootActivity.onResume");
thisActivity=this;
refreshUI();
if((!needPermissionLocation())&&(!needPermissionRecordAudio())&&(!needPermissionStorage())){
launchApp();
}
}
#Override
public void onNewIntent(Intent intent) {
this.setIntent(intent);
}
}
Related
I'm just fetching the current location of the device and displaying on a TextView but the TextView does not show the results, however , it seems that the java code is fetching the location correctly but not updating the TextView as I have tried a lot relevant codes without error of location fetching.
Moreover, I am using a physical device to run the Application, not the emulator.
The recent code I've tried is as below:
public class roadSideSelection extends AppCompatActivity implements AdapterView.OnItemSelectedListener, LocationListener {
int MY_PERMISSION_LOCATION=100;
int MY_PERMISSION_ACCESS_COARSE_LOCATION=100;
protected LocationManager locationManager;
protected Context context;
TextView txtLat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_road_side_selection);
marshmallowGPSPremissionCheck();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_ACCESS_COARSE_LOCATION);
}
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
txtLat = findViewById(R.id.latitudeTextview);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = findViewById(R.id.latitudeTextview);
String s = getString(R.string.latitude, location.getLatitude(), location.getLongitude());
txtLat.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
private void marshmallowGPSPremissionCheck() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& checkSelfPermission(
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_LOCATION);
} else {
// gps functions.
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#Nullable String[] permissions,#Nullable int[] grantResults) {
if (requestCode == MY_PERMISSION_LOCATION
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
'''
Strings.xml
Latitude: %1$d; Longitude: %2$d
txtLat = (TextView) findViewById(R.id.latitudeTextview);
Cast the view to TextView and make sure you are using correct view id
I have the following class, that is extended by all my activities, where I want to save the last location using LocationServices.
Debugging it seems that permissions are granted, and I enter the onComplete method, but task.getResult() is always null. How is this possible?
public class MyAppCompatActivity extends AppCompatActivity {
private static final int LOCATION_REQUEST_CODE = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
LOCATION_REQUEST_CODE);
} else
setUserLocation();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUserLocation();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
#SuppressLint("MissingPermission")
private void setUserLocation() {
LocationServices.getFusedLocationProviderClient(this).getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
ROUserInfo user = UserManager.getROUserInfo();
if(user==null || task.getResult()==null)
return;
user.User._Position._Latitude=task.getResult().getLatitude();
user.User._Position._Longitude=task.getResult().getLongitude();
UserManager.updateUserOnServer(user);
}
});
}
}
I'm writing an app in which its only function is acting as a receiver for Bluetooth Low Energy. The app is useless if the user does not allow BLE. When the app is started for the first time, I want it to ask the user for Locations Permission (since Android requires it for BLE). I bring the permissions dialog up, but the rest of the app continues while the user is reading the dialog, starting BLEScanner and all that. I want the app to pause while the user is reading the dialog and deciding what to do. Here's my setup:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);
}
//More UI preparation stuff
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE: {
if (permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
PermissionDialog newDialog = new PermissionDialog();
newDialog.show(getSupportFragmentManager(), "Request Location Permission");
}
}
}
}
Where "PermissionDialog" is a different class that uses an DialogFragment to explain why the app needs the permission and then closes/restarts the app. In this case, the rest of the app continues, attempting to do Bluetooth stuff while the user is still reading the permission dialog that has popped up! Naively, I thought I could use a synchronize lock to do it, as below, but in this case, the callback is never called:
private final Object initLock = new Object();
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);
}
Log.i("Lock", "At the lock!");
try {
synchronized (initLock) {
initLock.wait();
}
}
catch (InterruptedException e) {
//TODO find out what to do here
}
Log.i("Lock", "Past the lock!");
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE: {
if (permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
synchronized (initLock){
initLock.notify();
}
}
else{
PermissionDialog newDialog = new PermissionDialog();
newDialog.show(getSupportFragmentManager(), "Request Location Permission");
}
}
}
}
}
What's the proper way to do this? I have a few ideas, but they all balloon in scope. Do I need to make another class that inherits AppCompatActivity to do the permissions and I call it as a thread? But then how do I know where the onRequestPermissionResult callback will go? I'm at a loss.
Put the code inside your //More UI preparation stuff to a new method. After the permissions, say 'init()'
private void init(){
//More UI preparation stuff
}
Then inside onCreate, if permission is already granted, call init(); otherwise request permission.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);
} else {
init();
}
}
Now handle the user's response inside onRequestPermissionsResult - If user has granted, initialize the UI, otherwise block the feature and/or notify the user about the issue.
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE: {
if (permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
init();
} else{
PermissionDialog newDialog = new PermissionDialog();
newDialog.show(getSupportFragmentManager(), "Request Location Permission");
}
}
}
}
}
PS: For this same purpose, I have prepared a library which makes this process a lot easier. Have a look at my library.
You can use EasyPermissions and implement EasyPermissions.PermissionCallbacks to resolve it.
And add this annotation:#AfterPermissionGranted before the method you want to run
such as :
AfterPermissionGranted(PERMISSION_REQUESTCODE_BASE)
private void requestPerminssions(){
if(EasyPermissions.hasPermissions(this,PERMISSIONS)){
int hasCityData=config.getInt("isDataEmpty",0);
if(hasCityData==0){
new CountryInfoThread().execute();
}else {
new LocalPositionThread().execute();
}
}
}
I ended up using a private variable:
private boolean readyToStart = false;
In this way:
#Override
protected void onCreate(Bundle savedInstanceState) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);
}
else{
readyToStart = true;
}
}
#Override
protected void onResume() {
super.onResume();
if (readyToStart) {
startBluetooth();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults) {
Log.i("Permission", "Callback made");
switch (requestCode) {
case REQUEST_CODE: {
if (permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
PermissionDialog newDialog = new PermissionDialog();
newDialog.show(getSupportFragmentManager(), "Request Location Permission");
}
else{
startBluetooth();
}
}
}
}
}
I tried to learn how to develop an Apps for scanning Access Points. I read many references and watched many videos. Among them are the following:
Android 6.0 bug ? Have permission but getScanResults() still return empty list in Android 6.0
The method checkSelfPermission(Context, String) is undefined for the type ContextCompat
Wifi scan results broadcast receiver not working
https://www.youtube.com/watch?v=MrrBlxq33ms&t=181s
Please try my code and see if it runs on your device and if it give the list of Access Points. If not please advice. Thanks in advance
public class MainActivity extends AppCompatActivity {
Switch aSwitch;
WifiManager wifiManager;
TextView textView;
//Context mContext;
private static final int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//mContext = (Manifest.permission) this;
setContentView(R.layout.activity_main);
aSwitch = (Switch) findViewById(R.id.myswitch);
textView = (TextView) findViewById(R.id.textView);
wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
//reg switch
if (Build.VERSION.SDK_INT >= 23) {
checkPermission();
}
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//to switch on
if (isChecked && !wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
} else if (!isChecked && wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
}
});
//WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//textView.setText("\n\n Wifi status: " + wifiInfo.toString());
}
private boolean checkPermission() {
List<String> permissionsList = new ArrayList<String>();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(Manifest.permission.ACCESS_WIFI_STATE);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(Manifest.permission.CHANGE_WIFI_STATE);
}
if (permissionsList.size() > 0) {
ActivityCompat.requestPermissions(this, permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
if (permissions.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED ||
(permissions.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)){
onContinue();
}
else {
// Permission Denied
//Usually it works and I am thinking to add a toast later on
}
break;
}
}
//#Override
void onContinue() {
MyBroadCastReceiver myBroadCastReceiver = new MyBroadCastReceiver();
// register WiFi scan results receiver
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(myBroadCastReceiver, filter);
wifiManager.startScan();
super.onResume();
}
class MyBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
StringBuffer stringBuffer = new StringBuffer();
List<ScanResult> scanResults = wifiManager.getScanResults();
if (scanResults != null && !scanResults.isEmpty()) {
for (ScanResult scanResult : scanResults) {
stringBuffer.append(scanResult);
}
textView.setText(stringBuffer);
}
}
}
}
I'm trying to make that when I load my map activity, a "my location" button will appear. This is my code, and the button which makes my activity to zoom in to my current location isn't appearing. What do I need to change in my code to make it work?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String FIREBASE_URL="https://********.firebaseio.com/";
private Firebase firebaseRef;
private LocationManager locationManager;
private GoogleMap mMap;
SupportMapFragment mapFrag;
boolean bPermissionGranted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
Firebase.setAndroidContext(this);
firebaseRef = new Firebase(FIREBASE_URL);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
bPermissionGranted = checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (mMap != null) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(32.065483, 34.824550));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(10);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
// TODO: Prompt with explanation!
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay!
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap=googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (bPermissionGranted) {
//User has previously accepted this permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
}
else {
//Not in api-23, no need to prompt
mMap.setMyLocationEnabled(true);
}
firebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.child("users").getChildren()) {
String rightLocation = child.child("location_right").getValue().toString();
String leftLocation = child.child("location_left").getValue().toString();
double location_left = Double.parseDouble(leftLocation);
double location_right = Double.parseDouble(rightLocation);
String party_title = child.child("party/party_title").getValue().toString();
LatLng cod = new LatLng(location_left, location_right);
googleMap.addMarker(new MarkerOptions().position(cod).title(party_title));
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
This is a simplified version of my other answer that also requests location updates .
The key is just to make sure that the user has granted you permission before you make the call to setMyLocationEnabled().
It's also possible that the user has not accepted the permission prompt by the time onMapReady() is called (most likely on first launch of the app), therefore there's another call to setMyLocationEnabled() in the onRequestPermissionsResult() callback in the case that the user accepted the permission.
First, ensure that you have the permissions in your AndroidManifest.xml (outside of the application tag):
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Here is a full Activity class that will work for you:
public class MapLocationActivity extends AppCompatActivity
implements OnMapReadyCallback {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//User has previously accepted this permission
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mGoogleMap.setMyLocationEnabled(true);
}
} else {
//Not in api-23, no need to prompt
mGoogleMap.setMyLocationEnabled(true);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
// TODO: Prompt with explanation!
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay!
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
If you revoke the permission:
It will prompt again:
You are using the same condition in if and else both blocks.
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
So, if your above condition is not true then how will be the same condition gets true in your else block. That's the reason
mMap.setMyLocationEnabled(true); never gets executed because your condition is false.
I guess what you want to do in else block is to request for permissions if it is not there. So it will change like this -
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, <request_code>);
}
And implement onRequestPermissionsResult callback
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case <request_code>:
if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
break;
}
}
Please write N instead of M after Build.VERSION_CODES.
In this line in your code:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
it worked for me