getSpeed() always 0 - java

It's a location tracking application.
I test it in home, so location doesn't change. To do that I change them manually by incrementing the latitude and longitude by 2 everytime. I see the location change in my phone everytime, but the speed is still always 0! I don't know if it's working because I haven't tried this method before. If someone did I would appreciate the help.
public class MainActivity extends AppCompatActivity {
private Button b;
private TextView t;
private LocationManager locationManager;
private LocationListener listener;
private static int a=2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.textView);
b = (Button) findViewById(R.id.button);
t.setText(""); t.setTextSize(16);
b.setText("Demarer");
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
//to change location manually
location.setLatitude(location.getLatitude()+a);
location.setLongitude(location.getLongitude()+a);
a=a+10;
System.out.println("\n\nlocation changed !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n");
//
Long id = new Long(1);
String rs = null;
String json = null;
//post
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
PostLocation pl = new PostLocation();
json = pl.bowlingJson(location.getLongitude(), location.getLatitude(),id);
//System.out.println(json);
rs = pl.post("http://192.168.1.50:8080/api/v1/locations", json);
}catch (IOException EX){ EX.printStackTrace();
}finally {
if (rs == null)
t.setText("\nID : " +id+"\nLongitude : "+ location.getLongitude() + "\nLatitude : " + location.getLatitude() +"\nVitesse : "+(location.getSpeed()*3600/1000)+"km/h\n\nnon envoyée" );
//t.setText(location.getLatitude()+" : "+location.getLongitude()+"\n"+oldLocation.getLatitude()+" : "+oldLocation.getLongitude());
else
{
t.setText("\nID : " +id+"\nLongitude : "+ location.getLongitude() + "\nLatitude : " + location.getLatitude() +"\nVitesse : "+(location.getSpeed()*3600/1000)+"km/h\n\nbien envoyée" );
}
}
}
#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;
}
// va pas executer si n y a pas de privilege un return existe avant
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
//noinspection MissingPermission
try{
locationManager.requestLocationUpdates(locationProvider, 1000, 0, listener);
}catch (SecurityException e){
}
}
});
}
}

Related

Can't create handler inside thread that has not called Looper.prepare() in AsyncTask

im trying to get the city using Geocoder that android have
its app we creating as homework.
I'm trying to do it inside a AsyncTask but i get the this exception:
Can't create handler inside thread that has not called Looper.prepare()
the AsyncTask code:
public class GeocoderTask extends AsyncTask<Void, Void, String> {
LocationManager locationManager;
Location location;
Context context;
String city;
public GeocoderTask(Context context) {
this.context = context;
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
#SuppressLint("MissingPermission")
#Override
protected String doInBackground(Void... voids) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
GeocoderTask.this.location = location;
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(GeocoderTask.this.location.getLatitude(), GeocoderTask.this.location.getLongitude(), 3);
city = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.getMessage();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
return city;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
FrgPersonInfo frgPersonInfo = new FrgPersonInfo();
System.out.println(s);
frgPersonInfo.saveUserToTable(s);
}
}
I'm calling the AsyncTask from fragment
the calling from the fragment:
view.findViewById(R.id.btnRegister).setOnClickListener(new View.OnClickListener() {
#SuppressLint("MissingPermission")
#Override
public void onClick(View v) {
checkPermissions();
GeocoderTask geocoderTask = new GeocoderTask(context);
geocoderTask.execute();
}
});
the method I'm calling in onPostExecute in the AsyncTask:
public void saveUserToTable(String city) {
String age = uAge.getText().toString();
String name = fName.getText().toString();
UserInfo userInfo = new UserInfo();
userInfo.setIsConnected(true);
userInfo.setUserImage(imageUrl);
userInfo.setAge(Integer.valueOf(age));
userInfo.setName(name);
userInfo.setCity(city);
Backendless.Data.of(UserInfo.class).save(userInfo, new AsyncCallback<UserInfo>() {
#Override
public void handleResponse(UserInfo response) {
System.out.println("Bitch, im here again!");
((TextView)parentView.findViewById(R.id.loginFrgBtn)).setTextColor(Color.BLUE);
((TextView)parentView.findViewById(R.id.registerFrgBtn)).setTextColor(Color.BLACK);
FragmentTransaction ft = fm.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
FrgLogin frgLogin = new FrgLogin();
ft.replace(R.id.container, frgLogin);
ft.commit();
TastyToast.makeText(context, "Welcome!", TastyToast.LENGTH_LONG, TastyToast.SUCCESS).show();
}
#Override
public void handleFault(BackendlessFault fault) {
TastyToast.makeText(context, fault.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
}
});
}
the checkPermission:
private void checkPermissions() {
List<String> neededPerms = new ArrayList<>();
int fineGpsPerm = context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
int coarseGpsPerm = context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
if (fineGpsPerm != PackageManager.PERMISSION_GRANTED || coarseGpsPerm != PackageManager.PERMISSION_GRANTED) {
neededPerms.add(Manifest.permission.ACCESS_FINE_LOCATION);
neededPerms.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (!neededPerms.isEmpty()) {
ActivityCompat.requestPermissions( getActivity(), neededPerms.toArray(new String[neededPerms.size()]), GPS_PERM_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case GPS_PERM_CODE:
if (grantResults[0] != PackageManager.PERMISSION_GRANTED|| grantResults[1] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Need to Allow perms First", Toast.LENGTH_SHORT).show();
checkPermissions();
}
break;
}
}
the fragment class:
public class FrgPersonInfo extends Fragment{
public static final int GPS_PERM_CODE = 103;
Context context;
EditText fName, uAge, uCity;
String imageUrl = "";
FragmentManager fm;
View parentView;
LocationManager locationManager;
Location location;
boolean isLocEnabled = false;
String cityAddress = "";
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
this.context = context;
System.out.println("in person onattach");
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#SuppressLint("MissingPermission")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//inflating the wanted fragmentView
View myView = inflater.inflate(R.layout.frg_person_info, container, false);
// init the fields
fName = myView.findViewById(R.id.fName);
uAge = myView.findViewById(R.id.userAge);
uCity = myView.findViewById(R.id.userCity);
fm = getActivity().getSupportFragmentManager();
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
return myView;
}
#SuppressLint("MissingPermission")
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
parentView = view.getRootView();
//creating a bundle so we can (in this case) get data
Bundle bundle = getArguments();
//use the get.. method to get data by key
// imageUrl = bundle.getString(FrgRegister.IMAGE_KEY);
checkPermissions();
if (isLocEnabled) {
} else {
Toast.makeText(context, "dont have perms", Toast.LENGTH_SHORT).show();
}
view.findViewById(R.id.btnRegister).setOnClickListener(new View.OnClickListener() {
#SuppressLint("MissingPermission")
#Override
public void onClick(View v) {
checkPermissions();
GeocoderTask geocoderTask = new GeocoderTask(context);
geocoderTask.getUpdate();
}
});
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDetach() {
super.onDetach();
this.fName = null;
this.uAge = null;
this.uCity = null;
this.fm = null;
this.imageUrl = null;
}
public void saveUserToTable(String city) {
String age = uAge.getText().toString();
String name = fName.getText().toString();
UserInfo userInfo = new UserInfo();
userInfo.setIsConnected(true);
userInfo.setUserImage(imageUrl);
userInfo.setAge(Integer.valueOf(age));
userInfo.setName(name);
userInfo.setCity(city);
Backendless.Data.of(UserInfo.class).save(userInfo, new AsyncCallback<UserInfo>() {
#Override
public void handleResponse(UserInfo response) {
System.out.println("Bitch, im here again!");
((TextView)parentView.findViewById(R.id.loginFrgBtn)).setTextColor(Color.BLUE);
((TextView)parentView.findViewById(R.id.registerFrgBtn)).setTextColor(Color.BLACK);
FragmentTransaction ft = fm.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
FrgLogin frgLogin = new FrgLogin();
ft.replace(R.id.container, frgLogin);
ft.commit();
TastyToast.makeText(context, "Welcome!", TastyToast.LENGTH_LONG, TastyToast.SUCCESS).show();
}
#Override
public void handleFault(BackendlessFault fault) {
TastyToast.makeText(context, fault.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
}
});
}
private void checkPermissions() {
List<String> neededPerms = new ArrayList<>();
int fineGpsPerm = context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
int coarseGpsPerm = context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
if (fineGpsPerm != PackageManager.PERMISSION_GRANTED || coarseGpsPerm != PackageManager.PERMISSION_GRANTED) {
neededPerms.add(Manifest.permission.ACCESS_FINE_LOCATION);
neededPerms.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (!neededPerms.isEmpty()) {
ActivityCompat.requestPermissions( getActivity(), neededPerms.toArray(new String[neededPerms.size()]), GPS_PERM_CODE);
} else {
isLocEnabled = true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case GPS_PERM_CODE:
if (grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
checkPermissions();
} else {
isLocEnabled = true;
}
break;
}
}
}
Create the locationListener to keep a reference to it.
Create a class to trigger the LocationUpdates
public class GeocoderTask {
LocationManager locationManager;
Location location;
Context context;
String city;
LocationListener locationListener = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
GeocoderTask.this.location = location;
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
FrgPersonInfo frgPersonInfo = new FrgPersonInfo();
System.out.println(city);
frgPersonInfo.saveUserToTable(s);
try {
addresses = geocoder.getFromLocation(GeocoderTask.this.location.getLatitude(), GeocoderTask.this.location.getLongitude(), 3);
city = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.getMessage();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
}
public GeocoderTask(Context context) {
this.context = context;
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
public void getUpdate(){
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,locationListener,null
}
You just have to create the class and use the locationListener to call the Function getUpdate, this will call the Update once. You could also use requestUpdates and create a function to remove the listener if you want more updates.
Asynctask is a Thread, which only executes the tasks which it should and doesn't need a Looper and though there is no Looper called for this Thread. The Locationlistener works different, than that, what you have tried. OnLocationchanged get's called as long as you don't stop the listener, but this is happening asynchronously and you can't just wait inside an asynctask for this to finish. You have to start the locationlistener from your Mainthread and whenever your Location gets changed the function onLocationChanged gets called. You could for example put your onPostExecution inside the locationlistener.
#Override
public void onLocationChanged(Location location) {
GeocoderTask.this.location = location;
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(GeocoderTask.this.location.getLatitude(), GeocoderTask.this.location.getLongitude(), 3);
city = addresses.get(0).getLocality();
FrgPersonInfo frgPersonInfo = new FrgPersonInfo();
System.out.println(city);
frgPersonInfo.saveUserToTable(s);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.getMessage();
}
}

Broadcast manager not working in Fragment

I have a BroadcastReceiver which is used to receive data from a BLE device. The same code is working fine in an Activity but not in Fragment.
Here is the code:
public class HomeFragment extends Fragment implements LocationListener {
Session session;
TextView textViewName;
TextView textViewSteps;
TextView textViewCalories;
TextView textViewDistance;
TextView textViewFimos;
ImageView imageViewInfo;
public static final String TAG = "StepCounter";
private UARTService mService = null;
private BluetoothDevice evolutionDevice = null;
private static final int UART_PROFILE_CONNECTED = 20;
private static final int UART_PROFILE_DISCONNECTED = 21;
private int mState = UART_PROFILE_DISCONNECTED;
MyDatabase myDatabase;
LocationManager service;
private LocationManager locationManager;
private String provider;
double latitude, longitude;
List<Byte> listBytes = new ArrayList<>();
int rowNumber = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_home, container, false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
init(view);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
service_init();
}
private void init(View view) {
session = new Session(getActivity());
myDatabase = new MyDatabase(getActivity());
service = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
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;
}
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
textViewName = view.findViewById(R.id.textViewName);
textViewSteps = view.findViewById(R.id.textViewSteps);
textViewCalories = view.findViewById(R.id.textViewCalories);
textViewDistance = view.findViewById(R.id.textViewDistance);
textViewFimos = view.findViewById(R.id.textViewFimos);
imageViewInfo = view.findViewById(R.id.imageViewInfo);
try {
textViewName.setText("Hi, " + session.getUser().getUser().getName());
} catch (Exception e) {
}
}
private void service_init() {
System.out.println("---->>>>");
Intent bindIntent = new Intent(getActivity().getApplicationContext(), UARTService.class);
getActivity().bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder rawBinder) {
mService = ((UARTService.LocalBinder) rawBinder).getService();
Log.d(TAG, "onServiceConnected mService= " + mService);
if (!mService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
getActivity().finish();
}
}
public void onServiceDisconnected(ComponentName classname) {
mService = null;
}
};
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(UARTService.ACTION_GATT_CONNECTED);
intentFilter.addAction(UARTService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(UARTService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(UARTService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(UARTService.DEVICE_DOES_NOT_SUPPORT_UART);
return intentFilter;
}
private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
final Intent mIntent = intent;
//*********************//
if (action.equals(UARTService.ACTION_GATT_CONNECTED)) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
System.out.println("------- Device Connected: " + evolutionDevice.getName() + " - " + evolutionDevice.getAddress());
mState = UART_PROFILE_CONNECTED;
}
});
}
//*********************//
if (action.equals(UARTService.ACTION_GATT_DISCONNECTED)) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
System.out.println("------- Device Disconnected");
mState = UART_PROFILE_DISCONNECTED;
mService.close();
evolutionDevice = null;
}
});
}
//*********************//
if (action.equals(UARTService.ACTION_GATT_SERVICES_DISCOVERED)) {
mService.enableTXNotification();
}
//*********************//
if (action.equals(UARTService.ACTION_DATA_AVAILABLE)) {
final byte[] txValue = intent.getByteArrayExtra(UARTService.EXTRA_DATA);
List<Byte> byteList = Bytes.asList(txValue);
combineArrays(byteList);
}
//*********************//
if (action.equals(UARTService.DEVICE_DOES_NOT_SUPPORT_UART)) {
System.out.println("------- Device doesn't support UART. Disconnecting");
mService.disconnect();
}
}
};
#Override
public void onResume() {
super.onResume();
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;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
Log.d(TAG, "onResume");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
try {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(UARTStatusChangeReceiver);
} catch (Exception ignore) {
Log.e(TAG, ignore.toString());
}
getActivity().unbindService(mServiceConnection);
mService.stopSelf();
mService = null;
}
The complete code in the same ay with a few changes in working fine in Activity. Any idea what might be the blocker.? Do I need to do something else in the fragment to receive the data from the Local Broadcast Manager.?
Please try this way :
Create class BroadcastHelper
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hossam";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
And in your fragment :
private Receiver receiver;
private boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "Test":
Toast.makeText(getActivity(), "message", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
}
And to send your broadcast this this code :
BroadcastHelper.sendInform(context, "Test");
Or if you want to send data with it use :
Intent intent = new Intent("intent");
intent.putExtra("desc", desc);
intent.putExtra("name", Local_name);
intent.putExtra("code", productCode);
BroadcastHelper.sendInform(getActivity(), "Test" , intent);
I have a fragment where I do something similar. I put my code to setup the service in onCreateView and have a register and unregister in onPause() and onResume. Works good for me.
Can you check modify register receiver in service_init()
as
getActivity().registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
and for unregisterer receiver
getActivity().unregisterReceiver(UARTStatusChangeReceiver);

Cannot run android app in background through service

I try to get current location when the app running in background, so I use service. However, the data does not change in background, the service does not work. I want to know the problem. Here is the code of the app.
MainActivity as follow:
public class MainActivity extends Activity {
Button btn_start;
private static final int REQUEST_PERMISSIONS = 100;
boolean boolean_permission;
TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality;
SharedPreferences mPref;
SharedPreferences.Editor medit;
Double latitude,longitude;
Geocoder geocoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
tv_address = (TextView) findViewById(R.id.tv_address);
tv_latitude = (TextView) findViewById(R.id.tv_latitude);
tv_longitude = (TextView) findViewById(R.id.tv_longitude);
tv_area = (TextView)findViewById(R.id.tv_area);
tv_locality = (TextView)findViewById(R.id.tv_locality);
geocoder = new Geocoder(this, Locale.getDefault());
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
medit = mPref.edit();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolean_permission) {
if (mPref.getString("service", "").matches("")) {
medit.putString("service", "service").commit();
Intent intent = new Intent(getApplicationContext(), GoogleService.class);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
});
fn_permission();
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = Double.valueOf(intent.getStringExtra("latitude"));
longitude = Double.valueOf(intent.getStringExtra("longitude"));
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
tv_area.setText(addresses.get(0).getAdminArea());
tv_locality.setText(stateName);
tv_address.setText(countryName);
} catch (IOException e1) {
e1.printStackTrace();
}
tv_latitude.setText(latitude+"");
tv_longitude.setText(longitude+"");
tv_address.getText();
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Service as follow:
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver =
"com.findmyelderly.findmyelderly.receiver";
Intent intent;
public GoogleService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
intent = new Intent(str_receiver);
// fn_getlocation();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable) {
} else {
if (isNetworkEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
if (isGPSEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
}
private class TimerTaskToGetLocation extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
fn_getlocation();
}
});
}
}
private void fn_update(Location location){
intent.putExtra("latutide",location.getLatitude()+"");
intent.putExtra("longitude",location.getLongitude()+"");
sendBroadcast(intent);
}
}
build.gradle as follow
.........
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.android.support:multidex:1.0.0'
AndroidManifest as follow
..........
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
.........
<service android:name=".GoogleService" android:exported="false" android:enabled="true"/>
</application>
</manifest>
I am very puzzled.
One thing you could try is to check the permissions of the app on the phone itself. I've found with my device (Android version 6.0.1) it's not enough to just add "uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> and
"uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />"
in the manifest, you have to grant permissions to the app manually on the device.
To do this, go to Settings > Apps > 'yourApp' > Permissions and slide across the bar to turn on Location for that app.
I'm new enough to Android apps myself so there may be a bigger problem in your case I'm not sure but worth a try anyway!

Get ride of 0.0 location using google locationManager

I am using google location to get the location based on the best provider, so i am running that on a service, the service is responsable to update location based on a defined distance and time.
Everything is working well when i update my location, but i wanna get ride of the 0.0 location, when i doesn't update the location i need to get the current location, or to use the lastknowlocation how can i do it using my code below?
public class MyService extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private final IBinder mBinder = new LocalBinder();
private Intent intent;
Context context;
Location mLastLocation;
public class LocalBinder extends Binder {
public MyService getServerInstance() {
return MyService.this;
}
}
public Location getLocation(){
return mLastLocation;
}
private class LocationListener implements android.location.LocationListener
{
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
context = getApplicationContext();
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
//mLastLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
//mLastLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
**main activity call of the service**
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askPermission();
}
public void nextAct(View view){
Intent i = new Intent(this,GpsGetCoordinates.class);
startActivity(i);
}
public static final int REQ_PERMISSION = 99;
private boolean checkPermission() {
// PEDE PERMISSÃO SE A MESMA AINDA NÃO TIVER SIDO CONCEDIDA
return (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED );
}
// PEDIDO DE PERMISSÃO
private void askPermission() {
ActivityCompat.requestPermissions(
this,
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
REQ_PERMISSION);
}
// VERIFICAÇÃO DA RESPOSTA DO UTILIZADOR AO PEDIDO DE PERMISSÃO
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull
String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch ( requestCode ) {
case REQ_PERMISSION: {
if ( grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED ){
Log.d("PERMISSAO","DADA");
startService(new Intent(this, MyService.class));
} else {
// PERMISSÃO NEGADA
Log.w("fail", "permissionsDenied()");
}
break;
}
}
}
public void onResume() {
super.onResume();
}
}
When you get a location that is !=0.0, store it in a variable, or in Shared Preferences, or anywhere else you want. Then the next time you get 0.0 from locationManager, just use the latest real value that you stored previously.

Save a double value from textView to a variable

I am making a geocoder-reverse geocoder.
The coordinates are generated in a textview which I want to further use in reverse geocoding.
The problem is that the app suddenly stops working when I try to save the contents of textview into the variable. LATITUDE = Double.parseDouble(t.getText().toString());
LATITUDE being the variable, t is the textView in which the coordinates are generated.
Is there any other way to save a double value from textView into a variable so that it can be used further.
If not, can this problem be solved.
Thanks in Advance :)
Here is my java code:
public class MainActivity extends Activity {
private Button b;
public TextView t;
public TextView u;
public TextView add;
private LocationManager locationManager;
private LocationListener listener;
public Button b2;
private EditText e;
double LATITUDE;
double LONGITUDE;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.textView);
u = (TextView) findViewById(R.id.textView3);
add = (TextView) findViewById(R.id.textView4);
b = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
e = (EditText) findViewById(R.id.editText);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number = e.getText().toString();
String loc = t.getText().toString();
String loc1 = u.getText().toString();
String loc2 = add.getText().toString();
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"+number));
sendIntent.putExtra("sms_body",loc+loc1+loc2);
try {
startActivity(sendIntent);
finish();
Log.i("Finished sending SMS...", "");
}
catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
"SMS failed, please try again later.", Toast.LENGTH_SHORT).show();
}
}
});
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
t.append("\n " + location.getLatitude());
u.append("\n " + location.getLongitude());
}
#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.
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps",15000,0, listener);
}
});
}
public void phone(View view) {
Intent i = new Intent(this,Main2Activity.class);
startActivity(i);
}
public void address(View view) {
LATITUDE = Double.parseDouble(t.getText().toString());
LONGITUDE = Double.parseDouble(u.getText().toString());
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String result;
try {
List<Address> addressList = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i));
}
sb.append("\n" + address.getLocality());
sb.append("\n" + address.getPostalCode());
sb.append("\n" + address.getCountryName());
result = sb.toString();
add.append(result);
}
}
catch (IOException e) {
}
}
}
You are appending new coordinated to the textView by the following line.
t.append("\n " + location.getLatitude())
So now when you read the textView t you get all the values separated by \n. Try to split this first so you will get an array of string. Then run a loop converting all the strings to double.
Here is an example of how you can split strings
String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
Why dont you put in a class level string array during appending in the textview. So clean and safe code.No risk of null pointer during spliting.

Categories