13

I want to keep my application running in background
I have an application that sends the user's location to our server
I have the following code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LocationManager locationManager;
    String context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager)getSystemService(context);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String provider = locationManager.getBestProvider(criteria, true);

    updateWithNewLocation(null);

    locationManager.requestLocationUpdates(provider, (10*60*1000), 10,
                                           locationListener);
}
private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      updateWithNewLocation(location);
    }

    public void onProviderDisabled(String provider){
      updateWithNewLocation(null);
    }

    public void onProviderEnabled(String provider){ }
    public void onStatusChanged(String provider, int status, 
                                Bundle extras){ }
  };
  public void updateWithNewLocation(Location location) {


        if (location != null) {
            Dbhelper helper = new Dbhelper(this);
            final SQLiteDatabase db = helper.getWritableDatabase();
            long time = System.currentTimeMillis();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
            final String curTime = df.format(time);
            final double lat = location.getLatitude();
            final double lng = location.getLongitude();
            final double alt = location.getAltitude();
            System.out.println(lat);
            System.out.println(lng);
            System.out.println(alt);
            db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
            "('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
            db.close();
            /*Timer timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask(){
                @Override
                public void run(){
                    db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
                            "('121.2149012','-6.217837','0.0','2012-05-07 10:20:01')");
                    db.close();
                }
            }, 10*60*1000, 10*60*1000);*/

          } 
       }

I want my applicatioin to be running in the background. I want it to launch automatically when the phone is turned on

Jason
  • 1,658
  • 3
  • 20
  • 51
akubabas
  • 473
  • 5
  • 13
  • 28
  • There a component known as Service in Android. Android documnetation says **A Service is an application component that can perform long-running operations in the background and does not provide a user interface**. For automatically starting you app you can use AlarmManager. – Gaurav Agarwal May 08 '12 at 07:16

5 Answers5

15

A very simple answer for your problem is to use Service. It will allow you to perform variety of tasks while being in background and is your best bet for sending your location to server silently.

Read this answer for help.

Community
  • 1
  • 1
waqaslam
  • 67,549
  • 16
  • 165
  • 178
  • @Waqas where your update answer??i try to understand from your link, but i'm confused..i'm new in android..i just follow code from your link or how?? – akubabas May 08 '12 at 07:55
  • My updated answer was actually the update i made in my answer. Yes, if you follow the parts of that link (and modify a little as per your requirements), you can get this done. – waqaslam May 08 '12 at 08:00
  • there are AppGlobal, where did I get AppGlobal ?? – akubabas May 08 '12 at 08:24
  • replace **AppGlobal** with **Log.i** or perhaps you can skip those lines because they are for printing logs. I think that class (AppGlobal) is that user's custom designed class – waqaslam May 08 '12 at 08:49
  • i try to edited this code..but didn't work..can you give me a simple code to newbie??:) thank you – akubabas May 08 '12 at 09:31
1

You can keep your application running in the background using Service

I hope this link will help you

Please read the documentation for further details

Jason
  • 1,658
  • 3
  • 20
  • 51
Hassy31
  • 2,793
  • 3
  • 21
  • 37
0

Run your background logic in a Service, and if you want to give a good UX experience (and to also have an higher priority) post a Notification to status-bar (using NotificationManager).

avimak
  • 1,628
  • 11
  • 18
0

You should use a Service and a BroadcastReceiver

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
ashokk
  • 437
  • 1
  • 5
  • 13
  • @deadbabaz You can easily get the code for Service and Broadcast receiver from the developer site of Android. – Dharmendra May 08 '12 at 11:38
0

GrabLocationDetails.java

Use this code as your GrabLocationDetails.java

 public class GrabLocationDetails extends Service implements LocationListener {

        double lat,lng;
        private LocationManager locationManager;
        private String provider;
        boolean isGps;
        private ArrayList<String> mList;
        Context GLDContext;

        public GrabLocationDetails(Context cont){
            this.GLDContext=cont;
        }
        public GrabLocationDetails(){}
        @Override
        public void onCreate() {
            super.onCreate();
            mList = new ArrayList<String>();
            isGps = false;
            lat=0.0;
            lng=0.0;
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {

            //super.onStart(intent, startId);

            try {
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                Criteria criteria = new Criteria();
                provider = locationManager.getBestProvider(criteria, false);
                LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
                boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (!enabled) {
                    isGps = false;
                    ListAddItem(isGps);
                    SendBroadcast();
                } else {
                    isGps = true;
                    Location location = locationManager.getLastKnownLocation(provider);
                    lat=(location.getLatitude());
                    lng=(location.getLongitude());
                    ListAddItem(true);
                    SendBroadcast();
                    locationManager.requestLocationUpdates(provider, 400, 1, this);
                }

            } catch (Exception e) {
                ListAddItem(isGps);
                SendBroadcast();
            }
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            //locationManager.removeUpdates(this);
        }

        public  void SendBroadcast(){
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction(CommandExecutionModule.LocationDetails);
            broadcastIntent.putExtra("Data", mList);
            sendBroadcast(broadcastIntent);

        }
        public void ListAddItem(boolean GPS) {
            //if(!GPS)
            //mList.add("0");
            //else
            //mList.add("1");
            mList.add(Double.toString(lat));
            mList.add(Double.toString(lng));
        }

        /**************************************************************************************************************/

        @Override
        public void onLocationChanged(Location location){
            locationManager.requestLocationUpdates(provider, 400, 1, this);
            mList.clear();
            lat = (location.getLatitude());
            lng = (location.getLongitude());
            ListAddItem(isGps);
            SendBroadcast();
            locationManager.removeUpdates(this);
            stopSelf();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            locationManager.requestLocationUpdates(provider, 400, 1, this);
        }

        @Override
        public void onProviderEnabled(String provider){
            isGps=true;
        }
        @Override
        public void onProviderDisabled(String provider){
            isGps=false;
            lat=0.0;
            lng=0.0;
            mList.clear();
            ListAddItem(isGps);
            //SendBroadcast();
        }
Jason
  • 1,658
  • 3
  • 20
  • 51