dimanche 17 mai 2015

How to make sure that the code is executed every 10 minute, for an infinite time?

I have been trying to run a particular function every ten minutes, for an infinite time, however, it stops after about 60-90 minutes. This is despite the fact that I am making use of Alarm Manager and a Service to make sure that the App is not killed by the OS. I have even checked in the cellphone, in Settings-> Manage App -> Running and it shows that 1 Process and 1 Service of my App is running, yet the particular function stops to run after some time.

In the MainActivity, inside onCreate(), this is how I am calling the service:

Intent i = new Intent(MainActivity.this, MyService.class);
startService(i);

This is what my Service class looks like:

public class MyService extends Service
{
//Alarm alarm = new Alarm();
Alarm alarm;
public void onCreate()
{
    super.onCreate();       
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{   
    alarm = new Alarm();
    alarm.SetAlarm(MyService.this);
    Log.i("Called alarm.SetAlarm","Called alarm.SetAlarm");
     return START_STICKY;
}

public void onStart(Context context,Intent intent, int startId)
{   alarm = new Alarm();
    Log.i("Called alarm.SetAlarm(context)","Called alarm.SetAlarm(context)");
    alarm.SetAlarm(context);

}

@Override
public IBinder onBind(Intent intent) 
{
    return null;
}
}

This is what my Alarm Manager looks like. The function that needs to be executed after every 10 minutes is UpdataData(), which is also being called here in onReceive().

public class Alarm extends BroadcastReceiver 
 {    
public MainActivity obj;
//public MainActivity obj = new MainActivity();
@Override
public void onReceive(Context context, Intent intent) 
{   
    PowerManager pm = (PowerManager)          
    context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl =
    pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
    wl.acquire();
    obj = new MainActivity();
    //UpdataData() needs to be executed after every 10 minutes, for an     
    //  infinite time
    obj.UpdateData();
    // Put here YOUR code.
    Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); e
    //MainActivity.UpdateData(context);
    wl.release();
}

public void SetAlarm(Context context)
{
    Log.i("Inside SetAlarm","Inside SetAlarm");
    AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, Alarm.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}

public void CancelAlarm(Context context)
{
    Intent intent = new Intent(context, Alarm.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);
}
}

Also note that every ten minutes, the cellphone's screen splashes with the Toast text "Alarm!!!!" and the UpdataData function is called as well for good 60 -90 minutes. However, post this, the call stops and I don't know why. I would be very thankful if someone could help.

This is what my UpdataData() looks like:

public void UpdateData() {

    Log.i("Inside Update Data", "Inside Update Data");

    Thread thread = new Thread(new Runnable() {
       @Override
        public void run() {
         for(int i=0; i<1; i++){
                try {

                    // Your code goes here
                    if (locationclient != null
                            && locationclient.isConnected()) {
                        loc = locationclient.getLastLocation();
                        lat = loc.getLatitude();
                        lng = loc.getLongitude();

                    }

                    /*SharedPreferences settings = con.getSharedPreferences(PREFS_NAME, 0);
                    Log.i("SP UD", "SP UD");
                     if(settings.contains("token")){
                        token = settings.getString("token", null);
                        Log.i("Inside SP UD", "token: "+token);
                    }*/

                    try { // Updating the latest location in the UI, just
                            // for convinience.
                        HttpClient httpClient = new DefaultHttpClient();
                        // Creating HTTP Post
                        HttpPost httpPost = new HttpPost(
                                "http://ift.tt/1POmg7c");
                        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(
                                3);
                        // Building post parameters//
                        // key and value pair
                        Log.i("token", "token" +token);

                        Log.i("Latitude for III POST Call",
                                "Latitude for III POST Call" + lat);
                        Log.i("Longitude for III POST Call",
                                "Longitude for III POST Call" + lng);
                        if(lat == 10 && lng == 10){
                            loc = locationclient.getLastLocation();
                            lat = loc.getLatitude();
                            lng = loc.getLongitude();
                        }


                        nameValuePair.add(new BasicNameValuePair("token",
                                token));
                        nameValuePair.add(new BasicNameValuePair("lat",
                                Double.toString(lat)));
                        nameValuePair.add(new BasicNameValuePair("lng",
                                Double.toString(lng)));
                        Log.i("Made UpdateData Post Call",
                                "Made UpdateData Post Call");
                        // Url Encoding the POST parameters
                        try {
                            httpPost.setEntity(new UrlEncodedFormEntity(
                                    nameValuePair));
                        } catch (UnsupportedEncodingException e) {
                            // writing error to Log
                            e.printStackTrace();
                        }

                        // Making HTTP Request
                        try {
                            HttpResponse response = httpClient
                                    .execute(httpPost);

                            // writing response to log
                            Log.d("Http Response:", response.toString());
                            // Your code goes here
                        } catch (IOException e) {
                            // writing exception to log
                            e.printStackTrace();

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }// While closed

        }

    });
    thread.start();
    }// UpdateData closed

Aucun commentaire:

Enregistrer un commentaire