简单实现Android闹钟功能
作者:我爱酸奶奶奶奶奶
这篇文章主要教大家如何简单实现Android闹钟功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
闹钟的简单实现,只有显示时间和设置闹钟。
AlarmView
package com.example.lenovo.clock2; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.icu.util.Calendar; import android.os.Build; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v7.app.AlertDialog; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TimePicker; import java.util.Date; /** * Created by lenovo on 2017/11/20. */ //闹钟 public class AlarmView extends LinearLayout { // public AlarmView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } public AlarmView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public AlarmView(Context context) { super(context); init(); } private void init(){ alarmManager= (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE); } @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onFinishInflate() { super.onFinishInflate(); btnAddAlarm=findViewById(R.id.btnAddAlarm); lvAlarmList=findViewById(R.id.lvAlarmList); adapter=new ArrayAdapter<AlarmView.AlarmData>(getContext(),R.layout.support_simple_spinner_dropdown_item); lvAlarmList.setAdapter(adapter); readSavedAlarmList(); //adapter.add(new AlarmData(System.currentTimeMillis())); btnAddAlarm.setOnClickListener(new OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onClick(View view) { addAlarm(); } }); lvAlarmList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){ @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long id) { new AlertDialog.Builder(getContext()).setTitle("操作选项").setItems(new CharSequence[]{"删除"}, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, 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)); } @RequiresApi(api = Build.VERSION_CODES.N) 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); /* 第一个参数 RTC操作系统时间为启动时间点,WAKEUP系统休眠时同样执行 第二个参数 什么时候启动 第三个参数 启动之后什么时间再次启动 第四个参数 Pendingintent挂起的Intent,不立即执行 */ alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, ad.getTime(),//当前时间当做请求码 5*60*1000, //执行广播 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); }else{ editor.putString(KEY_ALARM_LIST,null); } editor.commit(); } //读取已存数据 @RequiresApi(api = Build.VERSION_CODES.N) 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[] timeStrings=content.split(","); for(String string:timeStrings){ adapter.add(new AlarmData(Long.parseLong(string))); } } } private static final String KEY_ALARM_LIST="alarmList"; private Button btnAddAlarm; private ListView lvAlarmList; private ArrayAdapter<AlarmData> adapter; private AlarmManager alarmManager;//系统的闹钟服务 private static class AlarmData{ //闹钟所要响起的时间 @RequiresApi(api = Build.VERSION_CODES.N) 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,//getMonth的返回值是从0开始的 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);//精确到分钟,getTime为毫秒 } //获取时间的标签 private String timeLable=""; private long time=0; private Calendar date; } }
TimeView
package com.example.lenovo.clock2; import android.content.Context; import android.icu.util.Calendar; import android.os.Build; import android.os.Handler; import android.os.Message; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; /** * Created by lenovo on 2017/11/20. */ //时钟 显示目前的时间 public class TimeView extends LinearLayout { public TimeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public TimeView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public TimeView(Context context) { super(context); } @Override protected void onFinishInflate() { super.onFinishInflate(); tvTime=findViewById(R.id.tvTime); tvTime.setText("这里显示时间"); timerHander.sendEmptyMessage(0); } //判断可见属性是否发生改变 @Override protected void onVisibilityChanged(View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if(getVisibility()== View.VISIBLE){ timerHander.sendEmptyMessage(0);//可见,则呈现 }else{ timerHander.removeMessages(0);//否则移除所有消息 } } //刷新时间 @RequiresApi(api = Build.VERSION_CODES.N) private void refreshTime(){ Calendar c=Calendar.getInstance(); tvTime.setText(String.format("%d:%d:%d",c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),c.get(Calendar.SECOND))); } //Hander每隔一秒执行一次 private Handler timerHander=new Handler(){ @RequiresApi(api = Build.VERSION_CODES.N) @Override public void handleMessage(Message msg) { refreshTime(); //若为当前页面,则刷新;否则,没有必要刷新 if (getVisibility()== View.VISIBLE) { timerHander.sendEmptyMessageDelayed(0, 1000);//1000毫秒后再执行handleMessage方法 } }; }; private TextView tvTime; }
AlarmReceiver
package com.example.lenovo.clock2; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * Created by lenovo on 2017/11/23. */ public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { AlarmManager am= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.cancel(PendingIntent.getBroadcast(context,getResultCode(),new Intent(context,AlarmReceiver.class),0)); Intent i=new Intent(context,PlayAlarmAty.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } }
MainActivity
package com.example.lenovo.clock2; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TabHost; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabHost= (TabHost) findViewById(R.id.tabhost); tabHost.setup(); //setContent()为声明内容 tabHost.addTab(tabHost.newTabSpec("tabTime").setIndicator("时钟").setContent(R.id.tabTime)); tabHost.addTab(tabHost.newTabSpec("tabAlarm").setIndicator("闹钟").setContent(R.id.tabAlarm)); tabHost.addTab(tabHost.newTabSpec("tabTimer").setIndicator("计时器").setContent(R.id.tabTimer)); tabHost.addTab(tabHost.newTabSpec("tabStopWatch").setIndicator("秒表").setContent(R.id.tabStopWatch)); } private TabHost tabHost; }
PlayAlarmAty
package com.example.lenovo.clock2; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.support.annotation.Nullable; /** * Created by lenovo on 2017/11/25. */ public class PlayAlarmAty extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alarm_player_aty); mp=MediaPlayer.create(this,R.raw.mine); mp.start(); } @Override protected void onPause() { super.onPause(); finish(); } @Override protected void onDestroy() { super.onDestroy(); mp.stop(); mp.release(); } private MediaPlayer mp; //音乐播放器 }
运行效果图
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。