Android菜鸟的成长笔记(25)——可爱的小闹钟

摘要:

这一篇主要使用系统为我们提供的一个服务AlarmManager来制作一个Android小闹钟,同时还涉及到了自定义主题、判断第一次启动应用、自定义动画、对话框、制作指导滑动页面等方面。最后形成一个可以直接在手机上面使用的小闹钟。

开始启动界面AppStart.java

  1. package com.example.alarmtest;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.content.SharedPreferences;  
  6. import android.content.SharedPreferences.Editor;  
  7. import android.content.pm.PackageManager.NameNotFoundException;  
  8. import android.os.Bundle;  
  9. import android.os.Handler;  
  10. import android.util.Log;  
  11. import android.widget.LinearLayout;  
  12.   
  13. public class AppStart extends Activity{  
  14.     public static final String PACKAGE_NAME = "com.example.alarmtest";  
  15.     public static final String VERSION_KEY = "versionCode";  
  16.     SharedPreferences preferences;  
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         // TODO Auto-generated method stub  
  20.         super.onCreate(savedInstanceState);  
  21.           
  22.         //判断是否是首次安装  
  23.         /** 判断应用首次运行 **/  
  24.           
  25.         preferences = getSharedPreferences("count",MODE_WORLD_READABLE);  
  26.   
  27.         int count = preferences.getInt("start_count"0);  
  28.         if(count == 0){  
  29.             Editor editor = preferences.edit();  
  30.             //存入数据  
  31.             editor.putInt("start_count", ++count);  
  32.             //提交修改    
  33.             editor.commit();  
  34.               
  35.             Intent intent = new Intent(AppStart.this, GuideActivity.class);  
  36.             startActivity(intent);  
  37.             AppStart.this.finish();  
  38.               
  39.         }else{  
  40.             LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(  
  41.                     LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);  
  42.             LinearLayout linearLayout = new LinearLayout(this);  
  43.             linearLayout.setLayoutParams(params);  
  44.             linearLayout.setOrientation(LinearLayout.VERTICAL);  
  45.             linearLayout.setBackgroundResource(R.drawable.main_bg_default_img_2);  
  46.               
  47.             new Handler().postDelayed(new Runnable(){  
  48.                 @Override  
  49.                 public void run(){  
  50.                     Intent intent = new Intent (AppStart.this, MainActivity.class);           
  51.                     startActivity(intent);            
  52.                     AppStart.this.finish();  
  53.                 }  
  54.             }, 1000);  
  55.             setContentView(linearLayout);  
  56.         }         
  57.     }  
  58. }  
上面使用sharedPreference中的默认设值来判断该应用是否是第一次启动,如果是第一次启动则启动GuidActivity进入指导页面,如果不是第一次启动则启动MainActivity进入主界面。

先看看GuidActivity的实现

  1. package com.example.alarmtest;  
  2.   
  3. import java.util.ArrayList;  
  4.   
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.os.Handler;  
  8. import android.os.Message;  
  9. import android.os.Parcelable;  
  10. import android.support.v4.view.PagerAdapter;  
  11. import android.support.v4.view.ViewPager;  
  12. import android.support.v4.view.ViewPager.OnPageChangeListener;  
  13. import android.view.LayoutInflater;  
  14. import android.view.MotionEvent;  
  15. import android.view.View;  
  16. import android.view.View.OnClickListener;  
  17. import android.view.ViewGroup;  
  18. import android.view.ViewGroup.LayoutParams;  
  19. import android.view.Window;  
  20. import android.view.WindowManager;  
  21. import android.widget.ImageView;  
  22.   
  23. /** 
  24.  * 第一次安装引导用户的Activity 
  25.  * @author lixq 
  26.  * 
  27.  */  
  28. public class GuideActivity extends Activity{  
  29.       
  30.   
  31.      private ViewPager viewPager;      
  32.      private ArrayList<View> pageViews;      
  33.      private ImageView imageView;      
  34.      private ImageView[] imageViews;     
  35.     // 包裹滑动图片LinearLayout    
  36.      private ViewGroup main;    
  37.     // 包裹小圆点的LinearLayout    
  38.      private ViewGroup group;    
  39.      //左箭头按钮    
  40.      private ImageView imageViewLeft;    
  41.      //右箭头按钮    
  42.      private ImageView imageViewRight;    
  43.      //当前页码    
  44.      private int currentIndex;    
  45.          
  46.      //ImageView的alpha值       
  47.      private int mAlpha = 0;    
  48.      private boolean isHide;   
  49.       
  50.     @Override  
  51.     protected void onCreate(Bundle savedInstanceState) {  
  52.         super.onCreate(savedInstanceState);  
  53.         //将要显示的图片放到ArrayList当中,存到适配器中    
  54.         LayoutInflater inflater = getLayoutInflater();      
  55.         pageViews = new ArrayList<View>();      
  56.         pageViews.add(inflater.inflate(R.layout.guide_item1, null));    
  57.         pageViews.add(inflater.inflate(R.layout.guide_item2, null));    
  58.         pageViews.add(inflater.inflate(R.layout.guide_item3, null));  
  59.         pageViews.add(inflater.inflate(R.layout.guide_item4, null));  
  60.         //将图片存放到ImageView集合中  
  61.         imageViews = new ImageView[pageViews.size()];      
  62.         main = (ViewGroup)inflater.inflate(R.layout.guide, null);      
  63.         //获取存放底部导航点ViewGroup    
  64.         group = (ViewGroup)main.findViewById(R.id.guide_point_ll);      
  65.         viewPager = (ViewPager)main.findViewById(R.id.guide_viewpager);      
  66.         imageViewLeft = (ImageView)main.findViewById(R.id.imageView1);    
  67.         imageViewRight = (ImageView)main.findViewById(R.id.imageView2);    
  68.         imageViewLeft.setAlpha(0);    
  69.         imageViewRight.setAlpha(0);    
  70.             
  71.         //将小圆点放到imageView数组当中    
  72.         for (int i = 0; i < pageViews.size(); i++) {      
  73.             System.out.println("pageViews.size() = " + pageViews.size());  
  74.             imageView = new ImageView(GuideActivity.this);      
  75.             imageView.setLayoutParams(new LayoutParams(20,20));      
  76.             imageView.setPadding(200200);      
  77.             imageViews[i] = imageView;      
  78.                 
  79.             if (i == 0) {      
  80.              //默认选中第一张图片    
  81.                 imageViews[i].setBackgroundResource(R.drawable.green_point);      
  82.             } else {      
  83.                 imageViews[i].setBackgroundResource(R.drawable.gray_point);      
  84.             }      
  85.                 
  86.             group.addView(imageViews[i]);      
  87.         }      
  88.             
  89.         setContentView(main);    
  90.             
  91.         viewPager.setAdapter(new GuidePageAdapter());      
  92.         viewPager.setOnPageChangeListener(new GuidePageChangeListener());    
  93.         imageViewLeft.setOnClickListener(new ButtonListener());    
  94.         imageViewRight.setOnClickListener(new ButtonListener());    
  95.     }    
  96.         
  97.     //左右切换屏幕的按钮监听器    
  98.     class ButtonListener implements OnClickListener{    
  99.      
  100.      @Override    
  101.      public void onClick(View v) {    
  102.          // TODO Auto-generated method stub    
  103.          int showNext=0;    
  104.          if(v.getId() == R.id.imageView1) {    
  105.              System.out.println("点击了向左的按钮");    
  106.              if(currentIndex ==0 )    
  107.                  showNext = currentIndex;    
  108.              else    
  109.                  showNext = currentIndex-1;    
  110.              viewPager.setCurrentItem(showNext);    
  111.          }    
  112.          if(v.getId() == R.id.imageView2){    
  113.              System.out.println("点击了向右的按钮");    
  114.              if(currentIndex == imageViews.length)    
  115.                  showNext = currentIndex;    
  116.              else    
  117.                  showNext = currentIndex+1;    
  118.              viewPager.setCurrentItem(showNext);    
  119.          }    
  120.              System.out.println("当前页码:"+showNext);    
  121.              
  122.      }    
  123.          
  124.     }    
  125.         
  126.     /**  
  127.      * 设置按钮渐显效果  
  128.      */    
  129.     private Handler mHandler = new Handler()    
  130.     {    
  131.         public void handleMessage(Message msg) {    
  132.             if(msg.what==1 && mAlpha<255){               
  133.                 //通过设置不透明度设置按钮的渐显效果    
  134.                 mAlpha += 50;    
  135.                     
  136.                 if(mAlpha>255)    
  137.                     mAlpha=255;    
  138.                     
  139.                 imageViewLeft.setAlpha(mAlpha);    
  140.                 imageViewLeft.invalidate();    
  141.                 imageViewRight.setAlpha(mAlpha);    
  142.                 imageViewRight.invalidate();    
  143.                     
  144.                 if(!isHide && mAlpha<255)    
  145.                     mHandler.sendEmptyMessageDelayed(1100);    
  146.             }else if(msg.what==0 && mAlpha>0){    
  147.                 mAlpha -= 3;    
  148.                     
  149.                 if(mAlpha<0)    
  150.                     mAlpha=0;    
  151.                 imageViewLeft.setAlpha(mAlpha);    
  152.                 imageViewLeft.invalidate();    
  153.                 imageViewRight.setAlpha(mAlpha);    
  154.                 imageViewRight.invalidate();    
  155.                     
  156.                 if(isHide && mAlpha>0)    
  157.                     mHandler.sendEmptyMessageDelayed(02);    
  158.             }                
  159.         }    
  160.     };    
  161.         
  162.     private void showImageButtonView(){    
  163.         isHide = false;    
  164.         mHandler.sendEmptyMessage(1);    
  165.     }    
  166.         
  167.     private void hideImageButtonView(){    
  168.         new Thread(){    
  169.             public void run() {    
  170.                 try {    
  171.                     isHide = true;    
  172.                     mHandler.sendEmptyMessage(0);    
  173.                 } catch (Exception e) {    
  174.                     ;    
  175.                 }    
  176.             }    
  177.         }.start();    
  178.     }    
  179.         
  180.      
  181.      
  182.      
  183.      
  184.  @Override    
  185.  public boolean dispatchTouchEvent(MotionEvent ev) {    
  186.      System.out.println("this is dispatch");    
  187.      System.out.println("触碰屏幕");    
  188.         switch (ev.getAction()) {    
  189.             case MotionEvent.ACTION_MOVE:    
  190.             case MotionEvent.ACTION_DOWN:    
  191.                 showImageButtonView();                
  192.                 break;    
  193.             case MotionEvent.ACTION_UP:    
  194.                 hideImageButtonView();                    
  195.                 break;    
  196.         }    
  197.             
  198.             
  199.      return super.dispatchTouchEvent(ev);    
  200.  }    
  201.      
  202.  // 指引页面数据适配器,实现适配器方法    
  203.     class GuidePageAdapter extends PagerAdapter {      
  204.            
  205.         @Override      
  206.         public int getCount() {      
  207.             return pageViews.size();      
  208.         }      
  209.       
  210.         @Override      
  211.         public boolean isViewFromObject(View arg0, Object arg1) {      
  212.             return arg0 == arg1;      
  213.         }      
  214.       
  215.         @Override      
  216.         public int getItemPosition(Object object) {      
  217.             // TODO Auto-generated method stub      
  218.             return super.getItemPosition(object);      
  219.         }      
  220.       
  221.         @Override      
  222.         public void destroyItem(View arg0, int arg1, Object arg2) {      
  223.             // TODO Auto-generated method stub      
  224.             ((ViewPager) arg0).removeView(pageViews.get(arg1));      
  225.         }      
  226.       
  227.         @Override      
  228.         public Object instantiateItem(View arg0, int arg1) {      
  229.             // TODO Auto-generated method stub      
  230.             ((ViewPager) arg0).addView(pageViews.get(arg1));      
  231.             return pageViews.get(arg1);      
  232.         }      
  233.       
  234.         @Override      
  235.         public void restoreState(Parcelable arg0, ClassLoader arg1) {      
  236.             // TODO Auto-generated method stub      
  237.       
  238.         }      
  239.       
  240.         @Override      
  241.         public Parcelable saveState() {      
  242.             // TODO Auto-generated method stub      
  243.             return null;      
  244.         }      
  245.       
  246.         @Override      
  247.         public void startUpdate(View arg0) {      
  248.             // TODO Auto-generated method stub      
  249.       
  250.         }      
  251.       
  252.         @Override      
  253.         public void finishUpdate(View arg0) {      
  254.             // TODO Auto-generated method stub      
  255.       
  256.         }      
  257.     }     
  258.         
  259.  // 指引页面更改事件监听器,左右滑动图片时候,小圆点变换显示当前图片位置    
  260.     class GuidePageChangeListener implements OnPageChangeListener {      
  261.            
  262.         @Override      
  263.         public void onPageScrollStateChanged(int arg0) {      
  264.             // TODO Auto-generated method stub      
  265.       
  266.         }      
  267.       
  268.         @Override      
  269.         public void onPageScrolled(int arg0, float arg1, int arg2) {      
  270.             // TODO Auto-generated method stub      
  271.       
  272.         }      
  273.       
  274.         @Override      
  275.         public void onPageSelected(int arg0) {      
  276.          currentIndex = arg0;    
  277.             for (int i = 0; i < imageViews.length; i++) {      
  278.                 imageViews[arg0].setBackgroundResource(R.drawable.green_point);    
  279.                     
  280.                 if (arg0 != i) {      
  281.                     imageViews[i].setBackgroundResource(R.drawable.gray_point);      
  282.                 }      
  283.             }    
  284.         }      
  285.     }  
  286. }  
使用ViewPage来显示各个布局文件,在四个布局文件中分别放四张图片。

详情请看:http://blog.csdn.net/dawanganban/article/details/17305769

进入主界面后就是我们设置闹钟的界面了,实现如下:

  1. package com.example.alarmtest;  
  2.   
  3. import java.util.Calendar;  
  4.   
  5. import android.app.Activity;  
  6. import android.app.AlarmManager;  
  7. import android.app.PendingIntent;  
  8. import android.app.Service;  
  9. import android.app.TimePickerDialog;  
  10. import android.content.Intent;  
  11. import android.os.Bundle;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.widget.Button;  
  15. import android.widget.TimePicker;  
  16. import android.widget.Toast;  
  17.   
  18. public class MainActivity extends Activity {  
  19.     Button button;  
  20.     AlarmManager alarmManager;  
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.         button = (Button) findViewById(R.id.button1);  
  26.           
  27.         //获取AlarmManager对象  
  28.         alarmManager = (AlarmManager) getSystemService(Service.ALARM_SERVICE);  
  29.           
  30.         button.setOnClickListener(new OnClickListener() {  
  31.               
  32.             @Override  
  33.             public void onClick(View arg0) {  
  34.                 Calendar currentTime = Calendar.getInstance();  
  35.                 //创建一个TimePickerDialog实例,并显示  
  36.                 new TimePickerDialog(MainActivity.this0,   
  37.                         new TimePickerDialog.OnTimeSetListener() {  
  38.                               
  39.                             @Override  
  40.                             public void onTimeSet(TimePicker view, int hourOfDay, int minute) {  
  41.                                 //指定启动AlarmActivity组件  
  42.                                 Intent intent = new Intent(MainActivity.this, AlarmActivity.class);  
  43.                                 //创建PendingIntent对象  
  44.                                 /* 
  45.                                  * PendingIntent与Intent的区别是PendingIntent处理即将发生的事情 
  46.                                  * 比如:在通知栏Notification中跳转页面,不是立即跳转 
  47.                                  * 通常通过  getActivity、getBroadcast、getService得到PendingIntent的实例 
  48.                                  *  
  49.                                  */  
  50.                                 PendingIntent pi = PendingIntent.getActivity(MainActivity.this0, intent, 0);  
  51.                                 Calendar c = Calendar.getInstance();  
  52.                                 c.setTimeInMillis(System.currentTimeMillis());  
  53.                                 c.set(Calendar.HOUR, hourOfDay);  
  54.                                 c.set(Calendar.MINUTE, minute);  
  55.                                   
  56.                                 alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);  
  57.                                 Toast.makeText(MainActivity.this"设置闹钟成功", Toast.LENGTH_SHORT).show();  
  58.                             }  
  59.                 }, currentTime.get(Calendar.HOUR_OF_DAY), currentTime.get(Calendar.MINUTE), false).show();  
  60.             }  
  61.         });  
  62.     }  
  63. }  
上面使用了一个时间设置组件TimePickDialog来设置时间,设置完时间后使用AlarmManager的set方法设置闹钟,值得注意的是上面有一个PendingIntent,这个和Intent的区别是PendIntent表示即将发生的意图,常和AlarmManager与Notifycation同时使用。另外,AlarmManager.RTC_WAKEUP表示一个定时器且会发出警报。

闹钟到时间后启动AlarmActivity来播放音乐

  1. package com.example.alarmtest;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.AlertDialog;  
  5. import android.app.Notification;  
  6. import android.content.DialogInterface;  
  7. import android.content.DialogInterface.OnClickListener;  
  8. import android.media.MediaPlayer;  
  9. import android.os.Bundle;  
  10.   
  11. public class AlarmActivity extends Activity{  
  12.     MediaPlayer alarmMusic;  
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         //加载指定音乐,并为之创建MediaPlayer对象  
  17.         alarmMusic = MediaPlayer.create(this, R.raw.nswdy);  
  18.         alarmMusic.setLooping(true);  
  19.         //播放闹钟  
  20.         alarmMusic.start();  
  21.         //创建一个对话框  
  22.         new AlertDialog.Builder(AlarmActivity.this).setTitle("闹钟")  
  23.             .setMessage("闹钟响了,快起床啦!")  
  24.             .setPositiveButton("确定"new OnClickListener() {  
  25.                   
  26.                 @Override  
  27.                 public void onClick(DialogInterface dialog, int which) {  
  28.                     //停止音乐  
  29.                     alarmMusic.stop();  
  30.                     AlarmActivity.this.finish();  
  31.                 }  
  32.             }).show();  
  33.     }  
  34. }  

最后的运行结果:

                   

                  


源代码下载:http://download.csdn.net/detail/lxq_xsyu/6963763

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值