GPS location only onClick button - android

I've got problem. I need only one information about location. I want to click on my button, get location and stop GPS. But in my case it gives me informations about location every 5 seconds. It'S possible to make it work, how i want it? Because i want to save data about start of road in sqlite database. So i need only one information about location. Like my first idea, or the most simple thing i can do, was making the time interval larger than five seconds, something like 5 000 000 seconds. But it's not the best solution i think. :)
this is my code
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent dbmanager = new Intent(MainActivity.this, AndroidDatabaseManager.class);
startActivity(dbmanager);
}
});
locLIST = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
gps1.append("\n " + location.getLatitude() + " " + location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent1);
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.INTERNET
},10);
return;
}else{
configureButton();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case 10:
if (grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED)
configureButton();
return;
}
}
private void configureButton() {
buttonGPS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locman.requestLocationUpdates("gps", 0, 0, locLIST);
}
});
}

Related

When I press the button I want it to tell me my location (text to speech), how is this done? Android studio

I have a button and when I press it it show me in 2 TextView my location(in textview3 the X, and textview21 the Y) and I want to listen my location with text to speech. The problem is: The text to speech is not working right and it say my location in loop. It's read right the textviews but the text to speech say/repeats the Location all the time. It will stop the repeat when I close the program. I don't know how to fix it.
The code in MainActivity2 for Location
ImageButtonLoc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(MainActivity2.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity2.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQ_LOC_CODE);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MainActivity2.this);
//locationManager.removeUpdates(MainActivity.this);
}
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
// 0, 0, MainActivity.this);
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER., 0, 0 , MainActivity.this);
}
});
}
//energopoietai apo to kleisimou tou dangerous permissions
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQ_LOC_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MainActivity2.this);
}
}
#Override
public void onLocationChanged(#NonNull Location location) {
//sintetagmenes sto text
x=location.getLatitude();
y=location.getLongitude();
textView3.setText(String.format("Your current location is:X=%.2f",x));
textView21.setText(String.format(" and Y=%.2f",y));
textspeech.speak("Your current location is:"+"X="+String.format("%.2f",x)+","+"\n"+"Y="+String.format("%.2f",y));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(#NonNull String provider) {
}
#Override
public void onProviderDisabled(#NonNull String provider) {
}
And the activity:textspeech
public class textspeech {
private TextToSpeech tts;
TextToSpeech.OnInitListener initListener=new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS){
tts.setLanguage(Locale.US);
}
}
};
//prepei na ftiaksume constructor moni mas gt h mixani omilias dn
// mporei na energopoithi moni ths h klasi prepei na energopoiithoi apo contex
public textspeech(Context context){
tts=new TextToSpeech(context, initListener);
}
//methodos gia na tn kalume
public void speak(String message){
tts.speak(message,TextToSpeech.QUEUE_ADD, null,null);
}
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, MainActivity2.this);
As I understand it, you want to wait for a while before reading the second address after the first address is read, right? If you want to do this, you can read the first address and then wait for a while with the Handler and then start reading the second address.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
start Voice 2
}
}, 1000);

how to make the GPS function work normally when the app is running in the background

I'm doing a flutter project,my problem is:
how to make the GPS function work normally when the app is running in the background,i use Service,but only when the app is in the foreground can GPS get it.
this is my code:
#Override
public void onCreate()
{
//
startService();
Log.v(tag, "GPSService Started.");
}
#TargetApi(Build.VERSION_CODES.M)
public void startService()
{
boolean isOpen = isOPen();
if (isOpen) {
initLocation();
return;
}
}
#TargetApi(Build.VERSION_CODES.M)
private void initLocation() {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.mainThis, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
return;
}
if (network&&gps){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500,0, listener); // network locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 8, listener); // gps
}else if(network&&!gps){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500,8, listener); // n
}else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 8, listener); // g
}
}
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateShow(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#SuppressLint("MissingPermission")
#Override
public void onProviderEnabled(String provider) {
updateShow(locationManager.getLastKnownLocation(provider));
}
#Override
public void onProviderDisabled(String provider) {
updateShow(null);
}
};
The article below has the caption "How to fetch user location in background with Flutter".
With subtopics like this,
How to fetch a user location
How to fetch it even if the app is running in the background
The limitations of the system
https://medium.com/#pierre.sabot/how-to-fetch-user-location-in-background-with-flutter-e3494021bdf5

Not able to fetch location using GPS

I'm trying to make a simple app to show my location coordinates. When I emulate the code ( nexus 6.0 , it works). However, when I use a real device via usb debugging (my htc 10), nothing appears when I press the button to show my coordinates. Any idea why? This is my code:
//Location
textView = (TextView) findViewById(R.id.textView);
button2 = (Button) findViewById(R.id.button2);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
textView.append("\n " + location.getLongitude() + " " + location.getLatitude());
System.out.println(location.getLongitude());
System.out.println(location.getLatitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
configure_button();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case 10:
configure_button();
break;
default:
break;
}
}
void configure_button() {
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
, 10);
}
return;
}
// this code won't execute IF permissions are not allowed, because in the line above there is return statement.
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
});
}
I have this added in my manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
You should declare the button2 click listener in oncreate as there is return statement in configure_button() method.
Just declare it right after declaring ids.
textView = (TextView) findViewById(R.id.textView);
button2 = (Button) findViewById(R.id.button2);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
});
//rest of the code

Getting error on button click to fetch location

The error I get is as follows
Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Please tell me where I'm going wrong
Activity onCreate function
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mbutton=(Button)findViewById(R.id.partymb);
textview=(TextView)findViewById(R.id.tv);
setContentView(R.layout.activity_menuact);
locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationlistener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
textview.append("\n "+location.getLongitude() +" "+location.getLatitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
},10);
return;
}
} else {
configureButton();
}
}
onRequestPermissionResult function
public void onRequestPermissionResult(int requestCode, String[] permission, int[] grantResults) {
switch (requestCode){
case 10:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
configureButton();
return;
}
}
ConfigureButton function
private void configureButton() {
mbutton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
locationmanager.requestLocationUpdates("gps", 5000, 5, locationlistener);
}
});
}
I took reference from here
setContentView(R.layout.activity_menuact);
Above line should come immediately after super.onCreate(savedInstanceState);
And after that do findViewById.
You are finding views before setting a view so all views will be null only.
you are setting view and id before
setContentView(R.layout.activity_menuact);
you should set like below
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menuact);
mbutton=(Button)findViewById(R.id.partymb);
textview=(TextView)findViewById(R.id.tv);
}

I want to send users location via sms in android

I am trying to send users location via sms. I can get the users location but it takes lot time while the smsmanager sends the message with null value of location can somebody see my code or guide me what is wrong here. thanks!
public class MainActivity extends AppCompatActivity {
public Button button;
private LocationManager locationManager;
private LocationListener listener;
private String gpslonla;
private TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getlocation();
sendlocationsms();
}
private void sendlocationsms() {
String phoneNumber = "903399000";
//Location location = new Location("dummyprovider");
SmsManager smsManager = SmsManager.getDefault();
StringBuffer smsBody = new StringBuffer();
smsBody.append("http://maps.google.com?q="+gpslonla);
//smsBody.append(location.getLatitude());
//smsBody.append(",");
//smsBody.append(location.getLongitude());
smsManager.sendTextMessage(phoneNumber, null, smsBody.toString(), null, null);
int gravity = Gravity.CENTER; // the position of toast
int xOffset = 0; // horizontal offset from current gravity
int yOffset = 0; // vertical offset from current gravity
Toast toast = Toast.makeText(getApplicationContext(), "Your message has been sent ", Toast.LENGTH_SHORT);
toast.setMargin(50, 50);
toast.setGravity(gravity, xOffset, yOffset);
toast.show();
}
});
}
private void getlocation() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
gpslonla=location.getLongitude() + "," + location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
configure_button();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10:
configure_button();
break;
default:
break;
}
}
void configure_button() {
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
, 10);
}
return;
}
// this code won't execute IF permissions are not allowed, because in the line above there is return statement.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
});
}
}
You must call the sendlocationsms() method when the location is received. Change your onClick method with:
EDITED:
Declare a boolean variable with initial value to false:
boolean needsToSendSms = false;
Then:
#Override
public void onClick(View view) {
needsToSendSms = true;
getlocation();
}
And call it when the location changes with
#Override
public void onLocationChanged(Location location) {
gpslonla=location.getLongitude() + "," + location.getLatitude();
if(needsToSendSms) {
sendlocationsms();
needsToSendSms = false;
}
}
Adding the boolean variable makes to only send one sms per click.
I hope this helps.

Categories

Resources