在活动创建方法android上启动Timer

时间:2012-10-12 16:29:28

标签: android timer

我需要在管理员在浏览器上发送消息时向应用程序用户显示消息。为此我实现了一个计时器,以便它在应用程序启动时向用户显示一条消息。如果按下新消息,计时器将继续运行以在20分钟内获取一次消息。我的计时器工作正常,但点击按钮。

  1. 我希望我的计时器在活动加载后立即启动。
  2. 这是显示信息的正确方法吗? (就像横幅一样)
  3. 资源消耗的计时器是什么?
  4. 计时器任务

    class secondTask extends TimerTask {
    
        @Override
        public void run() {
    
            TestBannerActivity.this.runOnUiThread(new Runnable() {
    
                @Override
                public void run() { 
                    fl.setVisibility(View.VISIBLE);
                    long millis = System.currentTimeMillis() - starttime;
                    int seconds = (int) (millis / 1000);
                    int minutes = seconds / 60;
                    seconds = seconds % 60;
    
    
                     text2.setText(String.format("%d:%02d", minutes,
                     seconds));
                }
            });
        }
    };
    

    按钮点击事件

    b.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                Button b = (Button) v;
                if (b.getText().equals("stop")) {
                    timer.cancel();
                    timer.purge(); 
                    b.setText("start");
                } else {
                    starttime = System.currentTimeMillis();
                    timer = new Timer(); 
                    timer.schedule(new secondTask(), 8000, 1200000); 
                    b.setText("stop");
                }
            }
        });
    

1 个答案:

答案 0 :(得分:0)

您可以使用此代码:

package packagename.timerService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;

public class TimerService extends Service{

    public static final String BROADCAST_TIMER_ACTION = "packagename.timerService.TimerService";
    private final Handler handler = new Handler();
    private final Handler updateUIHandler = new Handler();


    Intent intent;
    int time = 0;
    private int durationTime = 0;

    private int starDate;
    private int currentDate;
    private Date startTaskDate;
    private String taskComment;


    @Override
    public void onCreate() {
        // Called on service created
        intent = new Intent(BROADCAST_TIMER_ACTION);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {


                handler.removeCallbacks(sendUpdatesToUI);
                handler.post(sendUpdatesToUI); //post(sendUpdatesToUI);
                starDate = Calendar.getInstance().get(Calendar.DATE);
                durationTime = 0;
                startTaskDate = new Date();


            }
        } catch (Exception e) {}
        return START_STICKY;
    }

    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            try{
                displayLoggingInfo();
                time ++;
                durationTime ++;
                handler.postDelayed(this, 60 * 1000); // 1 minute
            }catch (Exception e) { }
        }
    };

    private Runnable sendUpdatesToUIOnResume = new Runnable() {
        public void run() {
            displayLoggingInfoForOnResume();
        }
    };

    private void displayLoggingInfoForOnResume() {
        try{
            currentDate = Calendar.getInstance().get(Calendar.DATE);

            intent.putExtra("changeDate", String.valueOf(false));

            intent.putExtra("time", String.valueOf(time == 0 ? time : time - 1 ));
            sendBroadcast(intent);
        } catch (Exception e) { }
    }

    private void displayLoggingInfo() {
        try{
            currentDate = Calendar.getInstance().get(Calendar.DATE);

            intent.putExtra("changeDate", String.valueOf(false));

            intent.putExtra("durationTime", String.valueOf(durationTime));
            intent.putExtra("time", String.valueOf(time));

            sendBroadcast(intent);
        }catch (Exception e) {
            // TODO: handle exception
        }
    }

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

    @Override
    public void onDestroy() {
        try {
            handler.removeCallbacks(sendUpdatesToUI);
            updateUIHandler.removeCallbacks(sendUpdatesToUIOnResume);
            durationTime = 0;
            time = 0;

            super.onDestroy();
        } catch (Exception e) { }

    }

    @Override
    public boolean stopService(Intent name) {
        handler.removeCallbacks(sendUpdatesToUI);
        updateUIHandler.removeCallbacks(sendUpdatesToUIOnResume);
        durationTime = 0;
        time = 0;

        return super.stopService(name);
    }


}