简体   繁体   中英

Multiple Timers in Android Application

I'm writing this post because I'm desperate and do not have any more ideas. I have a task to implement an Android application that has to display ten timers in one screen. These timers can be stopped, and reset. The countdown of the timers should be kept even if the app is exited( I know, that can be done using Services). But I don't have any idea about how to bind my Timer class with the service. Maybe somebody can give me any idea? Here is my Timer class

    package pavel.timer;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;

import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import android.widget.TextView;


public class Timer implements Parcelable{
    private boolean isActivated;
    private boolean isStopped;
    private Context context;
    private CountDownTimer timer;
    private String name;
    private long timeToGo;
    private long untilFinish;
    private String sound;
    private AlarmManager alarmMgr;
    private PendingIntent pending;
    private MediaPlayer mediaPlayer;
    Timer(){
        isActivated = false;
        isStopped = false;
        name = "";
    }
    Timer(String _name, long _timeToGo, String _sound){
        isStopped = true;
        isActivated = false;
        name = _name;
        timeToGo = _timeToGo;
        sound = _sound;


    }
    public void activate(long future, long interval,final TextView text,String _name,String _sound, Context _context,TimerActivity _ac){
        SystemClock.uptimeMillis();
        sound = _sound;
        timeToGo = future;
        untilFinish = timeToGo;
        context = _context;
        final TimerActivity ac = _ac;
        alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, wake_up.class);
        pending = PendingIntent.getBroadcast(context, 0, intent, 0);

        alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() +
                future, pending);
        timer = new CountDownTimer(future, interval){
             public void onTick(long millisUntilFinished) {
                 if(!isStopped){
                untilFinish = millisUntilFinished;
                 Time time = new Time(millisUntilFinished - 3 * 3600000);
                 String textTime = "";
                 Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
                 calendar.setTime(time);   // assigns calendar to given date 
                 int hrs = calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
                 int min = calendar.get(Calendar.MINUTE);
                 int sec = calendar.get(Calendar.SECOND);
                 if(millisUntilFinished > 3600000){
                     if(text.getTextSize() == 46)
                         text.setTextSize(36);
                     else
                         text.setTextSize(26); 
                 }
                 if(hrs!=0)
                     textTime+=String.format("%02d",hrs)+":";
                 if(min!=0||hrs!=0)
                     textTime+=String.format("%02d",min)+":";
                 textTime+=String.format("%02d",sec);
                 text.setText(textTime);
                 }
             }

             public void onFinish() {
                 if(!isStopped){
                     if(!TimerActivity.active){
                        Intent i = new Intent(context,TimerActivity.class);
                        context.startActivity(i);
                     }
                     else{
                         ac.setVisible(true);
                     }
                 text.setText("DONE!");
                // Uri myUri = Uri.parse(sound);
                 mediaPlayer = new MediaPlayer();
                 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                 mediaPlayer.setVolume(1.0f, 1.0f);
                 try {
                    mediaPlayer.setDataSource(sound);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                 try {
                    mediaPlayer.prepare();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                 mediaPlayer.start();
                 }
                 }
    };
    name = _name;
    isActivated = true;
    timer.start();
}
    public boolean isActivated(){
        return isActivated;
    }
    public String getTime(){
        Time time = new Time(untilFinish);
         String textTime = "";
         Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
         calendar.setTime(time);   // assigns calendar to given date 
         int hrs = calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
         int min = calendar.get(Calendar.MINUTE);
         int sec = calendar.get(Calendar.SECOND);

         if(hrs!=0)
             textTime+=String.format("%02d",hrs)+":";
         if(min!=0||hrs!=0)
             textTime+=String.format("%02d",min)+":";
         textTime+=String.format("%02d",sec);
        return textTime;

    }
    public String getName() {
        return name;
    }
    public void stop() {
        timer.cancel();
        timer = null;
        isStopped = true;
        if(mediaPlayer!=null)
            mediaPlayer.stop();
    }
    public boolean isStopped() {
        return isStopped;
    }
    public long getTimer() {
        return timeToGo;
    }
    public void start() {
        isStopped = false;
    }
    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    /** save object in parcel */
    public void writeToParcel(Parcel out, int flags) {
        ArrayList<Boolean> flag = new ArrayList<Boolean>();
        flag.add(isActivated);
        flag.add(isStopped);
        ArrayList<Long> longVal = new ArrayList<Long>();
        longVal.add(timeToGo);
        longVal.add(untilFinish);
        out.writeArray(longVal.toArray());
        List<String> data = new ArrayList<String>();
        data.add(name);
        data.add(sound);
        out.writeStringList(data);
    }

    public static final Parcelable.Creator<Timer> CREATOR
            = new Parcelable.Creator<Timer>() {
        public Timer createFromParcel(Parcel in) {
            return new Timer(in);
        }

        public Timer[] newArray(int size) {
            return new Timer[size];
        }
    };

    /** recreate object from parcel */
    private Timer(Parcel in) {
        ArrayList<String> data =new ArrayList<String>();
        in.readStringList(data);
        isActivated = false;
        isStopped = true;
        name = (String)data.get(0);
        sound = (String)data.get(1);
        long[] longVal = new long[2];
        in.readLongArray(longVal);
        timeToGo = longVal[0];
        untilFinish = longVal[1];  
        boolean[] flag = new boolean[2];
        in.readBooleanArray(flag);
        isActivated = flag[0];
        isStopped = flag[1];
    }
    public String getSound() {
        // TODO Auto-generated method stub
        return sound;
    }
    public long getUntilFinish() {
        // TODO Auto-generated method stub
        return untilFinish;
    }
    public String toString(){
        String res = "";
        return res;
    }
}

First of all you should create a service extending the Service class from the Android framework, once created, you can start as many instances as you want to, and then bind them to establish a connection with the activity (or any other object). This answer explains how to start, stop and bind a service: Bind service to activity in Android , you can also find implementation samples here: http://www.vogella.com/tutorials/AndroidServices/article.html#service_activitybinding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM