0

I am writing an application that has service in it. This service should do some long running background activities say getting Geo coordinates. Now, I want this service to notify the app after a particular interval of time that some thing is to be done like an alarm. I have confusions at this part. i am not getting, how can I make the service update the app about some actions and then show some alert alarms etc.

Below is my code,

Activity:

public class BroadcastTest extends Activity {
      private static final String TAG = "BroadcastTest";
      private Intent intent;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    intent = new Intent(this, BroadcastService.class);
}

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        updateUI(intent);
    }
};

@Override
public void onResume() {
    super.onResume();
    startService(intent);
    registerReceiver(broadcastReceiver, new IntentFilter(
            BroadcastService.BROADCAST_ACTION));
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(broadcastReceiver);
    stopService(intent);
}

private void updateUI(Intent intent) {
    boolean gps = intent.getBooleanExtra("gps", false);
    if (gps) {
        String counter = intent.getStringExtra("counter");
        String time = intent.getStringExtra("time");
        // Log.d(TAG, counter);
        // Log.d(TAG, time);

        TextView txtDateTime = (TextView) findViewById(R.id.txtDateTime);
        TextView txtCounter = (TextView) findViewById(R.id.txtCounter);
        txtDateTime.setText(time);
        txtCounter.setText(counter);
    } else {


    }
}

}

Service:

 public class BroadcastService extends Service {
  private static final String TAG = "BroadcastService";
  public static final String BROADCAST_ACTION = "";
  private final Handler handler = new Handler();
  Intent intent;
  int counter = 0;

GPSTracker gps;

@Override
public void onCreate() {
    super.onCreate();

    intent = new Intent(BROADCAST_ACTION);

    //Notification notification = new Notification(R.drawable.icon, "MyService", 1000);
    //Intent notifIntent = new Intent(this, BroadcastTest.class);
    //PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifIntent, 0);
    //notification.setLatestEventInfo(getApplicationContext(), "ForeGroundService", "Service is Running", pendingIntent);
    //startForeground(1, notification);
}

@Override
public void onStart(Intent intent, int startId) {
    handler.removeCallbacks(sendUpdatesToUI);
    handler.postDelayed(sendUpdatesToUI, 1000); // 1 second

}

private Runnable sendUpdatesToUI = new Runnable() {
    public void run() {
        DisplayLoggingInfo();
        handler.postDelayed(this, 10000); // 10 seconds
    }
};

private void DisplayLoggingInfo() {
    gps = new GPSTracker(getApplicationContext());
    double latitude = 0, longitude = 0;

    // check if GPS enabled
    System.out.println(gps.isGPSEnabled); 
     if (gps.canGetLocation()) {
        latitude = gps.getLatitude();
        longitude = gps.getLongitude();

    } else {
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        //gps.showSettingsAlert();

    }


    Log.d(TAG, "entered DisplayLoggingInfo");
    intent.putExtra("time", Double.toString(latitude)); 
    intent.putExtra("counter", Double.toString(longitude)); 
    sendBroadcast(intent);
}

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

@Override
public void onDestroy() {
    handler.removeCallbacks(sendUpdatesToUI);
    super.onDestroy();
}
 }

Can any body tell me how can I trigger the application after a particular interval of time say after 4hours or after 50kms to show a notification

tejas
  • 2,435
  • 10
  • 37
  • 54

1 Answers1

1

This is what i have written in the background service onStartCommand function

      public class Xyz extends Service{

        public int onStartCommand(Intent intent, int flags, int startId) {
                TimerTask geo = new TimerTask(){

                                  public void run(){

        if(your condition)
            {
                Uri soundrui = RingtoneManager
                                            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                    Intent intent = new Intent(getApplicationContext(),
                                            AcitivitytoOpenOnNotificationClick.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                    PendingIntent p = PendingIntent.getActivity(
                                            getApplicationContext(), 0, intent, 0);
                                    Notification msg = new NotificationCompat.Builder(
                                            getApplicationContext())
                                            .setContentTitle("Your App")
                                            .setContentText("Your Notification")
                                            .setContentInfo(""+count)
                                            .setSmallIcon(R.drawable.ic_launcher)
                                            .setAutoCancel(true)
                                            .setContentIntent(p).build();
                                    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                                    nm.notify("App tag", 0, msg);
            }


        }
        }

            }

           Timer t = new Timer();
           t.schedule(geo/*TimerTask object*/,long delay_before_first_execution, long period );
return super.onStartCommand(intent, flags, startId);
    }
    //End of startcommand
    public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            //Dont forget to cancel the timer.
            t.cancel();
        }

    }
    //End of class

I hope this helps.

Tejas
  • 585
  • 3
  • 15
  • Thank you, can you give me some time to check this. I will update you. – tejas Oct 31 '13 at 08:35
  • Sure. Take your time. – Tejas Oct 31 '13 at 09:12
  • soundrui is not used? – tejas Oct 31 '13 at 09:24
  • Yeah you can use that. I was finding it too irritating, so i removed it. – Tejas Oct 31 '13 at 09:32
  • HI, sorry for the delayed response. I was on leave – tejas Nov 05 '13 at 04:48
  • Can you tell me how to call this service for a periodic interval of time? Say I want to call this service only for once/2 hours – tejas Nov 05 '13 at 04:49
  • Use TimerTask for the notification. And then start the TimerTask using Timer. Check on the above specified 2 classes. – Tejas Nov 05 '13 at 04:53
  • 1
    http://stackoverflow.com/questions/6477608/timer-and-timertask-in-android Check this link. It gives perfect explanation. – Tejas Nov 05 '13 at 05:00
  • Correct me if I am wrong, according to that I should start my service in that if-else block based on my needs. i am going to write this in my activity. Is that right? – tejas Nov 05 '13 at 05:05
  • http://stackoverflow.com/questions/8101582/android-how-to-run-a-task-via-handler-periodically-within-a-service-intent, please see his updated second code. I think that will serve my purpose – tejas Nov 05 '13 at 05:07
  • Wait i'll edit the answer and will give you a brief structure. – Tejas Nov 05 '13 at 05:11
  • Thank you for the updated answer. Give me some time, I will check and update you – tejas Nov 05 '13 at 05:23
  • Super, it is working. Slight changes I had to do, used scheduleAtFixedRate method for timer. And need to call the timer before the return statement. Thank you very much :) – tejas Nov 05 '13 at 05:50