i am making a app in which on click of button it moves from 1 activity to 2nd activity on which i need gps to be active i used a alertdialog box to turn on the gps by clicking settings it will open to the setting and if i enable it dialogbox disapper and gps start working but if i press back button without enabling the gps it works and activity starts i want to check if gps is enabled if not the it should not show me the 2nd activity
No Error Coming but just on back press on setting without enabling it will start activity without any error and still gps is off.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
textView1 = (TextView) findViewById(R.id.location_view);
button1 = (Button) findViewById(R.id.camera);
button2 = (Button) findViewById(R.id.upload);
editText1 = (EditText) findViewById(R.id.remarks);
imageView11 = (ImageView) findViewById(R.id.image1);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
locationText = (TextView) findViewById(R.id.location_view);
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat
.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission
.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, (LocationListener) this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.item1:
Toast.makeText(getApplicationContext(),"Account Clicked",Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Account Clicked",Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Confirm Logout");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("Are You Sure You Want to Logout ");
alerDialogbuilder.setMessage("Logingout will need id password again");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intents = new Intent(Main3Activity.this,MainActivity.class);
startActivity(intents);
Toast.makeText(getApplicationContext(),"Successfull Logout",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Logout Canceled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
return true;
default:return super.onOptionsItemSelected(item);
}
}
private void camera(){
Intent intents = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intents,CAMERA_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==CAMERA_REQUEST&&resultCode== Activity.RESULT_OK){
Bitmap photo= (Bitmap)data.getExtras().get("data");
imageView11.setImageBitmap(photo);
}
}
private void upload(){
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Confirm Upload ?");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("Are You Sure You Want to Upload Data");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"File Uploading...",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Recheck Data",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
}
#Override
public void onClick(View view) {
if(view==button1){
camera();
}
else if (view == button2){
upload();
}
}
#Override
public void onLocationChanged(Location location) {
double lati = location.getLatitude();
double longi = location.getLongitude();
locationText.setText("Latitude: " + lati + "\n Longitude: " + longi);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Toast.makeText(this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Enable Gps to Continue");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("If You Want To Enable Gps Go To Settings");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent1);
Toast.makeText(getApplicationContext(),"Enable Gps..",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
Toast.makeText(getApplicationContext(),"Uploading Failed,Enable Gps",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
}
}
i want to check only if gps is enabled or not when my activity start if it is not enabled go to settings and still if the user doesnot enable the gps setting it should not work any further pls help me out m a new to android
Implement below method for checking status -:
public boolean CheckGpsStatus() {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return GpsStatus;
}
protected LocationRequest locationRequest;
public void checkForLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setInterval(MIN_UPDATE_INTERVAL);
locationRequest.setNumUpdates(1);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
public void checkForLocationSettings() {
try {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(MainActivity.this);
settingsClient.checkLocationSettings(builder.build())
.addOnSuccessListener((Activity) MainActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// delay(1);
//Setting is success...
// Toast.makeText(SplashActivity.this, "Enabled the Location successfully. Now you can press the buttons..", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener((Activity) MainActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult((Activity) MainActivity.this, GET_PERMISSION_REQ_CODE);
} catch (Exception ex) {
new MyUtils().catchError(MainActivity.this, ex);
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Toast.makeText(MainActivity.this, "Setting change is not available.Try in another device.", Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
new MyUtils().catchError(MainActivity.this, e);
}
}
This Above code shows the popup for enable the gps if gps is not enabled and also gives you callback for success and failure
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,OnMapReadyCallback,LocationListener{
protected static final String TAG = "MainActivity";
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
Marker mCurrLocationMarker;
GoogleMap mgooglemap;
private LocationManager locationManager;
#Override
public void onLocationChanged(Location location) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// MarkerOptions markerOptions = new MarkerOptions();
// markerOptions.position(latLng);
// markerOptions.title("Current Position");
// markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// mCurrLocationMarker = mgooglemap.addMarker(markerOptions);
//move map camera
mgooglemap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
mgooglemap.getMaxZoomLevel();
// locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Please Enable GPS", Toast.LENGTH_LONG).show();
//for you want to open Settings screen
while(!onProviderEnabled())
{
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
}
The onProviderDisabled() of the above code will provide you the required flow.
Related
iam unable to get my location i dont know why ive tried everything on google as iam a newbie to android please help me solve this
package com.parkaspot.najeeb.project;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
final String TAG = "MAIN";
ArrayList<RecentData> list;
RecentAdapter recentAdapter;
LinearLayoutManager linearLayoutManager;
RecyclerView recyclerView;
Drawer result;
Toolbar toolbar;
Double lat, lng;
Location location;
SharedPreferences sharedPreferences, sharedPreferences1;
String name, password;
SpotsDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new SpotsDialog(this,"Loading...", R.style.Loading);
sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
sharedPreferences1 = getSharedPreferences("userDetails", Context.MODE_PRIVATE);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (networkEnabled) {
Log.d(TAG,"network is enabled"); //shows successfully
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
Log.d(TAG,"permission ******************granted"); //This log Tag Never appears in logcat
return;
}
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d(TAG, "Location is initialized"); //shows successfully
}
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Log.d(TAG, "getting latlng values"); //**Never shows
}else{ //******Always returning NULL HERE****
Toast.makeText(getBaseContext(),"location returning null",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
list = new ArrayList<>();
recentAdapter = new RecentAdapter(this, list);
recyclerView = (RecyclerView) findViewById(R.id.parkingRecyclerView);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(recentAdapter);
setUpDrawer();
init();
}
private void setUpDrawer() {
/*
final PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName("Home");
*/
final ProfileDrawerItem profile1 = new ProfileDrawerItem().withName("Najeeb Pasha").withEmail("Najeeb#gmail.com");
final PrimaryDrawerItem item1 = new PrimaryDrawerItem().withName("Search By Location");
final PrimaryDrawerItem profile = new PrimaryDrawerItem().withName("Your Profile");
final PrimaryDrawerItem logOut = new PrimaryDrawerItem().withName("Log Out");
final PrimaryDrawerItem gps = new PrimaryDrawerItem().withName("GPS");
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
return false;
}
})
.withCompactStyle(true)
.withHeaderBackground(R.color.drawer1)
.withCloseDrawerOnProfileListClick(true)
.withSelectionListEnabled(false)
.withTranslucentStatusBar(true)
.addProfiles(profile1)
.build();
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withSelectedItem(-1)
.withRootView(R.id.drawer_container)
.withDisplayBelowStatusBar(false)
.withActionBarDrawerToggleAnimated(true)
.withCloseOnClick(true)
.withAccountHeader(headerResult)
.addDrawerItems(
item1,
profile,
logOut,
gps,
new SectionDrawerItem().withName("Others")
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem == item1) {
startActivity(new Intent(getApplicationContext(), MapsActivity.class)
.putExtra("url", Constants.getPlaceUrl(lat,lng)));
} else if (drawerItem == logOut) {
logOut();
} else if (drawerItem == profile) {
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}else if (drawerItem == gps) {
startActivity(new Intent(getApplicationContext(), GpsActivity.class));
}
return false;
}
})
.build();
}
private void logOut() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
SharedPreferences.Editor editor1 = sharedPreferences1.edit();
editor1.clear();
editor1.apply();
recreate();
Intent intent = new Intent(MainActivity.this, SignInActivity.class);
MainActivity.this.startActivity(intent);
}
public void init() {
new Load().execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private class Load extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
dialog.show();
}
protected Void doInBackground(Void... params) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
System.out.println(Constants.getPlaceUrl(lat,lng));
Request request = new Request.Builder()
/*.url("http://192.168.0.101/parking/place.php?lat=17.308531&lng=78.5364463")*/
.url(Constants.getPlaceUrl(lat,lng))
.build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
System.out.println(responseData);
JSONArray jsonArray = new JSONArray(responseData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
RecentData data = new RecentData(
jsonObject.getString("name"),
jsonObject.getString("address"),
jsonObject.getString("lat"),
jsonObject.getString("lng"),
jsonObject.getString("distance"),
jsonObject.getString("filled"),
jsonObject.getString("total"),
jsonObject.getString("service"));
list.add(data);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid) {
dialog.hide();
recentAdapter.notifyDataSetChanged();
}
}
this always returning null please help me from the scratch i dont know how to solve it and iam very very new to android and this is my college homewwork project iam unable to get the loation even with gps or net provider . **please help me with this only this thing then my project will get complete.
Returning location as Null
Iam a Newbie;
please reply me the whole code with change please.request(Noob)
Thank u very much sir
In order to get locations, you need to ask for location updates by using the method requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener) on the location manager.
create a listener that will print the data, for example :
requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, new LocationListener(){
#Override
public void onLocationChanged(Location location){
Log.d("LOCATION", location.toString());
}
});
This will ask the location manager to provide me every 1000 ms (1s) and if i moved 10m from the last location a new location.
Whats the best way to get the getCoordinates method to run, once you return from the intent that was used in order to turn the location on. When you backpress once you have turned the location on, what happens in the activity lifecylce and where would be the best place to then call the getCoordinates method once you have returned from turning the location on, or even to first check if the location is on and only if it is then run getCoordinates method?
checkLocationOn
public void checkLocationOn () {
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setCancelable(false);
dialog.setTitle("Location Needed");
dialog.setMessage("The devices location settings are not enabled, please enable it in order to use this application...");
dialog.setPositiveButton("Open Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
getCoordinates
public void getCoordinates() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != 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;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
latitude = Double.toString(lat);
longitude = Double.toString(lng);
SharedPreferences.Editor e = preferences.edit();
e.putString("myLats",latitude);
e.putString("myLngs",longitude);
e.commit();
}
});
}
onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.job_search_fragment, container, false);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
checkLocationOn();
getCoordinates();
//Please help here
return v;
}
Override onResume and call both checkLocationOn(); and getCoordinates(); from there.
If you are requesting continuous location updates, you can remove the request it in onPause method.
Thanks arsena, i just changed the checkLocationOn() to a boolean and then in the onResume() if the checkLocationOn() is true then i call the getCoordinate() like so.
public boolean checkLocationOn () {
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setCancelable(false);
dialog.setTitle("Location Needed");
dialog.setMessage("The devices location settings are not enabled, please enable it in order to use this application...");
dialog.setPositiveButton("Open Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
dialog.show();
return false;
}else{
return true;
}
}
then in onResume()
#Override
public void onResume() {
super.onResume();
if(checkLocationOn()){
getCoordinates();
}
}
its working now
My application was working perfectly then, after adding the following code LoginManager.getInstance().logOut(); to disconnect from the current facebook account (a developper acount), the ide showed that an error occurred while running the app, but the application launched anyway, but when trying to login, it crashed and now it's not logging in, it keeps crashing! even though I changed nothing except adding that line of code to the next activity to make the app disconnect in case the user want to logout!
here's my java code:
public class ConnexionActivity extends AppCompatActivity {
Button b_bb, b_back, ee, b_inscrp_formulaire, fb;
EditText tb_pseudo, tb_mdp;
int id;
String name, gender, email, birthday;
private LoginButton loginButton;
private CallbackManager callbackManager;
Profile profile;
//new try:
private AccessTokenTracker accessTokenTracker;
private Button customFacebookLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
/*List<String> permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");*/
setContentView(R.layout.activity_connexion);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
b_inscrp_formulaire = (Button) findViewById(R.id.b_inscrip_formulaire);
fb = (Button) findViewById(R.id.fb);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setText("");
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends", "user_birthday"));
//"user_photos", "email","user_birthday", "public_profile"
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
//getting the hash key
try {
PackageInfo info = getPackageManager().getPackageInfo(
"your.package",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
//2nd way to generate hash key (or get it)
try {
PackageInfo info = getPackageManager().getPackageInfo("your.package.name", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
b_bb = (Button) findViewById(R.id.b_bb);
b_back = (Button) findViewById(R.id.b_back);
tb_pseudo = (EditText) findViewById(R.id.textbox_pseudo);
tb_mdp = (EditText) findViewById(R.id.textbox_mdp);
/////////////
ee = (Button) findViewById(R.id.button);
////////////
b_bb.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
b_bb.setBackgroundResource(R.drawable.button_bb_selec);
break;
}
case MotionEvent.ACTION_UP: {
b_bb.setBackgroundResource(R.drawable.button_bb);
break;
}
}
return false;
}
});
b_bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isAuthorized()) {
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", tb_pseudo.getText().toString());
startActivity(menu_p);
} else {
openDialog();
}
}
});
b_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnexionActivity.this.finish();
}
});
ee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", "Easter");
startActivity(menu_p);
}
});
b_inscrp_formulaire.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu_p = new Intent(ConnexionActivity.this, InscriptionActivity.class);
startActivity(menu_p);
}
});
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(ConnexionActivity.this, Arrays.asList("user_photos", "email",
"user_birthday", "public_profile"));
profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", profile.getFirstName());
startActivity(menu_p);
Toast.makeText(getApplicationContext(), "Connecté : " + profile.getFirstName() + " " + profile.getLastName(), Toast.LENGTH_SHORT).show();
} else {
// user has not logged in
Toast.makeText(getApplicationContext(), "Non-Connecté : Erreur de connexion!!", Toast.LENGTH_SHORT).show();
}
}
});
//To log out of FB:
/*LoginManager.getInstance().logOut();*/
//TODO: check if the user is logged in or not
/* profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
} else {
// user has not logged in
}*/
}
private Boolean isAuthorized() {
if (tb_pseudo.getText().toString().equals("Admin")
&& tb_mdp.getText().toString().equals("0000")
) {
return true;
} else
return false;
}
public void openDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Mauvaise combinaison \"Pseudo\", \"Mot de passe\"");
alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
public void graphRequest(AccessToken token) {
GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Toast.makeText(getApplicationContext(), object.toString(), Toast.LENGTH_LONG).show();
}
});
Bundle b = new Bundle();
b.putString("fields", "id,email,first_name,last_name,picture.type(large)");
request.setParameters(b);
request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
I guess the problem was just in the IDE, something about indexation!! I closed and reopened the IDE and everything is working just fine.
I have following script to get Location using GoogleAPI. Working on My App is based on Location. When This Activity was opened, thanks to using GoogleAPI is got Location Known as Latitude and Longitude.
When MainActivity is opened, if Location turns on within Device Settings.(Android smart Phone).Location Knowledge is obtained as a successfully way and in MainActivity doesn't happen any Problems. Conversely, when Location Turns off on
my android device, while the Activity is started, I have error and App close with a message that called "Unfortunately The App has stopped".
How can I solve this problem? while The Activity is opening How to Control whether Location turns on or off.
thanks in advance for the whole help.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
, LocationListener , DialogInterface.OnClickListener {
public static final String KEY_LOC_ADD_URL = "http://xxxxxxxx/android_api/insertlocation.php";
public static final String KEY_LATITUDE = "enlem";
public static final String KEY_LONGITUDE = "boylam";
public static final String KEY_ID="id";
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location mevcutKonum;
private String[] seconds={"1","3","5","7","10"};
private String sonGuncellemeZamani;
private String employee_id;
private Long requestTime;
private TextView enlemTextView;
private TextView boylamTextView;
private TextView sonGuncellemeTextView;
private TextView employee_name;
private AlertDialog dialogSelectInternal;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enlemTextView = (TextView) findViewById(R.id.enlem);
boylamTextView = (TextView) findViewById(R.id.boylam);
sonGuncellemeTextView = (TextView) findViewById(R.id.guncellemezamani);
sonGuncellemeZamani = "";
employee_name= (TextView) findViewById(R.id.userName);
Intent intent = getIntent();
employee_name.setText("Welcome User " + intent.getStringExtra(Login_Activity.KEY_USERNAME));
employee_id=intent.getStringExtra(Login_Activity.KEY_ID);
buildGoogleApiClient();
selectRequestTimeDialog();
createLocationRequest();
}
protected void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void createLocationRequest() {
locationRequest = LocationRequest.create()
.setInterval(3000)
.setFastestInterval(1000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void updateUI() {
if (mevcutKonum != null) {
enlemTextView.setText(String.valueOf(mevcutKonum.getLatitude()));
boylamTextView.setText(String.valueOf(mevcutKonum.getLongitude()));
sonGuncellemeTextView.setText(sonGuncellemeZamani);
}
}
#Override
protected void onResume() {
super.onResume();
googleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (googleApiClient.isConnected()) {
stopLocationUpdates();
}
googleApiClient.disconnect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (mevcutKonum == null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mevcutKonum = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
try {
addLocationToUser(String.valueOf(mevcutKonum.getLatitude()),String.valueOf(mevcutKonum.getLongitude()),employee_id);
} catch (JSONException e) {
e.printStackTrace();
}
updateUI();
}
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mevcutKonum = location;
sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void addLocationToUser(final String latitude, final String longitude,final String id) throws JSONException {
StringRequest stringRequest = new StringRequest(Request.Method.POST, KEY_LOC_ADD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(KEY_LATITUDE,latitude);
params.put(KEY_LONGITUDE, longitude);
params.put(KEY_ID,id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void selectRequestTimeDialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Konumunuzu Güncellemek istediğiniz zaman aralığını seçiniz");
builder.setItems(seconds,this);
builder.setNegativeButton("Cancel", null);
dialogSelectInternal=builder.create();
dialogSelectInternal.show();
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
Above Code has worked when location only turns on
In your onCreate() , First check if your GPS is enabled in your device, if yes create location update, else go to Location Settings.
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createLocationRequest();
} else {
Toast.makeText(this, "Please enable your gps first.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent, 1);
}
On GPS -> HIGH ACCURACY selection:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 1) {
switch (requestCode) {
case 1:
createLocationRequest();
break;
}
}
}
Hope this helps.
I have provide a GPS reminder in my app, but when i enable my gps and return to my mainactivty, my gps reminder ask me again, again and a agin when i press the googlemaps button. It only works when I close the program and restart the app
This is my MainActivityClass.
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gps = new GPSTracker(MainActivity.this);
}
My button to googlemaps.
public void googlemaps(View view) {
if (gps.canGetLocation()) {
Intent intent = new Intent(this, GoogleMaps.class);
startActivity(intent);
} else {
gps.showSettingsAlert();
}
}
this is my GPS tracker class
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
public LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
} else {
this.canGetLocation = true;
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 10, 2000, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location loc) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
You need to retest if the GPS has been enabled after you show your dialog. From the looks of it, you set your canGetLocation variable once when you create the class (via a call to getLocation(). Adding a call to 'getLocation()inonResume()` should solve your problem. I would recommend breaking the logic to see if the GPS is enabled into its own method.