如何取消倒计时器停止工作的方法

时间:2016-05-25 05:29:04

标签: java android countdowntimer

我有用户设定播放时间的音乐列表。我想要一个按钮取消m倒计时器。 我测试某种方式,但它根本不起作用。 这是我的代码,可以播放时间。

public class Main扩展Activity {

public static int hour_device, minute_device;
public static int hour_user, minute_user;
Splash splash;
ListView listView;
Adaptor adaptor;
private MediaPlayer mediaPlayer;
static View lastview = null;
static MyIndexStore indexStore;

List<String> lines1 = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
static List<String> array_audio = new ArrayList<String>();

InputStream in;
BufferedReader reader;
String line = "1";
String[] tracks;
String[] names;
String[] infos;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    indexStore = new MyIndexStore(getApplicationContext());
    setContentView(R.layout.main_activity);


    splash = new Splash(this);
    splash.set_identity("1");


    initiate();
    mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a1);
    //lastview = null;
    listView = (ListView) findViewById(R.id.list);
    ReadText1();
    names = lines1.toArray(new String[0]);// = {"track one","the seconnd track","a nice track","name name name","the seconnd track","a nice track","name name name"};
    ReadText2();
    infos = lines2.toArray(new String[0]);
    tracks = array_audio.toArray(new String[0]);
    adaptor = new Adaptor(getApplicationContext(), tracks, names, infos);
    listView.setAdapter(adaptor);
    mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer arg0) {
            if (lastview != null) {
                ImageView play = (ImageView) lastview.findViewById(R.id.play_stop);
                play.setImageResource(R.drawable.n_btn_play_unselected);
            }
        }
    });
}

private static void initiate() {
    Field[] fields = R.raw.class.getFields();
    array_audio.clear();
    for (int count = 0; count < fields.length; count++) {
        array_audio.add("a" + (count + 1));
    }
}

private void play(int index) {
    mediaPlayer.release();
    index++;
    String s = "a" + index;
    Resources resources = getResources();
    final int resourceId = resources.getIdentifier(s, "raw", getPackageName());

    try {
        mediaPlayer = MediaPlayer.create(this, resourceId);
        mediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
protected void onPause() {
    mediaPlayer.release();
    listView.invalidateViews();
    super.onPause();
}


private void ReadText1() {
    lines1.clear();
    line = "1";
    try {
        in = this.getAssets().open("names.txt");
        reader = new BufferedReader(new InputStreamReader(in));
        while (line != null) {
            line = reader.readLine();
            if (line != null)
                lines1.add(line);
            else
                break;
        }

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

private void ReadText2() {
    lines2.clear();
    line = "1";
    try {
        in = this.getAssets().open("infos.txt");
        reader = new BufferedReader(new InputStreamReader(in));
        while (line != null) {
            line = reader.readLine();
            if (line != null)
                lines2.add(line);
            else
                break;
        }

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


public class Adaptor extends ArrayAdapter<String> {

    private final Context context;
    private final String[] tracks;
    private final String[] names;
    private final String[] infos;
    private HashMap<Integer,String> textMap;
    Typeface type_face;


    public Adaptor(Context context, String[] tracks, String[] names, String[] infos) {
        super(context, R.layout.track, tracks);
        this.context = context;
        this.tracks = tracks;
        this.names = names;
        this.infos = infos;
        type_face = Typeface.createFromAsset(context.getAssets(), "BTitrBd.ttf");
        this.textMap = new HashMap<>();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View rowView = inflater.inflate(R.layout.track, parent, false);

        TextView name = (TextView) rowView.findViewById(R.id.track_name);
        final TextView time = (TextView) rowView.findViewById(R.id.time);
        //populate the textview from map
        if(textMap!=null && textMap.get(new Integer(position))!=null){
            time.setText(textMap.get(new Integer(position)));
        }
        name.setText(names[position]);
        name.setTypeface(type_face);
        name.setTypeface(type_face);
        final ImageView ringtone = (ImageView) rowView.findViewById(R.id.ringtone);
        if (position == indexStore.getindex())
            ringtone.setImageResource(R.drawable.n_btn_ringtone_seted);
        final ImageView play = (ImageView) rowView.findViewById(R.id.play_stop);
        ringtone.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                LayoutInflater factory = LayoutInflater.from(Main.this);
                final View deleteDialogView = factory.inflate(
                        R.layout.mylayout, null);
                final AlertDialog deleteDialog = new AlertDialog.Builder(Main.this).create();
                deleteDialog.setView(deleteDialogView);

                TextView device_time = (TextView) deleteDialogView.findViewById(R.id.current_time);
                Calendar c = Calendar.getInstance();
                int hour = c.get(Calendar.HOUR_OF_DAY);
                int minute = c.get(Calendar.MINUTE);
                hour_device = hour;
                minute_device = minute;
                device_time.setText(hour_device + ":" + minute_device);

                deleteDialogView.findViewById(R.id.set).setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        TimePicker timePicker = (TimePicker) deleteDialogView.findViewById(R.id.timepicker);
                        timePicker.setIs24HourView(true);
                        hour_user = timePicker.getCurrentHour();
                        minute_user = timePicker.getCurrentMinute();
                        String time1 = hour_device + ":" + minute_device;
                        String time2 = hour_user + ":" + minute_user;
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                        Date date1 = null;
                        try {
                            date1 = format.parse(time1);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        Date date2 = null;
                        try {
                            date2 = format.parse(time2);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        long result = date2.getTime() - date1.getTime();


                        new CountDownTimer(result, 1000) {

                            public void onTick(long millisUntilFinished) {
                                time.setText(("seconds remaining: " + millisUntilFinished / 1000));
                                //create HashMap<Integer,String> textMap at the constructer of the adapter
                                //now fill this info int'o it
                                textMap.put(new Integer(position), "seconds remaining: " + millisUntilFinished / 1000);
                                //notify about the data change
                                notifyDataSetChanged();

                            }

                            public void onFinish() {
                                time.setVisibility(View.INVISIBLE);
                                //create HashMap<Integer,String> textMap at the constructer of the adapter
                                //now fill this info into it
                                textMap.put(new Integer(position),null);
                                //notify about the data change
                                notifyDataSetChanged();
                                Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
                                if (rowView != lastview || mediaPlayer == null) {
                                    play(position);
                                    if (lastview != null)
                                        lastview = rowView;
                                } else {
                                    play.setImageResource(R.drawable.n_btn_play_unselected);
                                    mediaPlayer.release();
                                    lastview = null;
                                }


                            }

                        }.start();
                        deleteDialog.dismiss();
                    }
                });


                deleteDialog.show();


            }
        });

        play.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (rowView != lastview || mediaPlayer == null) {
                    play(position);
                    if (lastview != null)
                        lastview = rowView;
                } else {
                    play.setImageResource(R.drawable.n_btn_play_unselected);
                    mediaPlayer.release();

                    lastview = null;
                }
            }
        });
        return rowView;
    }





}

}

2 个答案:

答案 0 :(得分:1)

使倒计时器成为实例变量;

private CountDownTimer timer;

然后将你的计数委托给这个变量:

@Override
public void onClick(View v) {
    ...
    timer = new CountDownTimer(result, 1000) {
        ...
    }
}

现在您可以随时停止计时器:

timer.cancel();

答案 1 :(得分:0)

检查此代码,工作成功 从这里打电话

       timer = new CounterClass(timeInmilles, 1000);
                    timer.start();

CounterClass就在这里

  public class CounterClass extends CountDownTimer {
       public CounterClass(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {

    }
      public void onTick(long millisUntilFinished) {
      }
}

用于取消见下面的行

timer.cancel()