How to wake up my App Periodically

Chintan Raghwani picture Chintan Raghwani · Mar 14, 2013 · Viewed 11k times · Source

I want to make an functionality, like reminder, in Android.

I want to start-up my app/activity, when it is not running, or its UI is invisible.

It is some-thing like same as reminder, that wakes ups the app at desired time.

I have not worked with any type of background task or service, so I haven't any idea that what to do, or what type of classes or demos should be studied by me?

Can any one give me some suggestions with demos or tutorials links. Thanks, in advance.

Answer

itsrajesh4uguys picture itsrajesh4uguys · Mar 14, 2013

Hi use the following code. This is service. By using pending Intent with alarm manager you can open your UI at your needed time.

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
public class ScheduleCheckService extends Service{

    private Timer timer;
    final  int REFRESH=0;
    Context context;
    private PendingIntent pendingIntent;

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

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

        TimerTask refresher;
        // Initialization code in onCreate or similar:
        timer = new Timer();    
        refresher = new TimerTask() {
            public void run() {
              handler.sendEmptyMessage(0);
            };
        };
        // first event immediately,  following after 1 seconds each
        timer.scheduleAtFixedRate(refresher, 0,1000); 
        //=======================================================

    }

    final Handler handler = new Handler() {


        public void handleMessage(Message msg) {
              switch (msg.what) {
              case REFRESH: 
                   //your code here 


                  break;
              default:
                  break;
              }
          }
        };


         void PendingIntentmethod()
         {
         Intent myIntent = new Intent(context, YOURCLASS.class);        
         pendingIntent = PendingIntent.getActivity(context, 0, myIntent, 0);
         AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();


         }




}

Start the service and stop the service when you want and also dont forget to register it in manifest file.