Android: How to deactivate GPS - java

'm working on an android app, and i'm quite new to the android development.
At the moment i have problems to find a way to deactivate the GPS on the device.
What i'm trying to do is to deactivate the GPS when the user clicks a button. As far as i know the only way to do is buy using removeUpdates method from the LocationManager. But my problem is atm that this method awaits the LocationListiner as a parameter. But i don't know how to get the LocationListiner :/
Here is my code:
The following code is part of the onCreate of my MainActivity
Button save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Startet die Abfrage der GPS Position
final LocationManager mLocMan = GetMyLocation();
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); //Read Update
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setTitle("GPS Signal");
alertDialog.setMessage("Some message");
alertDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
mLocMan.removeUpdates();
}
});
alertDialog.show();
}
});
private LocationManager GetMyLocation(){
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
GetLocation getMyLocation = new GetLocation();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, getMyLocation);
return locationManager;
}
Maybe someone has a hint for me. At the moment i have still some problems wrapping my head around the android system :/

You need to implement somewhere the LocationListener to be able of receive the updates via onLocationChanged(Location location).
And then, you juste have to locationManager.removeUpdates(MyLocationListener);
You can use the activity to implements the listener and then
locationManager.removeUpdates(this);
public class MyActivity extends Activity{
...
LocationManager manager;
GetLocation listener;
#Override
protected void onCreate() {
manager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
listener = new GetLocation();
#Override
protected void onResume() {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
#Override
protected void onPause() {
manager.removeUpdates(listener);
}

Related

Perform an Action when phone is shaked

I'm using shake-detector-librart to detect whether my phone is being shared or not. It is working fine, gives the exact results as needed in the background as well as while the application is opened. I need to perform any action when the phone is being shaken, but it isn't working for that.
Here's my code:
ShakeOptions options = new ShakeOptions()
.background(true)
.interval(1000)
.shakeCount(2)
.sensibility(3.0f);
this.shakeDetector = new ShakeDetector(options);
shakeDetector.start(this, new ShakeCallback() {
#Override
public void onShake() {
Toast.makeText(getApplicationContext(), "locationDetails", Toast.LENGTH_SHORT).show();
String msg_txt = "THis is a sammple sms";
String phoneNo = "03036018110";
System.out.println("jamoodgreat");
//sendSMS(phoneNo,msg_txt);
Log.d("event", "onShake");//this is not being printed
Toast.makeText(getApplicationContext(), "Jamshaid", Toast.LENGTH_LONG).show();//this toast is not being displayed as well.
}
});
}
I tested the following and it works fine (The Toast gets called/displayed).
public class MainActivity extends AppCompatActivity {
private ShakeDetector shakeDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ShakeOptions options = new ShakeOptions()
.background(true)
.interval(1000)
.shakeCount(2)
.sensibility(2.0f);
shakeDetector = new ShakeDetector(options).start(this, new ShakeCallback() {
#Override
public void onShake() {
Toast.makeText(MainActivity.this, "onShake", Toast.LENGTH_SHORT).show();
}
});
}
}
Even though it worked, I had to shake the device vigorously before it was picked up.

Saving Activity State when switching activities

I'm currently trying to create an activity, which should be creating a new TextView on my main activity, everytime a Button is clicked on the first activity. However, instead of creating a new TextView everytime the button is clicked, it just changes the values of the first created TextView, so that there is always only one TextView. Is there a way to make it so that my first activity will not only create one single textview?
Here's the code from my "NewSubjectActivity":
**public class NewSubjectActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_subject);
Button SaveBtn = findViewById(R.id.SaveBtn);
nsaSaveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Click();
}
});
}
protected void Click(){
Intent intent = new Intent(NewSubjectActivity.this, MainActivity.class);
Boolean createnewTextView = true;
intent.putExtra("createnewTextView",createnewTextView);
startActivity(intent);
}
}
And here's the (relevant) code from my MainActivity:
protected void ReceiveValue (){
//getting Extras
Intent nsareceivedvalues = getIntent();
boolean createTextView = false;
createTextView = nsareceivedvalues.getExtras().getBoolean("createnewTextView");
//declaring fixed Views
final LinearLayout mainLinearLayout = (LinearLayout)findViewById(R.id.mainLinearLayout);
//Params for TextView
RelativeLayout.LayoutParams Params = new RelativeLayout.LayoutParams(1000, 200);
Params.setMargins(0, 10, 0, 10);
while(createTextView) {
//creating a TextView
TextView newsubject = new TextView(MainActivity.this);
//applying values to the TextView
newsubject.setLayoutParams(Params);
newsubject.setGravity(CENTER);
newsubject.setBackgroundColor(Color.GRAY);
mainLinearLayout.addView(newsubject);
createTextView = false;
}
}
As I said, this only create one text view, everytime I press the button on my "NewSubjectActivity" I think this might be, because the previous text view is not saved and the MainActivity is reset everytime I switch between the activities.
Every help and advise is much appreciated <3
Maybe when you are going back to your main activity you should call to onBackPressed() function, so it will reset nothing at all. Here's the example in kotlin
val back_button:Button = findViewById(R.id.button2)
back_button.setOnClickListener { v -> run {
//Change activity
onBackPressed()
} }
in Java should be:
Button back_button = findViewById(R.id.button2);
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Change activity
onBackPressed()
}
});
Let's hope it works!

How to get the absolute current location of the device in android java

Perhaps I am misunderstanding, but all the articles i've found for locationmanager and locationlistener in android refer to the onLocationChanged() method.
I want to get the current position of the user, not when it's changed. Am I using the right method? The locationchanged listener is working, and in the emulator runs the method when I change the location.
My app workflow is this:
-> App gets request from server for location
-> locationservice starts and stays on for 5 seconds to get the location
-> locationservice saves the location to preferences
-> locationservice stops
-> messaging service sends location to server
is a location listener the right method? will it still work if the user does not change location?
here's my location service:
public class MyLocationService extends Service {
public LocationManager locationManager;
public LocationListener mLocationListener;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("MissingPermission")
public int onStartCommand(Intent intent, int flags, int startId){
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MyLocationService.this).edit();
editor.putString("latitude", Double.toString(location.getLatitude()));
editor.putString("longitude", Double.toString(location.getLongitude()));
editor.commit();
System.out.println("Location got changed");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
try {
locationManager.requestLocationUpdates(locationManager.getBestProvider(new Criteria(), true), 10000, 0, mLocationListener);
} catch (Exception e){
e.printStackTrace();
}
return START_STICKY;
}
}
but the location change is only registering when I do it as the service is open. How can I run that every time the service runs?
You will get the user's current position the first time LocationManager triggers LocationListener::onLocationChanged.
If you are interested only in the current location you can set up the LocationListener to receive the first location update and then stop.
public void onLocationChanged(Location location) {
// location gotten... store it somewhere
// and stop the location manager
locationManager.removeUpdates(this.locationListener);
}
Still, LocationListener::onLocationChanged will trigger depending on the criteria you have set to your LocationManager.
For instance:
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this.locationListener);
will not be limited by any criteria, it will continuously request location updates.
is a location listener the right method? will it still work if the user does not change location?
Yes

How to make a button permanently unclickable

I am making a log-in system on Android. And I want the register Button to be unclickable when it has been clicked. I am using this code:
final Button register = (Button) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register.setEnabled(false);
Intent register = new Intent(getApplicationContext(), register.class);
startActivity(register);
}
});
This is working great, but I want the Button to remain unclickable even when the application or phone has been restarted. Does anyone know a way to make the Button unclickable permanently even when the application has been shut down?
As I already said in the comments section something like this may work:
public class MyActivity extends Activity {
private static final String KEY_IS_BUTTON_CLICKABLE = "key_clickable";
#Override
public void onCreate(Bundle savedInstanceState) {
...
final Button register = (Button) findViewById(R.id.register);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean isClickable = sharedPreferences.getBoolean(KEY_IS_BUTTON_CLICKABLE, true);
register.setEnabled(isClickable);
if(isClickable) {
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register.setEnabled(false);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit()
.putBoolean(KEY_IS_BUTTON_CLICKABLE, false);
Intent register = new Intent(getApplicationContext(), register.class);
startActivity(register);
}
});
}
}
...
}
In this case you could take a pessimistic approach and disable the button in the layout (by default) with android:clickable="false" and enable it in the condition where registration is required.

I can't receive locations

I'm building a location based app, everything was fine until one day I stopped receiving locations.. I have no idea why. I will attach the important code:
private LocationManager mLocationManager;
public void onCreate()
{
super.onCreate();
...
// Get a reference to the LocationManager object.
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
...
setup();
}
private void setup()
{
mLocationManager.removeUpdates(listener);
// Request updates from just the providers.
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, ONE_MINUTE, 0, listener);
if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, ONE_MINUTE, 0, listener);
}
#Override
public void onLocationChanged(Location location)
{
handleLocation(location);
}
I put a break point on the onLocationChanged and nothing happened.. I tested it on other lines of my app to make sure that the debugging configuration is working and it is working. Looks like I just don't receive any locations.
Maybe I'm not seeing something.
I've good code to receive location :
public class Locato extends Activity implements LocationListener {
LocationManager locman;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.idlayout);
locman = (LocatonManager) getSystemService(Context.LOCATION_SERVICE);
}
public void onStatusChanged(String pr, int s, Bundle a) {
}
#Override public void onProviderDisabled(String provider)
{
Log.d("MyApp", "Provider disabled : " + provider);
}
#Override public void onProviderEnabled(String provider) {
Log.d("MyApp", "Provider enabled : " + provider);
}
#Override public void onLocationChanged(Location location) {
// do something
}
}
Try to use this.
Don't forget add ACCESS_FINE_LOCATION permission in manifest.
The same code now generates locations, it was kind of a joke when I said that it could be since it's cloudy but now when the clouds are gone it's working. I can't think about anything else and just to clarify it was very cloudy maybe even a small storm.

Categories

Resources