My GPS App Crashed After Setting Last Location - java

I'm currently doing a GPS App from FreeCodeCamp.Org Youtube Channel, "How to make A GPS Tracking App" https://www.youtube.com/watch?v=_xUcYfbtfsI&t=1774s . I did everything in the video, and the instructions, but every time I pressed the see way point list, it keep crashing. I need help to fix this. I dont know what's wrong with the code.
package com.example.gipies;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final int DEFAULT_UPDATE_INTERVAL = 30;
public static final int FAST_UPDATE_INTERVAL = 5;
public static final int PERMISSION_FINE_LOCATION = 99;
//Refrensi Element UI
TextView tv_lat, tv_lon, tv_altitude, tv_accuracy, tv_speed, tv_sensor, tv_updates, tv_address,tv_wayPointCounts;
Button btn_newWP, btn_showWayPointList,btn_showMap;
#SuppressLint("UseSwitchCompatOrMaterialCode")
Switch sw_locationupdates, sw_gps;
//Variable to Remember to Track
boolean updateOn = false;
//Current Locaton
Location currentLocation;
//List of Saved
List<Location> savedLocations;
//Location Request configs of FusedLocationProviderClient
LocationRequest locationRequest;
LocationCallback locationCallBack;
//Google API for Location Services
private FusedLocationProviderClient fusedLocationProviderClient;
Object FusedLocationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Nilai Variable UI
tv_lat = findViewById(R.id.tv_lat);
tv_lon = findViewById(R.id.tv_lon);
tv_altitude = findViewById(R.id.tv_altitude);
tv_accuracy = findViewById(R.id.tv_accuracy);
tv_speed = findViewById(R.id.tv_speed);
tv_sensor = findViewById(R.id.tv_sensor);
tv_updates = findViewById(R.id.tv_updates);
tv_address = findViewById(R.id.tv_address);
sw_gps = findViewById(R.id.sw_gps);
sw_locationupdates = findViewById(R.id.sw_locationsupdates);
btn_newWP = findViewById(R.id.btn_newWP);
btn_showWayPointList= findViewById(R.id.btn_showWayPointList);
btn_showMap = findViewById(R.id.btn_showMap);
tv_wayPointCounts = findViewById(R.id.tv_CountOfPoints);
FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
//Set all Properties of LR
locationRequest = new LocationRequest();
locationRequest.setInterval(1000 * DEFAULT_UPDATE_INTERVAL);
locationRequest.setFastestInterval(1000 * FAST_UPDATE_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationCallBack = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
//Save Location
Location location = locationResult.getLastLocation();
updateUIValues(location);
}
};
btn_newWP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//get GPS Location
// add New Location
MyApplication myApplication = (MyApplication)getApplicationContext();
savedLocations = myApplication.getMyLocations();
savedLocations.add(currentLocation);
}
});
btn_showWayPointList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, ShowSavedLocList.class);
startActivity(i);
}
});
btn_showMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,MapsActivity.class);
startActivity(i);
}
});
sw_gps.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if (sw_gps.isChecked()) {
//GPS Accurate
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
tv_sensor.setText("Using GPS Sensor");
} else {
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
tv_sensor.setText("Using WIFI");
}
}
});
sw_locationupdates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (sw_locationupdates.isChecked()) {
//Turned On Location Tracking
startLocationUpdates();
} else {
//Turned Off Tracking
stopLocationUpdates();
}
}
});
updateGPS();
}//END onCreate
#SuppressLint("SetTextI18n")
private void stopLocationUpdates() {
tv_updates.setText("Location is NOT Being Tracked");
tv_lat.setText("Not tracking");
tv_lon.setText("Not Tracking");
tv_speed.setText("Not Tracking");
tv_address.setText("Not Tracking");
tv_accuracy.setText("Not Tracking");
tv_altitude.setText("Not Tracking");
tv_sensor.setText("Not Tracking");
LocationCallback.FusedLocationProviderClient.RemoveLocationUpdates(locationCallBack);
}
#SuppressLint("SetTextI18n")
private void startLocationUpdates() {
tv_updates.setText("Location is Being Tracked");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
FusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallBack, null);
updateGPS();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSION_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
updateGPS();
}
else{
Toast.makeText(this,"The APP Needs Permissions",Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void updateGPS(){
//Permissions, Current Location, Update UI
FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
FusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
updateUIValues(location);
Location currentLocation = location;
}
});
}
else {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
}
}
}
private void updateUIValues(Location location) {
//Update All Text with New Location
tv_lat.setText(String.valueOf(location.getLatitude()));
tv_lon.setText(String.valueOf(location.getLongitude()));
tv_accuracy.setText(String.valueOf(location.getAccuracy()));
if(location.hasAltitude()){
tv_altitude.setText(String.valueOf(location.getAltitude()));
}
else{
tv_altitude.setText("Not Available");
}
if (location.hasSpeed()){
tv_speed.setText(String.valueOf(location.getAltitude()));
}
else{
tv_speed.setText("Not Available");
}
Geocoder geocoder = new Geocoder(MainActivity.this);
try{
List<Address>addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
tv_address.setText(addresses.get(0).getAddressLine(0));
}
catch ( Exception e){
tv_address.setText("Unable to find");
}
MyApplication myApplication = (MyApplication)getApplicationContext();
savedLocations = myApplication.getMyLocations();
//Show Number of WPs
tv_wayPointCounts.setText(Integer.toString(savedLocations.size()));
}
}
in MainActivity.Java
it said
Cannot Resolve symbol 'FusedLocationProviderClient'
Cannot resolve method 'requestLocationUpdates' in 'Object'
Cannot resolve method 'getLastLocation' in 'Object'

Related

Waiting for the text optional module to be downloaded. Please wait. On Android Studio

I'm a new android developer and trying to make image to text app. I watched some tutorials and pretty sure that i don't make any mistakes. I'm using ML Kit for this project and got error when i tried to convert the image to text.
My main activity
package com.gorkemtand.textrecognition;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.latin.TextRecognizerOptions;
import java.io.IOException;
import java.security.Permission;
public class MainActivity extends AppCompatActivity {
private MaterialButton inputImageBtn;
private MaterialButton recognizeTextBtn;
private ShapeableImageView imageIv;
private EditText recognizedTextEt;
private static final String TAG = "MAIN_TAG";
private Uri imageUri = null;
//to handle the result of Camere/Gallery permissions
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 101;
//arrays of permission required to pick image from Camera,gallery
private String[] cameraPermissions;
private String[] storagePermissions;
private ProgressDialog progressDialog;
private TextRecognizer textRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputImageBtn = findViewById(R.id.inputImageBtn);
recognizeTextBtn = findViewById(R.id.recognizeBtn);
imageIv = findViewById(R.id.imageIv);
recognizedTextEt = findViewById(R.id.recognizedTextEd);
cameraPermissions = new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please Wait");
progressDialog.setCanceledOnTouchOutside(false);
textRecognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
inputImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showInputImageDialog();
}
});
recognizeTextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imageUri == null){
Toast.makeText(MainActivity.this,"Pick image first...",Toast.LENGTH_SHORT).show();
}
else {
recognizeTextFromImage();
}
}
});
}
private void recognizeTextFromImage() {
Log.d(TAG, "recognizeTextFromImage: ");
progressDialog.setMessage("Preparing image...");
progressDialog.show();
try {
InputImage inputImage = InputImage.fromFilePath(this,imageUri);
progressDialog.setMessage("Recognizing text...");
Task<Text> textTaskResult = textRecognizer.process(inputImage).addOnSuccessListener(new OnSuccessListener<Text>() {
#Override
public void onSuccess(Text text) {
progressDialog.dismiss();
String recognizedText = text.getText();
Log.d(TAG, "onSuccess: recognizedText: "+recognizedText);
recognizedTextEt.setText(recognizedText);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Log.e(TAG, "onFailure: ",e);
Toast.makeText(MainActivity.this,"Failed recognizing text due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
progressDialog.dismiss();
Log.e(TAG, "recognizeTextFromImage: ",e);
Toast.makeText(MainActivity.this,"Failed preparing image due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
private void showInputImageDialog() {
PopupMenu popupMenu = new PopupMenu(this, inputImageBtn);
popupMenu.getMenu().add(Menu.NONE,1,1,"CAMERA");
popupMenu.getMenu().add(Menu.NONE,2,2,"GALLERY");
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if(id == 1){
Log.d(TAG, "onMenuItemClick: Camera Clicked...");
if(checkCameraPermissions()){
pickImageCamera();
}
else{
requestCameraPermissions();
}
}
else if(id == 2){
Log.d(TAG, "onMenuItemClick: Gallery Clicked...");
if(checkStoragePermision()){
pickImageGallery();
}
else{
requestStoragePermission();
}
}
return false;
}
});
}
private void pickImageGallery(){
Log.d(TAG, "pickImageGallery: ");
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
galleryActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> galleryActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
//image picked
Intent data = result.getData();
imageUri = data.getData();
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
//set to imageview
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled...",Toast.LENGTH_SHORT).show();
}
}
}
);
private void pickImageCamera(){
Log.d(TAG, "pickImageCamera: ");
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Sample Title");
values.put(MediaStore.Images.Media.DESCRIPTION, "Sample Description");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
cameraActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> cameraActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
);
private boolean checkStoragePermision(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission(){
ActivityCompat.requestPermissions(this,storagePermissions,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermissions(){
boolean cameraResult = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean storafeResult = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return cameraResult && storafeResult;
}
private void requestCameraPermissions(){
ActivityCompat.requestPermissions(this,cameraPermissions, CAMERA_REQUEST_CODE);
}
//handle permission results
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && storageAccepted){
pickImageCamera();
}
else {
Toast.makeText(this, "Camera && Storage permissions are required", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(this,"Cancelled",Toast.LENGTH_SHORT).show();
}
}
break;
case STORAGE_REQUEST_CODE:{
if(grantResults.length>0){
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (storageAccepted) {
pickImageGallery();
}
else {
Toast.makeText(this, "Storage permission is required", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
}
Also i implemented these two
implementation 'com.google.android.gms:play-services-mlkit-text-recognition:18.0.2'
implementation 'com.google.android.gms:play-services-mlkit-text-recognition-common:18.0.0'
And give the permissions to manifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the error i got:
Error
I searched the google and cnat find a solution. If u can help me i will be very happy.
I searched google and can't find anything works.
I solved by implementing com.google.mlkit:text-recognition:16.0.0-beta6
Are you testing on device without play store services? For example on an emulator? In order to use com.google.android.gms:play-services-mlkit-text-recognition:18.0.2 it has to be on a device with play store services.

How to make BLE scan and MQTT publish work in background Android Studio Java

I want make some project where Android can scan nearby Beacon/BLE and send it using MQTT. But I want the service to work in the background if the service work in the foreground it will interrupt the scanning process when screen is off.
This is my code for scanning:
package com.example.mqtt_active;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.nio.charset.StandardCharsets;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
Log.d("Logger", "On Create Android");
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
Log.d("Logger", "State Check");
handler.postDelayed(this, 1000);
}
}, 1000);
// final Handler handlerStop = new Handler();
// handlerStop.postDelayed(new Runnable() {
// #Override
// public void run() {
// bluetoothAdapter.cancelDiscovery();
// Log.d("Logger", "Cancel Dsicovery");
// handlerStop.postDelayed(this, 2000);
// }
// }, 2000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
Log.d("Logger", "Turn On State");
// if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
// if(checkCoarsePermission()){
// bluetoothAdapter.startDiscovery();
// }
// }
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Try ");
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Logger", "Connect MQTT");
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d("Logger", "Connect Failed");
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
Log.d("Logger", "error"+e);
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
// bluetoothAdapter.cancelDiscovery();
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
if(checkCoarsePermission()){
Log.d("Logger", "Discover");
bluetoothAdapter.startDiscovery();
}
}
}
// else {
// Log.d("Logger", "Cancel");
// bluetoothAdapter.cancelDiscovery();
// }
}
private boolean checkCoarsePermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
return false;
}else {
return true;
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String RSSI = String.valueOf(rssi);
Toast.makeText(context.getApplicationContext(),"rssi "+RSSI+" "+device.getAddress(),Toast.LENGTH_SHORT).show();
Log.d("Logger", "Recive data "+device.getAddress());
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Sending data");
String payload = "rssi:"+RSSI+"mac:"+device.getAddress();
client.publish("test",payload.getBytes(),0,false);
} catch ( MqttException e) {
e.printStackTrace();
Log.d("Logger", "Error Sending "+e);
}}
}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_ACCESS_COARSE_LOCATION:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"ALLOWED", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"Forbidden",Toast.LENGTH_SHORT).show();
} break;
}
}
}
App Flow:
Insert MQTT server, port, id, topic.
Turn on the proccess.
Android scan BLE/Beacon
Android sending MAC/RSSI to MQTT
I hope someone can help to guide me, on how to make the application run in the background?
I'm a beginner, and I don't understand how to implement background service in my application. Please help me!
You need to implement a foreground service that will handle your ble scanning and MQTT logic.
See this article with an overview of how to do it. Depending on your build/target SDK, the implementation will vary.

Get current user location- Android

I know there are a lot of examples on the internet about this subject but my problem isn't the code, is the part where I get the location. The FusedLocationProviderClient.getLastLocation() always returns null when I don't open Google Maps before. To get my current location I have to open google maps to get my current location and after that my app can know the location. My question is: is there a way to track my current location without opening google maps before? Here is what I tried:
package com.example.gps;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final int DEFAULT_UPDATE_INTERVAL = 30;
public static final int FAST_UPDATE_INTERVAL = 5;
public static final int PERMISSIONS_FINE_LOCATION = 99;
TextView tv_lat, tv_lon, tv_altitude,
tv_accuracy, tv_speed, tv_sensor, tv_updates, tv_address;
Switch sw_locationupdates, sw_gps;
// Google API for location services.
FusedLocationProviderClient fusedLocationProviderClient;
// Location request config file for all settings related to FusedLocationProviderClient
LocationRequest locationRequest;
LocationCallback locationCallBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_lat = findViewById(R.id.tv_lat);
tv_lon = findViewById(R.id.tv_lon);
tv_altitude = findViewById(R.id.tv_altitude);
tv_accuracy = findViewById(R.id.tv_accuracy);
tv_speed = findViewById(R.id.tv_speed);
tv_sensor = findViewById(R.id.tv_sensor);
tv_updates = findViewById(R.id.tv_updates);
tv_address = findViewById(R.id.tv_address);
sw_gps = findViewById(R.id.sw_gps);
sw_locationupdates = findViewById(R.id.sw_locationsupdates);
locationRequest = new LocationRequest();
locationRequest.setInterval(1000 * DEFAULT_UPDATE_INTERVAL);
locationRequest.setFastestInterval(1000 * FAST_UPDATE_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationCallBack = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
updateUIValues(locationResult.getLastLocation());
}
};
sw_locationupdates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sw_locationupdates.isChecked()) {
startLocationUpdates();
} else {
stopLocationUpdates();
}
}
});
sw_gps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sw_gps.isChecked()) {
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
String text = "Using GPS sensors";
tv_sensor.setText(text);
} else {
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
String text = "Using Towers + WIFi";
tv_sensor.setText(text);
}
}
});
updateGPS();
}// end onCreate
private void stopLocationUpdates() {
String text = "Location is NOT being tracked";
tv_updates.setText(text);
Toast.makeText(this, "done", Toast.LENGTH_SHORT).show();
fusedLocationProviderClient.removeLocationUpdates(locationCallBack);
}
private void startLocationUpdates() {
String text = "Location is being tracked";
tv_updates.setText(text);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "a", Toast.LENGTH_SHORT).show();
// 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.
// requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
// Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_FINE_LOCATION);
// return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallBack, null);
updateGPS();
Toast.makeText(this, "tracking again", Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSIONS_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
updateGPS();
} else {
Toast.makeText(this, "This app requires permission to be granted in order to work properly", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void updateGPS() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
updateUIValues(location);
}
});
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSIONS_FINE_LOCATION);
}
}
}
private void updateUIValues(Location location) {
if (location != null) {
tv_lat.setText(String.valueOf(location.getLatitude()));
tv_lon.setText(String.valueOf(location.getLongitude()));
tv_accuracy.setText(String.valueOf(location.getAccuracy()));
if (location.hasAltitude()) {
tv_altitude.setText(String.valueOf(location.getAltitude()));
} else {
String text = "Not available- altitude";
tv_altitude.setText(text);
}
if (location.hasSpeed()) {
tv_speed.setText(String.valueOf(location.getSpeed()));
} else {
String text = "Not available- speed";
tv_speed.setText(text);
}
Geocoder geocoder = new Geocoder(MainActivity.this);
try {
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
tv_address.setText(addressList.get(0).getAddressLine(0));
} catch (IOException e) {
String text = "geocode didnt work";
tv_address.setText(text);
e.printStackTrace();
}
} else {
Toast.makeText(this, "the gps doesnt work", Toast.LENGTH_SHORT).show();
}
}
}
This code will retrieve my current location and update the name of the location but it will only work if I open google maps, close google maps and launch my app, it will work. Maybe this is the only way to make it work? But I wonder how other apps can track my location without opening google maps before.
yes, you can do it using its fused location provider also...without a map...
These code work without map I Hope You have apply runtime permission code
also apply for permission in the android manifest check it...
follow these URL - https://javapapers.com/android/android-location-fused-provider/
public class HomeFragment extends Fragment implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient googleApiClient;
LocationRequest locationRequest;
Location mCurrentLocation;
private static final long INTERVAL = 1000;
private static final long FASTEST_INTERVAL = 1000;
private int Play_SERVICES_RESOLUTION_REQUEST = 11;
FragmentHomeBinding binding;
AddressListDialogBinding dialogBinding;
AddressInterface anInterface;
FirebaseFirestore firebaseFirestore;
BottomSheetDialog dialog;
public HomeFragment() {
}
protected void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
LayoutInflater layoutInflater = getLayoutInflater();
binding = FragmentHomeBinding.inflate(layoutInflater);
View view = binding.getRoot();
setHasOptionsMenu(true);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
if (!isGooglePlayServicesAvailable()) {
}
createLocationRequest();
anInterface = this;
// setAddress();
googleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
public void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
googleApiClient.disconnect();
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
return false;
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
Log.d("LocationUpdate", "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(#NonNull int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
updateUI();
}
private void updateUI() {
if (mCurrentLocation != null) {
Log.e("getLocation", "updateUI: " + mCurrentLocation.getLatitude() + ":" + mCurrentLocation.getLongitude());
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(), 1);
String address = addresses.get(0).getAddressLine(0);
binding.tvCurrentLocation.setText(address);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onPause() {
super.onPause();
stopLocationUpdate();
}
protected void stopLocationUpdate() {
try {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
} catch (Exception e) {
Log.e("error", "stopLocationUpdate: " + e.toString());
}
}
#Override
public void onResume() {
super.onResume();
if (googleApiClient.isConnected()) {
startLocationUpdates();
}
}
}

Android: FusedLocationProvider, get location every few seconds

I'm making an app that tracks the user's location and ultimatly uploads it to a Firebase server.
I have created a simple app that displays the location when I press a button on screen. The problem is that it doesnt change the location when I press it again after I walked a few meters (I do get a new location when I re-enter the app though). What do I need to add in order for the app to update the location every X seconds? This is my activity:
package com.example.gpstest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
client = LocationServices.getFusedLocationProviderClient(this);
Button button = findViewById(R.id.getLocation);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
return;
}
client.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
TextView lat = findViewById(R.id.location1);
TextView lon = findViewById(R.id.location2);
TextView alt = findViewById(R.id.location3);
lat.setText(Double.toString(location.getLatitude()));
lon.setText(Double.toString(location.getLongitude()));
alt.setText(Double.toString(location.getAltitude()));
}
}
});
}
});
}
private void requestPermission(){
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
}
}
Because you get the location from getLastLocation. For that you have to implement LocationCallback.
consider this link for more information
// implement these interface in your class
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener.
//than use this code
public void onConnected(Bundle bundle) {
Location mLastLocation = null;
if (mGoogleApiClient.isConnected()) {
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
// 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 precise.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000); //5 seconds
mLocationRequest.setFastestInterval(3000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
buildGoogleApiClient();
mGoogleApiClient.connect();
}
}

How to send location using sms? (fused location api)

I'm currently making an app for school.. my app functions specifically for sending users most accurate location via SMS. so I used fused location api ... but now I don't know how to incorporate the SMS manager on my current app ... at present I only built a simple app which shows the users current location by pressing a button
I just want help on how to incorporate SMS manager in my app.
I also want the message to be in a URL form plus the coordinates so that it will be easy for the receiver to track the user.
here is my code Main activity
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 2300;
TextView textView;
Button sosbtn;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
LocationCallback locationCallback;
#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) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
}
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
sosbtn = (Button) findViewById(R.id.sosbtn);
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
} else {
buildLocationRequest();
buildLocationCallBack();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
sosbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
});
}
}
private void buildLocationCallBack() {
locationCallback= new LocationCallback()
{
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
for(Location location:locationResult.getLocations())
textView.setText(String.valueOf(location.getLatitude())+"/"+String.valueOf(location.getLongitude()));
}
};
}
private void buildLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(3000);
locationRequest.setSmallestDisplacement(5);
}
}
your help will be greatly appreciated.
Here's an example, declare the location object as a private field and on the click of your button:
SmsManager smsManager = SmsManager.getDefault ();
String message = "My location: https://www.google.com/maps/#?api=1&map_action=map&center=" + location.getLatitude () + "," + location.getLongitude ();
String phoneNumber = "+1....";
smsManager.sendTextMessage (phoneNumber, null, message, null, null);
The above link should redirect your recipient to google maps.
SmsManager.sendTextMessage
Don't forget to add this permission in your manifest:
<uses-permission android:name="android.permission.SEND_SMS"/>
and request the send sms permission in runtime.

Categories