Android-希望应用程序每秒执行任务

Android-希望应用程序每秒执行任务,android,timer,action,handler,Android,Timer,Action,Handler,我正在尝试让我的倒计时应用程序执行更新我当前时间和日期文本视图的功能,并每秒启动MyOnItemSelectedListener,这样应用程序就可以动态倒计时,而不仅仅是在启动onCreate时。如果有一个更有效的方法,然后快速地启动MyOnItemSelectedListener,我将感谢您的批评 public class TheCount extends Activity { TextView description=null; TextView dates=null; TextView t

我正在尝试让我的倒计时应用程序执行更新我当前时间和日期文本视图的功能,并每秒启动MyOnItemSelectedListener,这样应用程序就可以动态倒计时,而不仅仅是在启动onCreate时。如果有一个更有效的方法,然后快速地启动MyOnItemSelectedListener,我将感谢您的批评

public class TheCount extends Activity {
TextView description=null;
TextView dates=null;
TextView times=null;
TextView output=null;
TextView cDateDisplay=null;
TextView cTimeDisplay=null;
private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMinute;
private int mSecond;
CountdownHelper helper=null;
String countdownId=null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.thecount);
    helper=new CountdownHelper(this);
    cTimeDisplay = (TextView)findViewById(R.id.lblCurTime);
    cDateDisplay = (TextView)findViewById(R.id.lblCurDate);

    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);
    mHour = c.get(Calendar.HOUR_OF_DAY);
    mMinute = c.get(Calendar.MINUTE);
    mSecond = c.get(Calendar.SECOND);

    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.countoptions, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    description =(TextView)findViewById(R.id.lblDescriptFed);
    dates =(TextView)findViewById(R.id.lblDateFed);
    times =(TextView)findViewById(R.id.lblTimeFed);
    output =(TextView)findViewById(R.id.lblOutput);

    countdownId=getIntent().getStringExtra(MainActivity.ID_EXTRA);
    if (countdownId!=null) {
        load();
    }

    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

    updateDisplay();

}

private void updateDisplay() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
//@Override
public void run() {
    updatedDisplay();
    }
},0,1000);//Update text every second

}

public class MyOnItemSelectedListener implements OnItemSelectedListener {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

        if (parent.getItemAtPosition(pos).toString().equals("Normal")){
            Toast.makeText(parent.getContext(), "Countdown format is " +
                  parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
            convertTime();
        } else if (parent.getItemAtPosition(pos).toString().equals("by Days")){
            Toast.makeText(parent.getContext(), "Countdown format " +
                      parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
                convertDays();
        } else if (parent.getItemAtPosition(pos).toString().equals("by Hours")){
            Toast.makeText(parent.getContext(), "Countdown format " +
                      parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
                convertHours();
        } else if (parent.getItemAtPosition(pos).toString().equals("by Minutes")){
            Toast.makeText(parent.getContext(), "Countdown format " +
                      parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
                convertMinutes();
        } else if (parent.getItemAtPosition(pos).toString().equals("by Seconds")){
            Toast.makeText(parent.getContext(), "Countdown format " +
                      parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
                convertSeconds();
        }

    }
    public void onNothingSelected(AdapterView parent) {
      // Do nothing.
    }
}

private void convertTime() {
    String dtCountdown = dates.getText().toString() + " " + times.getText().toString();
    String dtCurrent = cDateDisplay.getText().toString() + " " + cTimeDisplay.getText().toString();
    SimpleDateFormat  format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");  
    try {  
        Date date = format.parse(dtCountdown);
        Date dateCur = format.parse(dtCurrent);
        long diff = dateCur.getTime() - date.getTime();

        int timeInSeconds = (int) (diff / 1000);
        int days, hours, minutes, seconds;
        days = timeInSeconds / 86400;
        timeInSeconds = timeInSeconds - (days * 86400);
        hours = timeInSeconds / 3600;
        timeInSeconds = timeInSeconds - (hours * 3600);
        minutes = timeInSeconds / 60;
        timeInSeconds = timeInSeconds - (minutes * 60);
        seconds = timeInSeconds;


        System.out.println(date); 
        if(dateCur.compareTo(date)>0){
            output.setText(String.valueOf(days) + " days " + String.valueOf(hours) +
                    " hours \n" + String.valueOf(minutes) + " minutes " + String.valueOf(seconds) + " seconds ago");
        } else {
            output.setText(String.valueOf(Math.abs(days)) + " days " + String.valueOf(Math.abs(hours)) +
                    " hours \n" + String.valueOf(Math.abs(minutes)) + " minutes " + String.valueOf(Math.abs(seconds)) + " seconds till");
        }

    } catch (ParseException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }
}

private void convertDays() {
    String dtCountdown = dates.getText().toString() + " " + times.getText().toString();
    String dtCurrent = cDateDisplay.getText().toString() + " " + cTimeDisplay.getText().toString();
    SimpleDateFormat  format = new SimpleDateFormat("dd/MM/yyyy hh:mm");  
    try {  
        Date date = format.parse(dtCountdown);
        Date dateCur = format.parse(dtCurrent);
        long diff = dateCur.getTime() - date.getTime();

        int timeInSeconds = (int) (diff / 1000);
        int days;
        days = timeInSeconds / 86400;

        System.out.println(date); 
        if(dateCur.compareTo(date)>0){
            output.setText(String.valueOf(days) + " days ago");
        } else {
            output.setText(String.valueOf(Math.abs(days)) + " days till");
        }

    } catch (ParseException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }
}

private void convertHours() {
    String dtCountdown = dates.getText().toString() + " " + times.getText().toString();
    String dtCurrent = cDateDisplay.getText().toString() + " " + cTimeDisplay.getText().toString();
    SimpleDateFormat  format = new SimpleDateFormat("dd/MM/yyyy hh:mm");  
    try {  
        Date date = format.parse(dtCountdown);
        Date dateCur = format.parse(dtCurrent);
        long diff = dateCur.getTime() - date.getTime();

        int timeInSeconds = (int) (diff / 1000);
        int hours;

        hours = timeInSeconds / 3600;

        System.out.println(date); 
        if(dateCur.compareTo(date)>0){
            output.setText(String.valueOf(hours) + " hours ago");
        } else {
            output.setText(String.valueOf(Math.abs(hours)) + " hours till");
        }

    } catch (ParseException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }
}

private void convertMinutes() {
    String dtCountdown = dates.getText().toString() + " " + times.getText().toString();
    String dtCurrent = cDateDisplay.getText().toString() + " " + cTimeDisplay.getText().toString();
    SimpleDateFormat  format = new SimpleDateFormat("dd/MM/yyyy hh:mm");  
    try {  
        Date date = format.parse(dtCountdown);
        Date dateCur = format.parse(dtCurrent);
        long diff = dateCur.getTime() - date.getTime();

        int timeInSeconds = (int) (diff / 1000);
        int minutes;

        minutes = timeInSeconds / 60;

        System.out.println(date); 
        if(dateCur.compareTo(date)>0){
            output.setText(String.valueOf(minutes) + " minutes ago");
        } else {
            output.setText(String.valueOf(Math.abs(minutes)) + " minutes till");
        }

    } catch (ParseException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }
}

private void convertSeconds() {
    String dtCountdown = dates.getText().toString() + " " + times.getText().toString();
    String dtCurrent = cDateDisplay.getText().toString() + " " + cTimeDisplay.getText().toString();
    SimpleDateFormat  format = new SimpleDateFormat("dd/MM/yyyy hh:mm");  
    try {  
        Date date = format.parse(dtCountdown);
        Date dateCur = format.parse(dtCurrent);
        long diff = dateCur.getTime() - date.getTime();

        int timeInSeconds = (int) (diff / 1000);
        int seconds;
        seconds = timeInSeconds;

        System.out.println(date); 
        if(dateCur.compareTo(date)>0){
            output.setText(String.valueOf(seconds) + " seconds ago");
        } else {
            output.setText(String.valueOf(Math.abs(seconds)) + " seconds till");
        }

    } catch (ParseException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }
}

private void updatedDisplay() {
    TextView cDateDisplay=null;
    TextView cTimeDisplay=null;
    cTimeDisplay = (TextView)findViewById(R.id.lblCurTime);
    cDateDisplay = (TextView)findViewById(R.id.lblCurDate);
    cDateDisplay.setText(
        new StringBuilder()
                // Month is 0 based so add 1
                .append(mDay).append("/")
                .append(mMonth + 1).append("/")
                .append(mYear).append(" "));
    cTimeDisplay.setText(
            new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)).append(":").append(pad(mSecond)));
}

private static String pad(int c) {
    if (c >= 10)
        return String.valueOf(c);
    else
        return "0" + String.valueOf(c);
}  

private void load() {
    Cursor c=helper.getById(countdownId);

    c.moveToFirst();    
    description.setText(helper.getDescription(c));
    dates.setText(helper.getDate(c));
    times.setText(helper.getTime(c) + ":00");

    c.close();
}

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

    helper.close();
}
public类count扩展活动{
TextView description=null;
TextView日期=空;
TextView时间=空;
TextView输出=null;
TextView cDateDisplay=null;
TextView-cTimeDisplay=null;
私人髓鞘内;
私人住宅;
私人国际日;
私人住宅;
私家侦探;
私有整数毫秒;
CountdownHelper=null;
字符串countdownId=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
设置内容视图(R.layout.thecount);
helper=新的倒计时helper(此);
cTimeDisplay=(TextView)findViewById(R.id.lblCurTime);
cDateDisplay=(TextView)findViewById(R.id.lblCurDate);
最终日历c=Calendar.getInstance();
mYear=c.get(日历年);
mMonth=c.get(日历月);
mDay=c.get(日历,月的第天);
mHour=c.get(日历小时);
mMinute=c.get(日历分钟);
mSecond=c.get(Calendar.SECOND);
微调器微调器=(微调器)findViewById(R.id.spinner1);
ArrayAdapter=ArrayAdapter.createFromResource(
这个,R.array.countoptions,android.R.layout.simple\u微调器\u项);
setDropDownViewResource(android.R.layout.simple\u微调器\u下拉菜单\u项);
旋转器。设置适配器(适配器);
description=(TextView)findViewById(R.id.lblDescriptFed);
日期=(TextView)findViewById(R.id.lblDateFed);
times=(TextView)findViewById(R.id.lblTimeFed);
输出=(TextView)findViewById(R.id.lblOutput);
countdownId=getIntent().getStringExtra(MainActivity.ID\u EXTRA);
if(countdownId!=null){
加载();
}
spinner.setOnItemSelectedListener(新的MyOnItemSelectedListener());
updateDisplay();
}
私有void updateDisplay(){
定时器=新定时器();
timer.schedule(新TimerTask(){
//@凌驾
公开募捐{
更新显示();
}
},01000);//每秒更新一次文本
}
公共类MyOnItemSelectedListener实现OnItemSelectedListener{
已选择公共位置(AdapterView父项、视图、整数位置、长id){
if(parent.getItemAtPosition(pos.toString().equals(“Normal”)){
Toast.makeText(parent.getContext(),“倒计时格式为”+
parent.getItemAtPosition(pos.toString(),Toast.LENGTH_LONG.show();
转换时间();
}else if(parent.getItemAtPosition(pos.toString().equals)(“按天”)){
Toast.makeText(parent.getContext(),“倒计时格式”+
parent.getItemAtPosition(pos.toString(),Toast.LENGTH_LONG.show();
转换天数();
}else if(parent.getItemAtPosition(pos.toString().equals)(“按小时”)){
Toast.makeText(parent.getContext(),“倒计时格式”+
parent.getItemAtPosition(pos.toString(),Toast.LENGTH_LONG.show();
转换小时();
}else if(parent.getItemAtPosition(pos.toString().equals)(“按分钟”)){
Toast.makeText(parent.getContext(),“倒计时格式”+
parent.getItemAtPosition(pos.toString(),Toast.LENGTH_LONG.show();
转换分钟();
}else if(parent.getItemAtPosition(pos.toString().equals)(“按秒”)){
Toast.makeText(parent.getContext(),“倒计时格式”+
parent.getItemAtPosition(pos.toString(),Toast.LENGTH_LONG.show();
转换秒();
}
}
未选择公共无效(AdapterView父级){
//什么也不做。
}
}
私有void convertTime(){
String dtCountdown=dates.getText().toString()+“”+times.getText().toString();
字符串dtCurrent=cDateDisplay.getText().toString()+“”+cTimeDisplay.getText().toString();
SimpleDataFormat格式=新的SimpleDataFormat(“dd/MM/yyyy hh:MM:ss”);
试试{
日期=format.parse(dtCountdown);
Date dateCur=format.parse(dtCurrent);
long diff=dateCur.getTime()-date.getTime();
int-timeinsonds=(int)(差值/1000);
整数天、小时、分钟、秒;
天=时间秒/86400;
timeInSeconds=timeInSeconds-(天数*86400);
小时=时间秒/3600;
timeInSeconds=timeInSeconds-(小时*3600);
分钟=时间秒/60;
timeInSeconds=timeInSeconds-(分钟*60);
秒=时间秒;
系统输出打印项次(日期);
如果(日期当前与(日期)>0){
output.setText(String.valueOf(days)+“days”+String.valueOf(hours)+
“小时\n”+字符串.valueOf(分钟)+“分钟”+字符串.valueOf(秒)+“秒前”);
}否则{
output.setText(String.valueOf(Math.abs(天))+“天”+String.valueOf(Math.abs(小时))+
“hours\n”+String.valueOf(Math.abs(minutes))+“minutes”+String.valueOf(Math.abs(seconds))+“秒到”);
}
}捕获(异常解析){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
私人假期(天){
String dtCountdown=dates.getText().toString()+“”+times.getText().toString();
字符串dtCurrent=cDateDisplay.getText().toString()+“”+cTimeDisplay.getText().toString();
SimpleDateFormat=新的SimpleDateFormat(“dd/MM/yyyy hh:MM”);
试试{
日期=format.parse(dtCountdown);
Date dateCur=format.parse(dtCurrent);
long diff=dateCur.getTime()-date.getTime();
int-timeinsonds=(int)(差值/1000);
国际日;
天=时间第二天
private void updateDisplay() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);
            mSecond = c.get(Calendar.SECOND);

            cDateDisplay.setText(new StringBuilder()
                // Month is 0 based so add 1
                .append(mDay).append("/")
                .append(mMonth + 1).append("/")
                .append(mYear).append(" "));

            cTimeDisplay.setText(
                new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)).append(":").append(pad(mSecond))
            );
        }

    },0,1000);//Update text every second
}
        new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    yourMethodOnTheMainThread();
                }
            });
        }
    },0,10000);