I have a service in which I need to run onLocationChanged. When I try to put the onLocationChanged method inside onStartCommand, it doesn't work. How can I set onLocationChanged to run when my service starts?
public class myService extends Service implements LocationListener {
Double lat;
Double lng;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
if (MainActivity.location != null) {
lat = MainActivity.location.getLatitude();
lng = MainActivity.location.getLongitude();
if (MainActivity.placeArrayList.size() != 0) {
for (int i = 0; i < MainActivity.placeArrayList.size(); i++) {
Log.e("hello", String.valueOf(Float.parseFloat(MainActivity.latitudeArrayList.get(i))));
MainActivity.destination.setLatitude(Double.parseDouble(MainActivity.latitudeArrayList.get(i)));
MainActivity.destination.setLongitude(Double.parseDouble(MainActivity.longitudeArrayList.get(i)));
Log.e("distancemeters", Stri ng.valueOf(MainActivity.location.distanceTo(MainActivity.destination)));
if (MainActivity.location.distanceTo(MainActivity.destination)<100) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI);
} else {
}
}
}
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Related
In my app, I get the coordinates of my device. Now I'm trying to make it so that when the device is within a radius of 10 meters, the method is called. Found the addProximityAlert method. But there you need to pass the coordinates of the point I need, but I do not know how to link the marker I need and the position of the device. I have already created a broadcastreceiver. Please help with advice or an article.
public void getlocate() {
if (flag) {
Intent intent = new Intent("com.runline.workertrack");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, -1, intent, 0);
try {
enable = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception e) {
e.printStackTrace();
}
if (enable) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 5, listener);
manager.addProximityAlert(0,0 , 100, -1, pendingIntent);
}
}
}
public boolean checkLocationPermission()
{
int loc1 = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listper = new ArrayList<>();
if(loc1 != PackageManager.PERMISSION_GRANTED)
listper.add(Manifest.permission.ACCESS_FINE_LOCATION);
if(!listper.isEmpty()) {
ActivityCompat.requestPermissions(this, listper.toArray(new String[listper.size()]), 1);
}
return true;
}
class Locate implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
manager.removeUpdates(listener);
shirota = "" + location.getLatitude();
dolgota = "" + location.getLongitude();
shir.setText(shirota);
dolg.setText(dolgota);
final Map<String, Object> hashMap = new HashMap<>();
hashMap.put("shirota", shirota);
hashMap.put("dolgota", dolgota);
hashMap.put("id", "1");
reference.setValue(hashMap);
IntentFilter filter = new IntentFilter("com.runline.workertrack");
registerReceiver(new ProximityIntentReceiver(), filter);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
public class ProximityIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive (Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if(entering){
Toast.makeText(getApplicationContext(), "You are here!", Toast.LENGTH_LONG).show();
}
}
}
When I come back after click the back button and I try to play music I have error 'java.lang.IllegalStateException' - but why..? I noticed that others method like player.isPlaying() or player.reset() didn't work too. If somebody had already this problem - please help. Nice day :)
java.lang.IllegalStateException
at android.media.MediaPlayer.prepareAsync(Native Method)
Activity class:
#Override
protected void onStart() {
super.onStart();
playIntent = new Intent(this, MediaPlayerService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
#Override
protected void onDestroy() {
super.onDestroy();
if(musicConnection!=null){
unbindService(musicConnection);
}
}
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MediaPlayerService.LocalBinder musicBinder = (MediaPlayerService.LocalBinder) service;
musicService = musicBinder.getService();
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
MusicService class:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.reset();
player.release();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onCreate() {
super.onCreate();
setSong(0);
player = new MediaPlayer();
initMediaPlayer();
}
public void initMediaPlayer(){
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void playSong(){
try{
player.reset();
Song playSong = songList.get(songPos);
long currSong = playSong.getId();
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
player.setDataSource(getApplicationContext(), trackUri);
}catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
I had to change the onDestroy method on:
#Override
protected void onDestroy() {
stopService(playIntent);
musicService = null;
super.onDestroy();
}
I want to detect the switch of GPS.
My idea is to use IntentService and Broadcast intent.
My service is running but my broadcast receiver doesn't work.
I just wanna say to my HomeActivity if GPS is turn on/off by user. With this info, i will able to set up my GoogleMap with the current location.
Thx !
GpsService.java :
public class GpsService extends IntentService implements LocationListener {
private final static String TAG = "com.example.smartoo.gpsservice";
public GpsService () {
super(TAG);
Log.e("TAG", "GPS service k");
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
if (LocationManager.GPS_PROVIDER.equals(provider)) {
Intent i = new Intent("android.location.PROVIDERS_CHANGED");
i.putExtra("enabled", 1);
sendBroadcast(i);
}
}
#Override
public void onProviderDisabled(String provider) {
if (LocationManager.GPS_PROVIDER.equals(provider)) {
Intent i = new Intent("android.location.PROVIDERS_CHANGED");
i.putExtra("disnabled", 1);
sendBroadcast(i);
}
}
#Override
protected void onHandleIntent(Intent intent) {
}
}
HomeActivity.java
public class HomeActivity extends ActionBarActivity implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
//My attrs
private GoogleMap mMap = null;
Location currentLocation;
/*
* Initialize the Activity
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
//Get the map from xml file
mMap = getMap();
Intent i = new Intent(HomeActivity.this, GpsService.class);
startService(i);
}
/*
* Called when the Activity is restarted, even before it becomes visible.
*/
#Override
public void onStart() {
super.onStart();
final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//Check if GPS is enable on device.
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
showGPSDisabledAlertToUser();
}
}
public class GpsLocationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
int extra = intent.getIntExtra("enabled", -1);
//If GPS not enabled
if(extra == -1) {
extra = intent.getIntExtra("disabled", -1);
//If GPS not disabled
if (extra == -1) {
//Nothing
}
//If GPS disabled
else {
//Do something
}
}
//If GPS enabled
else {
Toast.makeText(HomeActivity.this, "GPS enabled", Toast.LENGTH_LONG).show();
currentLocation = getLocation();
setUpMapIfNeeded();
}
Toast.makeText(HomeActivity.this, "in onREceive", Toast.LENGTH_LONG).show();
}
}
}
}
For an example, first add the following permission to your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Then, a simple Activity:
public class MainActivity extends Activity
{
private GpsStatusReceiver receiver = new GpsStatusReceiver();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume()
{
super.onResume();
registerReceiver(receiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}
#Override
protected void onPause()
{
super.onPause();
unregisterReceiver(receiver);
}
private class GpsStatusReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
LocationManager lm = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
boolean isEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
onGpsStatusChanged(isEnabled);
}
}
private void onGpsStatusChanged(boolean isEnabled)
{
// Do/start your work here.
Toast.makeText(this, "GPS enabled - " + isEnabled, 0).show();
}
}
I'm trying to do a service, who listen user's location.
Code bellow:
public class ServiceBeezer extends Service implements
OnConnectionFailedListener, ConnectionCallbacks {
private LocationRequest mLocationRequest;
private LocationClient mLocationClient;
public ServiceBeezer() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 1. init locationrequest
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_NO_POWER);
mLocationRequest.setFastestInterval(1000);
// 2. mlocationclient
mLocationClient = new LocationClient(this, this, this);
return START_STICKY;
}
#Override
public void onConnected(Bundle arg0) {
Toast.makeText(this,
getClass().getSimpleName() + "onConnected: " + arg0,
Toast.LENGTH_LONG).show();
}
#Override
public void onDisconnected() {
Toast.makeText(this, getClass().getSimpleName() + "onDisconnected: ",
Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
Toast.makeText(this,
getClass().getSimpleName() + "onConnectionFailed: " + arg0,
Toast.LENGTH_LONG).show();
}
}
But onConnected(), onDisconnected() and onConnectionFailed() is never called.
What I doing wrong?
I have other LocationRequest, and LocationClient inside on Activity.
Can be this the problem?
If I am not wrong you haven't called mLocationClient.connect() anywhere in the code you pasted above.
I'm having an issue stopping a service that I have started.
The service is called when the user logs in, and starts to track the user's location. This is working fine. The service is meant to stop when the user presses the logout button and is successfully logged out.
It's an android service that is being called through a JavaScript interface by a HTML button.
Here is my Main Class which contains the methods for starting and stopping the service:
public class CasesMain extends DroidGap {
Intent gpsTracking;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
appView.addJavascriptInterface(this, "StartGPS");
super.loadUrl(Config.getStartUrl());
}
public void startGPS(){
gpsTracking = new Intent(this, MyService.class);
startService(gpsTracking);
}
public void stopGPS(){
stopService( gpsTracking );
}
}
Here is the MyService class:
public class MyService extends Service {
private LocationManager locManager;
private LocationListener locListener = new myLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Handler handler = new Handler();
Thread t;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT)
.show();
final Runnable r = new Runnable() {
public void run() {
location();
handler.postDelayed(this, 10000);
}
};
handler.postDelayed(r, 10000);
return START_STICKY;
}
public void location() {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, locListener);
}
}
private class myLocationListener implements LocationListener {
double lat_old = 0.0;
double lon_old = 0.0;
double lat_new;
double lon_new;
#Override
public void onLocationChanged(Location location) {
if (location != null) {
locManager.removeUpdates(locListener);
lon_new = location.getLongitude();
lat_new = location.getLatitude();
String longitude = "Longitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
Log.v("Debug", "Latt: " + latitude + " Long: " + longitude);
Toast.makeText(getApplicationContext(),
longitude + "\n" + latitude, Toast.LENGTH_SHORT).show();
lat_old = lat_new;
lon_old = lon_new;
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
And here is my call to stop the service: window.StartGPS.stopGPS();
The start works perfectly, but when I log out, the app continues to show messages of the latt and long meaning the call to stopService() either didn't work or is not called.
Can anyone see where my mistake is or what is going wrong?
Any help would be greatly appreciated!
FIXED
Adding handler.removeCallbacksAndMessages(null); in the onDestroy() method of MyService fixed it for me.
Can anyone see where my mistake is or what is going wrong?
You have an empty onDestroy() method. You need to call removeCallbacks() on your Handler there.
If you are using any android.os.Handler in the service remember to call removeCallbacksAndMessages like this:
#Override
public void onDestroy() {
Toast.makeText(this, "service onDestroy", Toast.LENGTH_LONG).show();
Utils.cancelNotification(this);
customHandler.removeCallbacksAndMessages(null);
}
And the service will destroy successfully. It worked for me.
Here's what I would suggest
1) Put more log statements in calls leading to stopService.
2) Implement On ServiceConnection interface and see what's happening in OServiceConnected and onServiceDisconnected.