设置一个公共类

时间:2013-12-21 18:15:27

标签: java android sdk countdowntimer

我的应用程序中有四个类具有相同的方法。基本上代码显示CountDownTimer并在计时器开始时播放音乐。当计时器用完时,音乐停止。所有四个活动都具有相同的布局文件。代码如下:

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class Vyala extends Activity implements OnClickListener{
private static final int MILLIS_PER_SECOND = 1000;
private static final int SECONDS_TO_COUNTDOWN = 1;
TextView Time;
int totalTimeText;
MediaPlayer mp;
Button startTimer, howTo;
MediaPlayer bck;
protected CountDownTimer PushUpTimer;
protected int speed;
int PracticeCount;
AudioManager am;
SeekBar sb;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.abhyasa);
    getRefs();
    setTotalTime();
    startTimer.setOnClickListener(this);

}

private void getRefs() {

    Time=(TextView)findViewById(R.id.tvTime);

    startTimer=(Button) findViewById (R.id.bStart);
    howTo=(Button) findViewById(R.id.bHowTo);
    howTo.setOnClickListener(this);
    am=(AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mp = MediaPlayer.create(this, R.raw.sound2);
    sb.setMax(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
    sb.setProgress(am.getStreamVolume(AudioManager.STREAM_MUSIC));
    sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
        {
//change the volume, displaying a toast message containing the current volume and    playing a feedback sound
      am.setStreamVolume(AudioManager.STREAM_MUSIC,progress, 0);
        }
  });
}

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event)
      {
  //if one of the volume keys were pressed
         if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode ==   KeyEvent.KEYCODE_VOLUME_UP)
  {
        //change the seek bar progress indicator position  
             sb.setProgress(am.getStreamVolume(AudioManager.STREAM_MUSIC));
  }
  //propagate the key event
  return super.onKeyDown(keyCode, event);
  }




   private void getTheCount() {
    // TODO Auto-generated method stub
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    int c=prefs.getInt("practicecount", 5);
    PracticeCount=c;


    }


private void getSpeed() {
    // TODO Auto-generated method stub
    SharedPreferences     getPref=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String values=getPref.getString("list","3");
    if(values.contentEquals("1")){
        speed=1;
    }else if(values.contentEquals("5")){
        speed=5;
    }else{
        speed=3;
    }   
}

private void setTotalTime() {
    // TODO Auto-generated method stub
    getSpeed();
    getTheCount();
    totalTimeText=PracticeCount*speed;
    Time.setText(String.format("%02d",  totalTimeText / 60) + ":" +     String.format("%02d",  totalTimeText % 60));
}

    @Override
public void onClick(View v) {
    // TODO Auto-generated method stub
        if(v==startTimer){
        try {
              showTimer(PracticeCount*speed*SECONDS_TO_COUNTDOWN * MILLIS_PER_SECOND);

            } catch (NumberFormatException e) {
              // method ignores invalid (non-integer) input and waits
              // for something it cant use
            }
        }
        }   
    private void showTimer(int countdownMillis) {
          if(PushUpTimer != null) { PushUpTimer.cancel(); }
          PushUpTimer = new CountDownTimer(countdownMillis, MILLIS_PER_SECOND) {
          @Override
          public void onTick(long millisUntilFinished) {
              mp.start();
              long seconds = millisUntilFinished / 1000;
              Time.setText(String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60));

          }
          @Override
            public void onFinish() {
              Time.setText("KABOOM!");
              mp.release();
            }
          }.start();
        }   
}

这是布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/tvTime"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:padding="10dip"
    android:text="@string/starttime"
    android:textSize="60sp" />

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/tvTime"
android:layout_alignParentLeft="true"
android:orientation="horizontal" >

<Button
    android:id="@+id/bStart"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_above="@+id/tvTime"
    android:layout_alignLeft="@+id/bPause"
    android:layout_marginBottom="21dp"
    android:layout_marginLeft="24dp"
    android:text="Start" />

<Button
    android:id="@+id/bPause"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/bStart"
    android:layout_alignBottom="@+id/bStart"
    android:layout_alignLeft="@+id/bHowTo"
    android:layout_marginLeft="34dp"
    android:text="Pause" />
</LinearLayout>

<TextView
android:id="@+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/bHowTo"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:text="25"
android:textSize="80sp" />

<Button
android:id="@+id/bHowTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="78dp"
android:layout_toRightOf="@+id/count"
android:text="How" />
   </RelativeLayout>

如何设置所有四个活动都可以实现的公共类?因为它节省了空间并且是更好的编码方式。我读到创建一个片段是一个很好的解决方案,但我无法理解android开发者网站提供的文档 如果您可以提供有关样品编码的指导,我们将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

根据我的理解,这应该是有用的,也是你想要的。

public class redundant {

private Context _context;

    public redundant(Context context){
        this._context = context;
    }

     private void showTimer(int countdownMillis,MediaPlayer m,TextView v) {
              if(PushUpTimer != null) { PushUpTimer.cancel(); }
              PushUpTimer = new CountDownTimer(countdownMillis, MILLIS_PER_SECOND) {
              @Override
              public void onTick(long millisUntilFinished) {
                  m.start();
                  long seconds = millisUntilFinished / 1000;
                  Time.setText(String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60));

              }
              @Override
                public void onFinish() {
                  v.setText("KABOOM!");
                  m.release();
                }
              }.start();
            } 
}

在活动中使用它:

Redundant r = new Redundant(activity.this);
r.showTimer(2000,mediaplayerobject,textview)