此多功能闹钟界面采用TabHost框架,头部包含分别用LinearLayout水平布局显示四个标签闹钟,时钟,计时器和秒表,FrameLayout框架内部采用LinearLayout垂直布局。功能事件的基本实现分别有AlarmView类,AlarmReceiver类,PlayAlarmAty类, TimeView类和StopWatch类完成。
此多功能闹钟界面采用TabHost 框架,头部包含分别用LinearLayout水平布局显示四个标签闹钟,时钟,计时器和秒表,FrameLayout框架内部采用LinearLayout垂直布局。功能事件的基本实现分别有AlarmView类,AlarmReceiver类,PlayAlarmAty类, TimeView类和StopWatch类完成。:
主页面,MainActivity 代码
.
// An highlighted block
public class MainActivity extends Activity {
private TabHost tabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost=(TabHost)findViewById(android.R.id.tabhost);
tabHost.setup();
tabHost.addTab(tabHost.newTabSpec("tabAlarm").setIndicator("闹钟").setContent(R.id.tabAlarm));
tabHost.addTab(tabHost.newTabSpec("tabTime").setIndicator("时钟").setContent(R.id.tabTime));
tabHost.addTab(tabHost.newTabSpec("tabTimer").setIndicator("计时器").setContent(R.id.tabTimer));
tabHost.addTab(tabHost.newTabSpec("tabStopWatch").setIndicator("秒表").setContent(R.id.tabStopWatch));
}
}
主页面,PlayAlarmAty 代码
.
// An highlighted block
public class PlayAlarmAty extends Activity {
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp = MediaPlayer.create(this,R.raw.clockmusic2);
mp.start();
new AlertDialog.Builder(PlayAlarmAty.this)
.setIcon(R.mipmap.ic_launcher)
.setTitle("闹钟")
.setMessage("快完成你制定的计划吧!!!")
.setNegativeButton("关闭", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
PlayAlarmAty.this.finish();
mp.stop();
}
})
.show();
}
@Override
protected void onPause(){
super.onPause();
finish();
}
protected void onDestroy(){
super.onDestroy();
mp.stop();
mp.release();
}
}
主页面,AlarmView 代码
.
// An highlighted block
public class AlarmView extends LinearLayout {
public AlarmView(Context context,AttributeSet attrs,int defStyle){
super(context,attrs,defStyle);
init();
}
public AlarmView(Context context,AttributeSet attrs){
super(context,attrs);
init();
}
public AlarmView(Context context ){
super(context);
init();
}
private void init(){
alarmManager= (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
}
@Override
protected void onFinishInflate(){
super.onFinishInflate();
btAddAlarm=(Button) findViewById(R.id.btnAddAlarm);
lvAlarmList=(ListView) findViewById(R.id.lvAlarmList);
adapter=new ArrayAdapter<AlarmData>(getContext(),android.R.layout.simple_list_item_1);
lvAlarmList.setAdapter(adapter);
readSavedAlarmList();
btAddAlarm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
addAlarm();
}
});
lvAlarmList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(getContext()).setTitle("操作").setItems(new CharSequence[]{"删除"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
deleteAlarm(position);
break;
default:
break;
}
}
}).setNegativeButton("取消",null).show();
return true;
}
});
}
private void deleteAlarm(int position){
AlarmData ad=adapter.getItem(position);
adapter.remove(ad);
saveAlarmList(); alarmManager.cancel(PendingIntent.getBroadcast(getContext(),ad.getId(),new Intent(getContext(),AlarmReceiver.class),0));
}
private void addAlarm(){
Calendar c =Calendar.getInstance();
new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
calendar.set(Calendar.MINUTE,minute);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
Calendar currentTime=Calendar.getInstance();
if (calendar.getTimeInMillis()<=currentTime.getTimeInMillis()){
calendar.setTimeInMillis(calendar.getTimeInMillis()+24*60*60*1000);
}
AlarmData ad=(new AlarmData(calendar.getTimeInMillis()));
adapter.add(ad);
alarmManager.set(AlarmManager.RTC_WAKEUP,
ad.getTime(),
PendingIntent.getBroadcast(getContext(),
ad.getId(),
new Intent(getContext(),AlarmReceiver.class),0));
saveAlarmList();
}
},c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),true).show();
}
private void saveAlarmList(){
SharedPreferences.Editor editor =getContext().getSharedPreferences(AlarmView.class.getName(),Context.MODE_PRIVATE).edit();
StringBuffer sb = new StringBuffer();
for (int i=0;i<adapter.getCount();++i) {
sb.append(adapter.getItem(i).getTime()).append(",");
}
if(sb.length()>1) {
String content = sb.toString().substring(0, sb.length() - 1);
editor.putString(KEY_ALARM_LIST, content);
System.out.println(content);
}else {
editor.putString(KEY_ALARM_LIST,null);
}
editor.commit();
}
private void readSavedAlarmList(){
SharedPreferences sp=getContext().getSharedPreferences(AlarmView.class.getName(),Context.MODE_PRIVATE);
String content=sp.getString(KEY_ALARM_LIST,null);
if (content!=null){
String[] timeString=content.split(",");
for (String string:timeString){
adapter.add(new AlarmData(Long.parseLong(string)));
}
}
}
private static final String KEY_ALARM_LIST="alarmlist";
private Button btAddAlarm;
private ListView lvAlarmList;
private ArrayAdapter<AlarmData> adapter;
private AlarmManager alarmManager;
private static class AlarmData{
public AlarmData(long time){
this.time=time;
date=Calendar.getInstance();
date.setTimeInMillis(time);
timeLable=String.format("%d月%d日 %d:%d",
date.get(Calendar.MONTH)+1,
date.get(Calendar.DAY_OF_MONTH),
date.get(Calendar.HOUR_OF_DAY),
date.get(Calendar.MINUTE));
}
public long getTime(){
return time;
}
public String getTimeLable(){
return timeLable;
}
@Override
public String toString(){
return getTimeLable();
}
public int getId() {
return (int)(getTime()/1000/60);
}
private String timeLable="";
private long time=0;
private Calendar date;
}
}
计时器页面,TimerView 代码
.
// An highlighted block
public class TimerView extends LinearLayout{
private Button btnStart, btnPause, btnReset;
private EditText etHour, etMin, etSec;
private Timer timer = new Timer ( );
private TimerTask timerTask = null;
private int allTimerCount = 0;
private static final int MSG_WHAT_TIME_IS_UP = 1;
private static final int MSG_WHAT_TIME_TICK = 2;
public TimerView(Context context , @Nullable AttributeSet attrs , int defStyleAttr) {
super ( context , attrs , defStyleAttr );
}
public TimerView(Context context , @Nullable AttributeSet attrs) {
super ( context , attrs );
}
public TimerView(Context context) {
super ( context );
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
btnPause = (Button) findViewById(R.id.btnPause);
btnPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopTimer();
btnPause.setVisibility(View.GONE);
btnStart.setVisibility ( View.VISIBLE );
btnReset.setVisibility(View.VISIBLE);
}
});
btnReset = (Button) findViewById(R.id.btnReset);
btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopTimer();
etHour.setText("0");
etMin.setText("0");
etSec.setText("0");
btnReset.setVisibility(View.GONE);
btnPause.setVisibility(View.GONE);
btnStart.setVisibility(View.VISIBLE);
}
});
btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startTimer();
btnStart.setVisibility(View.GONE);
btnPause.setVisibility(View.VISIBLE);
btnReset.setVisibility(View.VISIBLE);
}
});
etHour = (EditText) findViewById(R.id.etHour);
etMin = (EditText) findViewById(R.id.etMin);
etSec = (EditText) findViewById(R.id.etSec);
etHour.setText("00");
etHour.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!TextUtils.isEmpty(s)) {
int value = Integer.parseInt(s.toString());
if (value>59) {
etHour.setText("59");
}else if (value<0) {
etHour.setText("0");
}
}
checkToEnableBenStart ();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
etMin.setText("00");
etMin.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!TextUtils.isEmpty(s)) {
int value = Integer.parseInt(s.toString());
if (value>59) {
etMin.setText("59");
}else if (value<0) {
etMin.setText("0");
}
}
checkToEnableBenStart ();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
etSec.setText("00");
etSec.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!TextUtils.isEmpty(s)) {
int value = Integer.parseInt(s.toString());
if (value>59) {
etSec.setText("59");
}else if (value<0) {
etSec.setText("0");
}
}
checkToEnableBenStart ();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
btnStart.setVisibility(View.VISIBLE);
btnStart.setEnabled(false);
btnPause.setVisibility(View.GONE);
btnReset.setVisibility(View.GONE);
}
private void checkToEnableBenStart() {
btnStart.setEnabled ( (!TextUtils.isEmpty ( etHour.getText ( ) ) && Integer.parseInt ( etHour.getText ( ).toString ( ) ) > 0) ||
(!TextUtils.isEmpty ( etMin.getText ( ) ) && Integer.parseInt ( etMin.getText ( ).toString ( ) ) > 0) ||
(!TextUtils.isEmpty ( etSec.getText ( ) ) && Integer.parseInt ( etSec.getText ( ).toString ( ) ) > 0) );
}
private void startTimer() {
allTimerCount = Integer.parseInt ( etHour.getText ( ).toString ( ) ) * 60 * 60 + Integer.parseInt ( etMin.getText ( ).toString ( ) ) * 60 + Integer.parseInt ( etSec.getText ( ).toString ( ) );
if (timerTask == null) {
timerTask = new TimerTask ( ) {
@Override
public void run() {
allTimerCount--;
handler.sendEmptyMessage ( MSG_WHAT_TIME_TICK );
if (allTimerCount == 0) {
handler.sendEmptyMessage ( MSG_WHAT_TIME_IS_UP );
stopTimer ( );
}
}
};
timer.schedule ( timerTask , 1000 , 1000 );
}
}
private void stopTimer() {
if (timerTask != null) {
timer.cancel ( );
timerTask = null;
}
}
private android.os.Handler handler = new android.os.Handler ( ) {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_WHAT_TIME_TICK:
int hour = allTimerCount / 60 / 60;
int min = (allTimerCount / 60) % 60;
int sec = allTimerCount % 60;
etHour.setText ( hour + "" );
etMin.setText ( min + "" );
etSec.setText ( sec + "" );
break;
case MSG_WHAT_TIME_IS_UP:
new AlertDialog.Builder ( getContext ( ) ).setTitle("Timer" )
.setMessage ( "时间到" )
.setNegativeButton ( "返回" , null )
.show ( );
btnStart.setVisibility ( View.VISIBLE );
btnPause.setVisibility ( View.GONE );
btnReset.setVisibility ( View.GONE );
break;
default:
break;
}
}
};
}
秒表页面,StopWatch 代码
.
// An highlighted block
public class StopWatch extends LinearLayout {
private Chronometer myChronometer;
private Button butStart;
private Button butStop;
private Button butResume;
private Button butReset;
public StopWatch(Context context , @Nullable AttributeSet attrs) {
super ( context , attrs );
}
@Override
protected void onFinishInflate() {
super.onFinishInflate ( );
myChronometer = (Chronometer) super.findViewById ( R.id.myChronometer );
butStart = (Button) super.findViewById ( R.id.butStart );
butStop = (Button) super.findViewById ( R.id.butPause );
butResume=(Button) super.findViewById ( R.id.butResume );
butReset = (Button) super.findViewById ( R.id.butReset );
butStart.setVisibility ( View.VISIBLE );
butStop.setVisibility ( View.GONE);
butResume.setVisibility ( View.GONE);
butReset.setVisibility ( View.GONE );
butStart.setOnClickListener ( new OnClickListener ( ) {
@Override
public void onClick(View v) {
myChronometer.setBase ( (long) ((long) (SystemClock.elapsedRealtime ()-
(long)Double.parseDouble (myChronometer.getText ().toString ().split ( ":")[0])*60*1000)-
(long)Double.parseDouble ( myChronometer.getText ().toString ().split (":" )[1] )*1000) );
myChronometer.start ();
butStart.setVisibility ( View.GONE );
butResume.setVisibility ( View.VISIBLE );
butStop.setVisibility ( View.VISIBLE);
butReset.setVisibility ( View.GONE );
}
} );
butStop.setOnClickListener ( new OnClickListener ( ) {
@Override
public void onClick(View v) {
myChronometer.stop ();
butStop.setVisibility ( View.GONE );
butResume.setVisibility ( View.GONE);
butStart.setVisibility ( View.VISIBLE );
butReset.setVisibility ( View.VISIBLE );
}
} );
butReset.setOnClickListener ( new OnClickListener ( ) {
@Override
public void onClick(View v) {
myChronometer.setBase ( SystemClock.elapsedRealtime ( ) );
butReset.setVisibility ( View.GONE );
butResume.setVisibility ( View.GONE );
butStart.setVisibility ( View.VISIBLE );
butStop.setVisibility ( View.GONE);
}
} );
butResume.setOnClickListener ( new OnClickListener ( ) {
@Override
public void onClick(View v) {
myChronometer.setFormat ( "%s" );
myChronometer.setBase ( SystemClock.elapsedRealtime ( ) );
butStop.setVisibility ( View.VISIBLE );
butReset.setVisibility ( View.GONE );
butResume.setVisibility ( View.VISIBLE);
butStart.setVisibility ( View.GONE );
}
} );
}
}
源码下载链接: link.