java.util.concurrent.ScheduledExecutorService is an ExecutorService that can schedule commands to run after a given delay, or to execute periodically. This example show how to create a one-shot action using ScheduledExecutorService.
package com.example.androidscheduledexecutorservice;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
Button buttonStart;
ScheduledExecutorService scheduledExecutorService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button)findViewById(R.id.start);
buttonStart.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"Start",
Toast.LENGTH_LONG).show();
scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.schedule(new Runnable(){
@Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable(){
@Override
public void run() {
Toast.makeText(MainActivity.this,
"Times-up",
Toast.LENGTH_LONG).show();
}});
}},
5,
TimeUnit.SECONDS);
}
});
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.androidcountdownprogressbar.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android-coding.blogspot.com" />
<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start" />
</LinearLayout>
stop or cancel a ScheduledExecutorService
ReplyDeleteVery nice Example.Thanks alot
ReplyDelete