간단하게 Android 알 람 기능 구현

13235 단어 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; 
 //      
} 
실행 효과 도




이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기