Using Timer to do repeat task : Time « Date Type « Android






Using Timer to do repeat task

  

package app.test;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

class MyIntentService extends IntentService {

  public MyIntentService() {
    super("MyIntentServiceName");
  }
  @Override
  protected void onHandleIntent(Intent intent) {
    try {
      int result = DownloadFile(new URL("http://a.com/b.pdf"));
      Log.d("IntentService", "Downloaded " + result + " bytes");
      Intent broadcastIntent = new Intent();
      broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
      getBaseContext().sendBroadcast(broadcastIntent);

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

  private int DownloadFile(URL url) {
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return 100;
  }
}

class MyService extends Service {
  int counter = 0;
  public URL[] urls;

  static final int UPDATE_INTERVAL = 1000;
  private Timer timer = new Timer();

  private final IBinder binder = new MyBinder();

  public class MyBinder extends Binder {
    MyService getService() {
      return MyService.this;
    }
  }

  @Override
  public IBinder onBind(Intent arg0) {
    return binder;
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

    try {
      int result = DownloadFile(new URL("http://amazon.com"));
      Toast.makeText(getBaseContext(), "Downloaded " + result + " bytes",
          Toast.LENGTH_LONG).show();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }

    try {
      new DoBackgroundTask().execute(new URL("http://a.com/a.pdf"),
          new URL("http://b.com/b.pdf"),
          new URL("http://c.com/c.pdf"),
          new URL("http://d.net/d.pdf"));

    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    doSomethingRepeatedly();

    Object[] objUrls = (Object[]) intent.getExtras().get("URLs");
    URL[] urls = new URL[objUrls.length];
    for (int i = 0; i < objUrls.length - 1; i++) {
      urls[i] = (URL) objUrls[i];
    }
    new DoBackgroundTask().execute(urls);

    return START_STICKY;
  }

  private void doSomethingRepeatedly() {
    timer.scheduleAtFixedRate(new TimerTask() {
      public void run() {
        Log.d("MyService", String.valueOf(++counter));
        try {
          Thread.sleep(4000);
          Log.d("MyService", counter + " Finished");

        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }, 0, UPDATE_INTERVAL);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if (timer != null) {
      timer.cancel();
    }
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
  }

  private int DownloadFile(URL url) {
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return 100;
  }

  private class DoBackgroundTask extends AsyncTask<URL, Integer, Long> {
    protected Long doInBackground(URL... urls) {
      int count = urls.length;
      long totalBytesDownloaded = 0;
      for (int i = 0; i < count; i++) {
        totalBytesDownloaded += DownloadFile(urls[i]);
        publishProgress((int) (((i + 1) / (float) count) * 100));
      }
      return totalBytesDownloaded;
    }

    protected void onProgressUpdate(Integer... progress) {
      Log.d("Downloading files", String.valueOf(progress[0])
          + "% downloaded");
      Toast.makeText(getBaseContext(),
          String.valueOf(progress[0]) + "% downloaded",
          Toast.LENGTH_LONG).show();
    }

    protected void onPostExecute(Long result) {
      Toast.makeText(getBaseContext(), "Downloaded " + result + " bytes",
          Toast.LENGTH_LONG).show();
      stopSelf();
    }
  }
}

public class Test extends Activity {
  IntentFilter intentFilter;
  private MyService serviceBinder;
  Intent i;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    intentFilter = new IntentFilter();
    intentFilter.addAction("FILE_DOWNLOADED_ACTION");
    registerReceiver(intentReceiver, intentFilter);

    Button btnStart = (Button) findViewById(R.id.btnStartService);
    btnStart.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {

        Intent intent = new Intent(getBaseContext(), MyService.class);
        try {
          URL[] urls = new URL[] { new URL("http://a.com/a.pdf"),
              new URL("http://b.com/b.pdf"),
              new URL("http://c.com/c.pdf"),
              new URL("http://d.com/d.pdf") };
          intent.putExtra("URLs", urls);

        } catch (MalformedURLException e) {
          e.printStackTrace();
        }
        startService(intent);

        startService(new Intent(getBaseContext(), MyService.class));
        startService(new Intent("app.test.MyService"));
        startService(new Intent(getBaseContext(), MyIntentService.class));

        i = new Intent(Test.this, MyService.class);
        bindService(i, connection, Context.BIND_AUTO_CREATE);
      }
    });

    Button btnStop = (Button) findViewById(R.id.btnStopService);
    btnStop.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        stopService(new Intent(getBaseContext(), MyService.class));
      }
    });
  }

  private ServiceConnection connection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
      serviceBinder = ((MyService.MyBinder) service).getService();
      try {
        URL[] urls = new URL[] { new URL("http://a.com/a.pdf"),
            new URL("http://b.com/b.pdf"),
            new URL("http://c.com/c.pdf"),
            new URL("http://d.net/d.pdf") };
        serviceBinder.urls = urls;
      } catch (MalformedURLException e) {
        e.printStackTrace();
      }
      startService(i);
    }

    public void onServiceDisconnected(ComponentName className) {
      serviceBinder = null;
    }
  };
  private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      Toast.makeText(getBaseContext(), "File downloaded!",
          Toast.LENGTH_LONG).show();
    }
  };
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="Start Service" />
        
<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="Stop Service" />
        
</LinearLayout>

   
    
  








Related examples in the same category

1.Timer task
2.Get Time String From Milliseconds
3.Returns the current time since 1970, UTC, in seconds.
4.Returns the current time since 1970, UTC, in milliseconds.
5.Converts time from a long to a string in a format set by the user in the phone's settings.
6.Returns the current time since 1970, local time zone, in milliseconds.
7.time From Local Millis
8.Given a number, round up to the nearest power of ten times 1, 2, or 5. The argument must be strictly positive.
9.Thread based Timer
10.Create Timestamp
11.Timestamp to Local time in long
12.Timestamp to UTC
13.Get Current Time
14.Get Elapsed Time Minutes Seconds String
15.Get Time String
16.Get Moscow Time
17.Returns the time represented by the time String.
18.Utils for calculating sleep time
19.int To String Time Format
20.millis To Seconds To Time Str
21.Convert time in seconds to a string in 00:00:00
22.remaining Time To Human Readable Form
23.Get a readable string displaying the time
24.Return the time in ms into format MM:SS
25.Get Time Difference
26.TimeSpan class
27.Calculate how many days the first time is expired than second time.
28.Checks if the first parameter is after the second parameter in time.
29.Checks if the first parameter is before the second parameter in time.
30.GMT (UTC) Time Converter