Android Studio多功能闹钟[android源码]
程序员文章站
2022-07-12 10:35:40
...
多功能闹钟App
简 介
此多功能闹钟界面采用TabHost框架,头部包含分别用LinearLayout水平布局显示四个标签闹钟,时钟,计时器和秒表,FrameLayout框架内部采用LinearLayout垂直布局。功能事件的基本实现分别有AlarmView类,AlarmReceiver类,PlayAlarmAty类, TimeView类和StopWatch类完成。
主 要 技 术
此多功能闹钟界面采用TabHost 框架,头部包含分别用LinearLayout水平布局显示四个标签闹钟,时钟,计时器和秒表,FrameLayout框架内部采用LinearLayout垂直布局。功能事件的基本实现分别有AlarmView类,AlarmReceiver类,PlayAlarmAty类, TimeView类和StopWatch类完成。:
- 闹钟界面的界面设计 ,闹钟界面使用一个Button按钮和ListvView,设置的闹钟由ListView的Item项来呈现出来;开始按钮设置监听,当点击添加闹钟按钮时触发按钮监听引用TimePickerDialog将弹出一个设置时间对话框,当设置时间后点击ok按钮将触发监听中添加saveAlarmList()存储方法保存数据;闹钟功能使用SharedPreferences类存取数据,使用创建的saveAlarmList()存储方法和readSavedAlarmList()读取方法来实现闹钟设定数据的存取,使用创建AlarmData工具类进行数据存放。闹钟的设置及具体的响应采用AlarmView类,AlarmReceiver类和PlayAlarmAty类;AlarmView类中通过listview的setOnItemLongClickListener方法监听每个Item项,当检测到长按水平弹出到闹钟的操作对话框,通过弹出对话框中setNegativeButton按钮,删除Item项目闹钟;闹钟响铃通过AlarmManager的实例对象,根据我们设定时间来实现响铃。该闹钟是利用了页面跳转来实现的响铃,通过getActivity()方法来获取PendingIntent对象,将设定好的时间通过数据跳转到响铃的页面,通过弹出一个提示对话框和mediaPlayer 组件播放音乐来实现响铃功能。
- 时钟功能的实现简单引用了DigitalClock 显示时钟时间。
- 计时器功能具体实现是通过TimerView类来实现的,类中设置了开始,暂停和重置方法,然后监听开始,暂停,重置按钮来引用对应方法来实现计时器的计时功能,计时时间到采用Handle机制来新建一个对话框提醒时间到。
- 秒表的具体实现通过StopWatch 类来实现,类中设置了开始,暂停,复位和重置按钮的监听,监听直接引用了Chronometer 的start,stop,setBase和setFormat等方法实现秒表的功能。
界面截图
主要代码
主页面,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.
作者信息
- aaa@qq.com
- Authors
- 罄宇
下一篇: vins-mono运行步骤及实验演示
推荐阅读
-
Android实现下载zip压缩文件并解压的方法(附源码)
-
Android studio点击跳转WebView详解
-
超简单实现Android自定义Toast示例(附源码)
-
Android仿微信朋友圈全文收起功能示例(附源码)
-
Mac OS下为Android Studio编译FFmpeg解码库的详细教程
-
Mac Android Studio快捷键整理
-
月下载量上千次Android实现二维码生成器app源码分享
-
Android编程实现手绘及保存为图片的方法(附demo源码下载)
-
Android Studio中快捷键实现try catch等功能包含代码块的实现方法
-
Android Studio生成函数注释的实现方法