We have been working on developing service for android platform.
In our service we need to send GPS data (Lat and Long) of device to some external REST service after every one minute.
It is running fine for almost 15 minutes after locking of device. But after that it does not send any data.
After unlocking the device, it start again to send data over REST service.
My Code So far
public class MainActivity extends AppCompatActivity {
private PendingIntent pendingIntent;
private PowerManager.WakeLock wakeLock;
public static final String USER_NAME = "USERNAME";
String username;
String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent alarm = new Intent(this, AlarmReceiver.class);
boolean alarmRunning = (PendingIntent.getBroadcast(this, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
if(alarmRunning == false) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 30000, pendingIntent);
}
PowerManager mgr = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyWakeLock");
wakeLock.acquire();
}
public class BackgroundService extends Service {
private boolean isRunning;
private Context context;
private Thread backgroundThread;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);
}
private Runnable myTask = new Runnable() {
public void run() {
// Do something here
login("admin","admin");
stopSelf();
}
};
@Override
public void onDestroy() {
this.isRunning = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!this.isRunning) {
this.isRunning = true;
this.backgroundThread.start();
}
return START_STICKY;
}
private void login(final String strLatitude, final String strLongitude) {
class LoginAsync extends AsyncTask<String, Void, String> {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result = new StringBuilder();
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
@Override
protected void onPreExecute() {
super.onPreExecute();
// loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
@Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
sbParams = new StringBuilder();
try {
sbParams.append("name").append("=")
.append(URLEncoder.encode(uname, charset));
sbParams.append("&");
sbParams.append("password").append("=")
.append(URLEncoder.encode(pass, charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
String url="http://192.168.0.122:1234/YegoService.svc/AddVehicleMovement";
URL object=new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
JSONObject parent = new JSONObject();
parent.put("strValidatorID","111");
parent.put("TXT_LAT", "28.25252525");
parent.put("TXT_LONG", "77.7777777");
parent.put("DAT_DATE", "");
con.connect();
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
wr.flush();
wr.close();
InputStream input = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception ex) {
ex.printStackTrace();
}
return result.toString();
}
@Override
protected void onPostExecute(String result){
String s = result.trim();
}
}
LoginAsync la = new LoginAsync();
la.execute("admin", "admin");
}
}
public class AlarmReceiver extends BroadcastReceiver {
String strLatitude;
String strLongitude;
@Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, BackgroundService.class);
context.startService(background);
}
}
What to do?
You have to fire the alarm over and over again when the service completes running.
Also you can implement a BroadCastReceiver that starts the service on the device boot.
Check this tutorial: http://ncona.com/2014/04/schedule-your-android-app-to-do-something-periodically/
Yes, you can run any service even if the device is locked. Even, you can resume the service after rebooting the device.
You can implement GCM Network Manager.
Sample code required:-
Java code :-
Fore more info you can visit https://developers.google.com/cloud-messaging/network-manager#run_tasks and read the docs.
You just have to include the gcm services in you project to use GCM network manager. Support 4.0 +
Please accept this answer if this is the solution you want. This may help other developers also.