0

I wrote an application which is getting GPS location and send it to my server via HTTP post. Now i want to do, after press home button and minimize it, app will still send data from GPS. I've found something about IntentServices but i don't have any idea how to use it. Here's my code:

public class MainActivity extends AppCompatActivity implements LocationListener{


public CharSequence message;
public String log;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);

    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);

    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED);
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

}

@Override
public void onLocationChanged(Location location){
    double latitude = (location.getLatitude());
    double longitude = (location.getLongitude());

    message = "Latitude: " + latitude + ", Longitude: " + longitude;
    Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);
    Calendar calendar = Calendar.getInstance();
    String year = Integer.toString(calendar.get(Calendar.YEAR));
    String month = Integer.toString(calendar.get(Calendar.MONTH));
    String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
    String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
    String min = Integer.toString(calendar.get(Calendar.MINUTE));
    log = year+"/"+month+'/'+day+" "+hour+":"+min+" w:"+latitude+" h:"+longitude;
    Log.v("log: ", log);

    //whole asynctask is about sending data only

    new AsyncTask<Void, Void, Void>(){
        @Override
        protected void onPreExecute(){
            Log.v("AsyncTask: ", "starting");
        }

        @Override
        protected Void doInBackground(Void ...params){

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://server/php.php");

            try{
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("log", log));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                try {
                    HttpResponse response = httpClient.execute(httpPost);
                } catch (IOException e){
                    Log.v("error: ", "IOException");
                }


            } catch (UnsupportedEncodingException e){
                e.printStackTrace();
                Log.v("error: ", "UnsupportedEncodingException");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void res){
            Log.v("AsyncTask: ", "Ended");
        }
    }.execute();

}

@Override
public void onProviderDisabled(String provider){
    // TODO Auto-generator 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
}
}
salih kallai
  • 879
  • 2
  • 13
  • 34
Qiteq
  • 675
  • 1
  • 6
  • 22

1 Answers1

0

You should create a Service rather than Activity. There is an option to start a Service with startForeground() which makes Service running even when you minimize application or use task killer.

Look at that question for example of usage of startForeground()

Community
  • 1
  • 1
L. Kolar
  • 535
  • 2
  • 7
  • I tried, but startForeground() accepts Notification only as parameter, so how can i start whole function? And second one, I am not sure do i create service correclty. Is it only java class extending "Service"? – Qiteq Mar 14 '16 at 14:23
  • Please check out link to the question in the answer. You will see PlayerService. Your service class needs to extend Service and override methods onStartCommand, onBind, onDestroy, onCreate, ... You can start service from activity with `Intent i=new Intent(this, PlayerService.class); startService(i);` And then in your service you create notification and call startForeground. For more information about service lifecycle and service methods look [here](http://developer.android.com/guide/components/services.html#LifecycleCallbacks) – L. Kolar Mar 14 '16 at 15:35
  • So i have done service with Thread and while(true) in onStartCommand. There is a Log with sleep(1000) in try catch. But after start thread, nothing happens. I want to loop whole code in service. – Qiteq Mar 14 '16 at 17:06
  • First try to implement Service without thread. Just start Service from MainActivity's onCreate with Intent as I wrote one comment before and Log something in onStartCommand. I don't see the point of try/catch in this case. – L. Kolar Mar 14 '16 at 17:15
  • I have done just like you said, and it works. It shows toast from onStartCommand method, but i want to loop something, for example this toast. I used try /catch because of sleep in while loop. – Qiteq Mar 14 '16 at 19:14
  • Ok I see, my miskate. Feel free to add while loop and sleep. Please mark my answer as accepted. – L. Kolar Mar 14 '16 at 19:24
  • I have the last one question. How can i use location object from onLocationChanged method in service? – Qiteq Mar 14 '16 at 20:24
  • Depends on what you want to do. But as I can see from your code you are using it correctly to get longitude and latitude. – L. Kolar Mar 14 '16 at 20:32
  • I want to recieve updated data of gps location and send it via post, but location object is avilable in onLocationChanged method only. – Qiteq Mar 14 '16 at 21:17
  • Sorry, cant help you here. – L. Kolar Mar 14 '16 at 21:34
  • Anyway, you helped me a lot, and very thank you fot this – Qiteq Mar 14 '16 at 21:43