What should i do to turn off the gps if location is not found at 1st instance..without location update being called
package mobile.sales;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
public class test extends Activity
{
DataSource dataSource;
Double lat=0.0,lng=0.0;
String GPS_FILTER = "";
Thread triggerService;
LocationListener locationListener;
LocationManager lm;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1000; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 29*1000*60; // in Milliseconds
protected LocationManager locationManager;
boolean isRunning = true;
NotificationManager notificationManager;
PendingIntent contentIntent;
Notification notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
turnGPSOn();
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
locationManager.removeUpdates(locationListener);
locationManager= null;
turnGPSOnOff();
super.onDestroy();
// removeGpsListener();
}
private class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location location)
{
lat=location.getLatitude();
lng=location.getLongitude();
turnGPSOnOff();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String currentDateandTime = sdf.format(new Date());
SimpleDateFormat sdft = new SimpleDateFormat("hh:mm:ss");
String time=sdft.format(new Date());
dataSource.insertIntoLocationDetails(""+lat,""+lng,currentDateandTime,""+time);
Log.d("service","location Inserted");
}
public void onStatusChanged(String s, int i, Bundle b) {
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
}
private void turnGPSOnOff(){
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
}
private void turnGPSOn(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){
final Intent poke = new Intent();
poke.setClassName("com.android.settings","com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
}
You are calling the function when you are trying to DESTROY The activity itself. First find the Fix of GPS using GPSStatusListener
Use this code
Check Gps Status
Call your GpsTurnOff status in GPSStatusListener
new Handler().postDelayed(new Runnable() {
#Override
public void run()
{
turnGPSOnOff();
}
}, 2000*60);
this will turnoff my gps after certain time
Related
I am trying to create an android program to get the location
but unfortunately its throwing the exception as unfortunately APP is stopped
Can you suggest me please .code is the following
package com.example.ngo;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to"+
" see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----Method to Check GPS is enable or disable ----- */
#SuppressLint("NewApi") private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
RESOLVED
Singleton pattern was suggested. Not the most elegant way to solve the problem but it works. Here is the code I used. Just have to get the instance in the main and LocationService class to use. See answer for how you are suppose to do it.
import android.location.Location;
public class LocationSingleton {
private Location location;
private static LocationSingleton singleton = new LocationSingleton();
private LocationSingleton(){
}
public static LocationSingleton getInstance( ) {
return singleton;
}
protected void setLocation(Location newLocation) {
this.location = newLocation;
}
protected Location getLocation(){
return this.location;
}
}
Attempting to use a background service to handle Location updates. I create a service in Main that updates the data (working correctly I believe) but I also have a button in main that whenever pressed does some work with the location data. I can't figure out though how to pass the Location from the service back to main. I've tried passing Main to the service but that didn't work and always created the service using the constructor without main passed. I've also tried creating a method in the service that returns the location but that kept getting a null pointer exception. How does one go about doing this.
Service Class
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import java.util.Locale;
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private String TAG = "LocationService";
private GoogleApiClient mGoogleApiClient;
private static final long INTERVAL = 1000 * 15;
private static final long FATEST_INTERVAL = 1000 * 30;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
private Geocoder geocoder;
AddressStringOperations addressOps;
TimerUpdate timerUpdate;
Context mainContext;
MainActivity act;
public LocationService(MainActivity act) {
this.mainContext = mainContext;
Log.e(TAG, "Correct Constructor");
}
public LocationService(){
Log.e(TAG, "Shouldn't use");
}
#Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
this.geocoder = new Geocoder(this, Locale.getDefault());
addressOps = new AddressStringOperations(this.geocoder);
this.timerUpdate = new TimerUpdate(this, addressOps);
timerUpdate.startTimer();
mGoogleApiClient = new GoogleApiClient.Builder(LocationService.this)
.addApi(LocationServices.API).addConnectionCallbacks(LocationService.this)
.addOnConnectionFailedListener(LocationService.this).build();
mGoogleApiClient.connect();
createLocationRequest();
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Log.e(TAG, "Service Started");
return super.onStartCommand(intent, flags, startId);
}
protected void createLocationRequest(){
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public Location getLocation(){
Log.e(TAG, "Latitude: "+ mCurrentLocation.getLatitude() + "\n" + "Longitude: " + mCurrentLocation.getLatitude());
return this.mCurrentLocation;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onConnected(Bundle bundle) {
Log.e(TAG, "Connection Successful");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.e(TAG, "Connection Lost");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connection Failed");
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "Firing onLocationChanged.........");
//Log.e(TAG, "Latitude: "+ location.getLatitude() + "\n" + "Longitude: " + location.getLatitude());
timerUpdate.location = location;
mCurrentLocation = location;
}
}
Main Class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.location.Geocoder;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import java.util.Locale;
public class MainActivity extends Activity {
private Button bLogout, bWebsite;
private ImageButton bLogData;
private TextView etLabel;
private UserLocalStore userLocalStore;
private static final String TAG = "MainActivity";
TimerUpdate timerUpdate;
Geocoder geocoder;
Location location;
AddressStringOperations addressOps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e(TAG, "On Create . . . . .");
if(!isGooglePlayServicesAvailable()){
startActivity(new Intent(MainActivity.this, login.class));
Log.e(TAG, "No GooglePlayServices");
finish();
Toast.makeText(getApplicationContext(), "Please update GooglePlay Servies to use this Application", Toast.LENGTH_LONG).show();
}else{
userLocalStore = new UserLocalStore(this);
this.geocoder = new Geocoder(this, Locale.getDefault());
addressOps = new AddressStringOperations(this.geocoder);
this.timerUpdate = new TimerUpdate(this, addressOps, false);
if (authenticate() != true) {
startActivity(new Intent(MainActivity.this, login.class));
Log.e(TAG, "Authenticate is not true");
finish();
} else {
etLabel = (TextView) findViewById(R.id.etEmailLabel);
bLogout = (Button) findViewById(R.id.bLogout);
bLogData = (ImageButton) findViewById(R.id.DataLog);
bWebsite = (Button) findViewById(R.id.website);
LocationService service = new LocationService(MainActivity.this);
Intent start = new Intent(MainActivity.this, LocationService.class);
MainActivity.this.startService(start);
bLogData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String pressStatus = "3";
Log.e(TAG, "Latitude: "+ location.getLatitude() + "\n" + "Longitude: " + location.getLatitude());
timerUpdate.update(pressStatus);
}
});
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
userLocalStore.clearuserData();
userLocalStore.setUserLoggedIn(false);
startActivity(new Intent(MainActivity.this, login.class));
finish();
}
});
bWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("temp"));
startActivity(browserIntent);
}
});
}
}
}
public void setLocation(Location newLocation){
this.location = newLocation;
}
}
You can do that in multiple ways. You can create a Receiver and broadcast and intent from there or you can use an EventBus ( https://github.com/greenrobot/EventBus ).
In this case I think it's more appropriate the Service/Receiver model, you can find here an example: http://www.truiton.com/2014/09/android-service-broadcastreceiver-example/
If you need it only in one activity, consider to use an AsyncTask and handle the output in the postExecute method, it would be a lot easier.
My Application crashes when gps is off and the back end code searches for the location of the user. I have tried the following code for finding the location of user when gps is off it searches using the internet.
Please suggest something in the following code or any other way
below is my code for the locationservice:
package com.example.myapp;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class LocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public LocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Here is the code.
How can I be sure, that location is returned alwasys instead of null.
package com.test.location;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
public class NotifyOnBoot extends Service {
Location location;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
updateNotification();
Thread th = new Thread(null, task, "myService");
th.start();
}
private Runnable task = new Runnable() {
public void run() {
if(location == null)
{
Log.d("location","No location");
}
else
Log.d("location",location.toString());
NotifyOnBoot.this.stopSelf();
}
};
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand (Intent intent, int flags, int startId){
return START_STICKY;
}
protected void updateNotification()
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
private class MyLocationlistener implements LocationListener{
public void onLocationChanged(Location location){}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status, Bundle extras){}
}
}
I recommend to create a call back interface and use onLocationChanged which notifies that call back on the moment the location initiate for the first time.
LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
Greg
Here is my New code based on your suggestions. It did not work. I got a bunch of "Just sent a text message with coords" in a row. So it still is not sleeping for 15 seconds.
package com.droid.service;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
public class DroidService extends Service
{
private LocationManager lm;
private LocationListener locationListener;
private Location location = null;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
// #Override
// public void onCreate()
// {
// super.onCreate();
// initService();
// }
private static final int PERIOD = 15000;
Handler mHandler;
Runnable mRunnable;
#Override
public void onCreate()
{
super.onCreate();
mHandler = new Handler();
mRunnable = new Runnable()
{
public void run()
{
updateNotification();
mHandler.postDelayed(this, PERIOD);
System.out.println("PAUSE FOR 15 SECONDS..!!");
}
};
}
#Override
public void onStart(final Intent intent, final int startId)
{
super.onStart(intent, startId);
mRunnable.run();
}
// private void initService()
// {
// System.out.println("In initService..Droid Service...!!");
// int initialDelay = 15000; // start after 15 seconds
// // int period = 300000; // repeat every 5 minuets
// // int period = 1800000; // repeat every 30 minuets
// int period = 15000; // repeat every 15 seconds for testing
// Timer timer = new Timer();
// TimerTask task = new TimerTask()
// {
// public void run()
// {
// Looper.prepare();
// updateNotification();
// Looper.loop();
// }
// };
// timer.scheduleAtFixedRate(task, initialDelay, period);
// }
protected void updateNotification()
{
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
public static class DateUtils
{
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now()
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
}
private class MyLocationlistener implements LocationListener
{
public void onLocationChanged(Location loc)
{
double lat = loc.getLatitude();
double lon = loc.getLongitude();
String latitude = Double.toString(lat);
String longitude = Double.toString(lon);
String coords = latitude + longitude;
// comment out text message for debug mode
// SmsManager sm = SmsManager.getDefault();
// sm.sendTextMessage("phoneNumber", null, coords, null, null);
System.out.println("Just sent a text message with coords");
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
Here is my code
I get "Just sent a text message with coords" sent like once a second even though my scheduleAtFixedRate is set for 10 seconds.
I got this to work in a normal program, but on the Android platform, they want you to use Looper....and it appears that my code is caught up in this Looper so therefore it is ignoring my scheduleAtFixedRate(10 seconds)
Any help is greatly appreciated.
package com.droid.service;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
public class DroidService extends Service
{
private LocationManager lm;
private LocationListener locationListener;
private Location location = null;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
initService();
}
private void initService()
{
System.out.println("In initService..!!");
int initialDelay = 15000; // start after 15 seconds
// int period = 300000; // repeat every 5 minuets
// int period = 1800000; // repeat every 30 minuets
int period = 15000; // repeat every 15 seconds for testing
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
public void run()
{
Looper.prepare();
updateNotification();
Looper.loop();
Looper.myLooper().quit();
}
};
timer.scheduleAtFixedRate(task, initialDelay, period);
}
protected void updateNotification()
{
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
private class MyLocationlistener implements LocationListener
{
public void onLocationChanged(Location loc)
{
double lat = loc.getLatitude();
double lon = loc.getLongitude();
String latitude = Double.toString(lat);
String longitude = Double.toString(lon);
String coords = latitude + longitude;
// comment out text message for debug mode
// SmsManager sm = SmsManager.getDefault();
// sm.sendTextMessage("phoneNumber", null, coords, null, null);
System.out.println("Just sent a text message with coords");
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
I think the misconception here is not so much that Android wants to use a Looper, but thaty you shouldn't use the Timer for the behavior that you desire. Instead of the Timer you have to manipulate a Looper. I haven't used the Looper directly in a while because there are other components which abstract away a lot of the nuances of it. However I think that Looper.loop() should not return until an outside entity either interrupts your thread or quit's the looper for you. So I don't think that will work, I could be wrong though.
You could use a Handler if you want to create a pulse. A Handler allow you to do work on the Looper thread.
So with the example you have,
private static final int PERIOD = 15000;
Handler mHandler;
Runnable mRunnable;
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
mRunnable = new Runnable() {
public void run() {
updateNotication();
mHandler.postDelayed(this, PERIOD);
}
};
}
I will admit from here on out I am only guessing I know the desired outcome of your application. I am assuming you don't need two way communication as your IBinder is null.
#Override
public void onStart() {
mRunnable.run();
}
// The rest of your code.
..
Try to call initService from onStart().
Basically the best bet for me was to call this onCreate. Now it is doing exactly what I want it to do. Thanks for all your inputs..!! This helped me solve the problem.