2

I am creating alarmmanager in one of my activities like following

    AlarmManager alarmManager=(AlarmManager) MenuItems.this.getSystemService(Context.ALARM_SERVICE);
    Intent intent23 = new Intent(MenuItems.this, MyReceiver.class);
    PendingIntent pendingIntent23 = PendingIntent.getBroadcast(MenuItems.this, 0, intent, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),300000,
                                                                          pendingIntent);

After this i have following BroadcastReceiver

public class MyReceiver extends WakefulBroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {

    ComponentName comp = new ComponentName(context.getPackageName(),
            MyAlarmService.class.getName());

    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}
}

This broadcast receiver calls my following service

Public class MyAlarmService extends Service
 {
private String server_response,data_to_send;
private String server ;
private String setLocation =  "/xyz";
private URL url; 
public double mLatitude;
private MainActivity main;
private boolean isGpsEnabled = false;
  private sendToserver send;
  private Context context;
 public String vallatlong;

private boolean isNetworkEnabled = false;

private boolean canGetLocation = false;

private Location mLocation;


public MyAlarmService(Context context) 
{
    this.context = context;

    getLocation();
}
public MyAlarmService() 
{

}

public double mLongitude;
private LocationManager mLocationManager;
 private NotificationManager mManager;

 @Override
 public IBinder onBind(Intent arg0)
 {
   // TODO Auto-generated method stub
    return null;
 }

@Override
public void onCreate() 
{
   // TODO Auto-generated method stub  
   super.onCreate();
}


   @Override
   public void onStart(Intent intent, int startId)
   {
   super.onStart(intent, startId);
    main = new MainActivity();
   getLocation();
  }

    public String getLocation() 
 {
   server = getString(R.string.server_add_new);
   try {
    Log.e("this is getlocation method ", "1");

       mLocationManager = (LocationManager)         getApplicationContext().getSystemService(LOCATION_SERVICE);

       /*getting status of the gps*/
       isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);


       /*getting status of network provider*/
       isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

       if (!isGpsEnabled && !isNetworkEnabled) {

           Log.e("no provider", "non availability");
       } else {
           Log.e("this is getlocation method ", "2");
           this.canGetLocation = true;

           /*getting location from network provider*/
           if (isNetworkEnabled) {

              // mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,    MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
               Log.e("this is getlocation method ", "3");
               if (mLocationManager != null) {
                   Log.e("this is getlocation method ", "7");
                   mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                   if (mLocation != null) {
                       Log.e("this is getlocation method ", "8");
                       mLatitude = mLocation.getLatitude();

                       mLongitude = mLocation.getLongitude();
                       long user_id = main.getDefaultsint("user_id", MyAlarmService.this);

                       String stringLatitude = String.valueOf(mLatitude);
                       String stringLongitude = String.valueOf(mLongitude);
                       vallatlong = stringLatitude+stringLongitude;

                       try {
                            url = new URL(server+setLocation);
                            data_to_send = "lat=" + mLatitude + "&";
                            data_to_send += "long=" + mLongitude + "&";
                            data_to_send += "user_id=" + user_id ;

                            Log.e("data to send", "url"+data_to_send);
                            send = new sendToserver(url, data_to_send);
                            send.execute();
                              Log.e("this is getlocation method ", "6");
                        } catch (MalformedURLException e) {

                            e.printStackTrace();
                        }
                   }
               }
               /*if gps is enabled then get location using gps*/
               if (isGpsEnabled) {

                   if (mLocation == null) {

                    //   mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
                       Log.e("this is getlocation method ", "4");
                       if (mLocationManager != null) {

                           mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                           if (mLocation != null) {
                               Log.e("this is getlocation method ", "5");

                               mLatitude = mLocation.getLatitude();

                               mLongitude = mLocation.getLongitude();



                               long user_id = main.getDefaultsint("user_id", MyAlarmService.this);

                               try {
                                    url = new URL(server+setLocation);
                                    data_to_send = "lat=" + mLatitude + "&";
                                    data_to_send += "long=" + mLongitude + "&";
                                    data_to_send += "user_id=" + user_id ;

                                    Log.e("data to send", "url"+data_to_send);
                                    send = new sendToserver(url, data_to_send);
                                    send.execute();
                                      Log.e("this is getlocation method ", "6");
                                } catch (MalformedURLException e) {

                                    e.printStackTrace();
                                }
                           }

                       }
                   }

               }
           }
       }

    } catch (Exception e) {

       e.printStackTrace();
    }
       return vallatlong;
 }

@Override
public void onDestroy() 
{
    // TODO Auto-generated method stub
    super.onDestroy();
}



public double getLatitude() {

    if (mLocation != null) {

        mLatitude = mLocation.getLatitude();
    }
    return mLatitude;
}


public double getLongitude() {

    if (mLocation != null) {

        mLongitude = mLocation.getLongitude();

    }

    return mLongitude;
}


public boolean canGetLocation() {

    return this.canGetLocation;
}

public class sendToserver extends AsyncTask<URL, String, ArrayList<String>> 
{
    @Override
    protected void onPostExecute(ArrayList<String> result) {

        super.onPostExecute(result);
    }


    String data_to_send = "";
     URL url;
     public sendToserver(URL u, String data){
         this.url =  u;
         this.data_to_send = data;
     }

    @Override
    protected ArrayList<String> doInBackground(URL... params) { 

        BufferedReader reader=null;

      try
      { 


        URLConnection conn = url.openConnection(); 
        conn.setDoOutput(true);                   
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
        wr.write(data_to_send);
        wr.flush();     

        // Get the server response 

      reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      StringBuilder sb = new StringBuilder();
      String line = null;

      // Read Server Response
      while((line = reader.readLine()) != null)
          {
                 // Append server response in string
                 sb.append(line + "\n");
                 Log.e("inside", "while loop");
          }


      server_response = sb.toString();


      }
      catch(Exception ex)
      { 

      }

        return null;
    }

}
}

Everything is working fine, my activity sets Alarmmanager which triggers broadcast-receiver after every 5 minutes which executes my service even when my app is closed and phone is not in use i am getting user location at my server, but on some phones like galaxy NoteEdge this code is not working. I am not getting user location after every 5 minutes am i doing something wrong. Please suggest any relevant way of doing this if this is not right way of doing.

Smart
  • 71
  • 1
  • 2
  • Did you do [this](http://stackoverflow.com/questions/9093271/start-sticky-and-start-not-sticky). After facing a lot of problems with Alarms and Services, I suggest you debug to the last point where you are in control of the Alarm-Broadcast Manager and the service - put logs (System.out's) and see what is the tripping point of your service. Is it the problem with the service, broadcast or the alarm? – Skynet Jan 14 '15 at 11:50
  • Also it will be a huge service to yourself if you check the Memory consumption and time taken by your relevant code to execute - Use the Debug class and DDMS to trace your memory usage - Debug.startMethodTracing() and Debug.stopMethodTracing() – Skynet Jan 14 '15 at 11:53
  • I would also suggest to export your service in the Manifest - an exported/ remote service gets its own heap. So that means more memory at your hand. – Skynet Jan 14 '15 at 11:54
  • I forgot to add one very important point - the way alarms are dispatched on Kitkat is different than how they were pre-Kitkat. "setRepeating" is not guaranteed to be delivered at exact times. check [this](http://developer.android.com/training/scheduling/alarms.html) guide. – Skynet Jan 14 '15 at 11:57
  • thanks @Skynet for your comment. should i go for intent service rather than service – Smart Jan 14 '15 at 12:17
  • every thing is working fine but on some devices location is not updated. – Smart Jan 14 '15 at 12:18
  • [Check This](http://stackoverflow.com/questions/21461191/alarmmanager-fires-alarms-at-wrong-time/21461246#21461246) isolate it in a new project and try it on the problematic phone and see what works for you. – Skynet Jan 14 '15 at 12:21

0 Answers0