Android菜鳥的成長筆記(25)——可愛的小鬧鐘

摘要:

這一篇主要使用系統為我們提供的一個服務AlarmManager來制作一個Android小鬧鐘,同時還涉及到瞭自定義主題、判斷第一次啟動應用、自定義動畫、對話框、制作指導滑動頁面等方面。最後形成一個可以直接在手機上面使用的小鬧鐘。

開始啟動界面AppStart.java

package com.example.alarmtest;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.LinearLayout;

public class AppStart extends Activity{
	public static final String PACKAGE_NAME = "com.example.alarmtest";
	public static final String VERSION_KEY = "versionCode";
	SharedPreferences preferences;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		//判斷是否是首次安裝
		/** 判斷應用首次運行 **/
		
		preferences = getSharedPreferences("count",MODE_WORLD_READABLE);

        int count = preferences.getInt("start_count", 0);
        if(count == 0){
        	Editor editor = preferences.edit();
            //存入數據
            editor.putInt("start_count", ++count);
            //提交修改	
            editor.commit();
            
			Intent intent = new Intent(AppStart.this, GuideActivity.class);
			startActivity(intent);
			AppStart.this.finish();
			
		}else{
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
			LinearLayout linearLayout = new LinearLayout(this);
			linearLayout.setLayoutParams(params);
			linearLayout.setOrientation(LinearLayout.VERTICAL);
			linearLayout.setBackgroundResource(R.drawable.main_bg_default_img_2);
			
			new Handler().postDelayed(new Runnable(){
				@Override
				public void run(){
					Intent intent = new Intent (AppStart.this, MainActivity.class);			
					startActivity(intent);			
					AppStart.this.finish();
				}
			}, 1000);
			setContentView(linearLayout);
		}		
	}
}

上面使用sharedPreference中的默認設值來判斷該應用是否是第一次啟動,如果是第一次啟動則啟動GuidActivity進入指導頁面,如果不是第一次啟動則啟動MainActivity進入主界面。

先看看GuidActivity的實現

package com.example.alarmtest;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

/**
 * 第一次安裝引導用戶的Activity
 * @author lixq
 *
 */
public class GuideActivity extends Activity{
	

     private ViewPager viewPager;    
     private ArrayList pageViews;    
     private ImageView imageView;    
     private ImageView[] imageViews;   
    // 包裹滑動圖片LinearLayout  
     private ViewGroup main;  
    // 包裹小圓點的LinearLayout  
     private ViewGroup group;  
     //左箭頭按鈕  
     private ImageView imageViewLeft;  
     //右箭頭按鈕  
     private ImageView imageViewRight;  
     //當前頁碼  
     private int currentIndex;  
       
     //ImageView的alpha值     
     private int mAlpha = 0;  
     private boolean isHide; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//將要顯示的圖片放到ArrayList當中,存到適配器中  
        LayoutInflater inflater = getLayoutInflater();    
        pageViews = new ArrayList();    
        pageViews.add(inflater.inflate(R.layout.guide_item1, null));  
        pageViews.add(inflater.inflate(R.layout.guide_item2, null));  
        pageViews.add(inflater.inflate(R.layout.guide_item3, null));
        pageViews.add(inflater.inflate(R.layout.guide_item4, null));
        //將圖片存放到ImageView集合中
        imageViews = new ImageView[pageViews.size()];    
        main = (ViewGroup)inflater.inflate(R.layout.guide, null);    
        //獲取存放底部導航點ViewGroup  
        group = (ViewGroup)main.findViewById(R.id.guide_point_ll);    
        viewPager = (ViewPager)main.findViewById(R.id.guide_viewpager);    
        imageViewLeft = (ImageView)main.findViewById(R.id.imageView1);  
        imageViewRight = (ImageView)main.findViewById(R.id.imageView2);  
        imageViewLeft.setAlpha(0);  
        imageViewRight.setAlpha(0);  
          
        //將小圓點放到imageView數組當中  
        for (int i = 0; i < pageViews.size(); i++) {    
        	System.out.println("pageViews.size() = " + pageViews.size());
            imageView = new ImageView(GuideActivity.this);    
            imageView.setLayoutParams(new LayoutParams(20,20));    
            imageView.setPadding(20, 0, 20, 0);    
            imageViews[i] = imageView;    
              
            if (i == 0) {    
             //默認選中第一張圖片  
                imageViews[i].setBackgroundResource(R.drawable.green_point);    
            } else {    
                imageViews[i].setBackgroundResource(R.drawable.gray_point);    
            }    
              
            group.addView(imageViews[i]);    
        }    
          
        setContentView(main);  
          
        viewPager.setAdapter(new GuidePageAdapter());    
        viewPager.setOnPageChangeListener(new GuidePageChangeListener());  
        imageViewLeft.setOnClickListener(new ButtonListener());  
        imageViewRight.setOnClickListener(new ButtonListener());  
    }  
      
    //左右切換屏幕的按鈕監聽器  
    class ButtonListener implements OnClickListener{  
   
     @Override  
     public void onClick(View v) {  
         // TODO Auto-generated method stub  
         int showNext=0;  
         if(v.getId() == R.id.imageView1) {  
             System.out.println("點擊瞭向左的按鈕");  
             if(currentIndex ==0 )  
                 showNext = currentIndex;  
             else  
                 showNext = currentIndex-1;  
             viewPager.setCurrentItem(showNext);  
         }  
         if(v.getId() == R.id.imageView2){  
             System.out.println("點擊瞭向右的按鈕");  
             if(currentIndex == imageViews.length)  
                 showNext = currentIndex;  
             else  
                 showNext = currentIndex+1;  
             viewPager.setCurrentItem(showNext);  
         }  
             System.out.println("當前頁碼:"+showNext);  
           
     }  
       
    }  
      
    /** 
     * 設置按鈕漸顯效果 
     */  
    private Handler mHandler = new Handler()  
    {  
        public void handleMessage(Message msg) {  
            if(msg.what==1 && mAlpha255)  
                    mAlpha=255;  
                  
                imageViewLeft.setAlpha(mAlpha);  
                imageViewLeft.invalidate();  
                imageViewRight.setAlpha(mAlpha);  
                imageViewRight.invalidate();  
                  
                if(!isHide && mAlpha0){  
                mAlpha -= 3;  
                  
                if(mAlpha0)  
                    mHandler.sendEmptyMessageDelayed(0, 2);  
            }              
        }  
    };  
      
    private void showImageButtonView(){  
        isHide = false;  
        mHandler.sendEmptyMessage(1);  
    }  
      
    private void hideImageButtonView(){  
        new Thread(){  
            public void run() {  
                try {  
                    isHide = true;  
                    mHandler.sendEmptyMessage(0);  
                } catch (Exception e) {  
                    ;  
                }  
            }  
        }.start();  
    }  
      
   
   
   
   
 @Override  
 public boolean dispatchTouchEvent(MotionEvent ev) {  
     System.out.println("this is dispatch");  
     System.out.println("觸碰屏幕");  
        switch (ev.getAction()) {  
            case MotionEvent.ACTION_MOVE:  
            case MotionEvent.ACTION_DOWN:  
                showImageButtonView();              
                break;  
            case MotionEvent.ACTION_UP:  
                hideImageButtonView();                  
                break;  
        }  
          
          
     return super.dispatchTouchEvent(ev);  
 }  
   
 // 指引頁面數據適配器,實現適配器方法  
    class GuidePageAdapter extends PagerAdapter {    
         
        @Override    
        public int getCount() {    
            return pageViews.size();    
        }    
    
        @Override    
        public boolean isViewFromObject(View arg0, Object arg1) {    
            return arg0 == arg1;    
        }    
    
        @Override    
        public int getItemPosition(Object object) {    
            // TODO Auto-generated method stub    
            return super.getItemPosition(object);    
        }    
    
        @Override    
        public void destroyItem(View arg0, int arg1, Object arg2) {    
            // TODO Auto-generated method stub    
            ((ViewPager) arg0).removeView(pageViews.get(arg1));    
        }    
    
        @Override    
        public Object instantiateItem(View arg0, int arg1) {    
            // TODO Auto-generated method stub    
            ((ViewPager) arg0).addView(pageViews.get(arg1));    
            return pageViews.get(arg1);    
        }    
    
        @Override    
        public void restoreState(Parcelable arg0, ClassLoader arg1) {    
            // TODO Auto-generated method stub    
    
        }    
    
        @Override    
        public Parcelable saveState() {    
            // TODO Auto-generated method stub    
            return null;    
        }    
    
        @Override    
        public void startUpdate(View arg0) {    
            // TODO Auto-generated method stub    
    
        }    
    
        @Override    
        public void finishUpdate(View arg0) {    
            // TODO Auto-generated method stub    
    
        }    
    }   
      
 // 指引頁面更改事件監聽器,左右滑動圖片時候,小圓點變換顯示當前圖片位置  
    class GuidePageChangeListener implements OnPageChangeListener {    
         
        @Override    
        public void onPageScrollStateChanged(int arg0) {    
            // TODO Auto-generated method stub    
    
        }    
    
        @Override    
        public void onPageScrolled(int arg0, float arg1, int arg2) {    
            // TODO Auto-generated method stub    
    
        }    
    
        @Override    
        public void onPageSelected(int arg0) {    
         currentIndex = arg0;  
            for (int i = 0; i < imageViews.length; i++) {    
                imageViews[arg0].setBackgroundResource(R.drawable.green_point);  
                  
                if (arg0 != i) {    
                    imageViews[i].setBackgroundResource(R.drawable.gray_point);    
                }    
            }  
        }    
	}
}

使用ViewPage來顯示各個佈局文件,在四個佈局文件中分別放四張圖片。

詳情請看:https://blog.csdn.net/dawanganban/article/details/17305769

進入主界面後就是我們設置鬧鐘的界面瞭,實現如下:

package com.example.alarmtest;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;

public class MainActivity extends Activity {
	Button button;
	AlarmManager alarmManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button) findViewById(R.id.button1);
		
		//獲取AlarmManager對象
		alarmManager = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
		
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Calendar currentTime = Calendar.getInstance();
				//創建一個TimePickerDialog實例,並顯示
				new TimePickerDialog(MainActivity.this, 0, 
						new TimePickerDialog.OnTimeSetListener() {
							
							@Override
							public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
								//指定啟動AlarmActivity組件
								Intent intent = new Intent(MainActivity.this, AlarmActivity.class);
								//創建PendingIntent對象
								/*
								 * PendingIntent與Intent的區別是PendingIntent處理即將發生的事情
								 * 比如:在通知欄Notification中跳轉頁面,不是立即跳轉
								 * 通常通過  getActivity、getBroadcast、getService得到PendingIntent的實例
								 * 
								 */
								PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
								Calendar c = Calendar.getInstance();
								c.setTimeInMillis(System.currentTimeMillis());
								c.set(Calendar.HOUR, hourOfDay);
								c.set(Calendar.MINUTE, minute);
								
								alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
								Toast.makeText(MainActivity.this, "設置鬧鐘成功", Toast.LENGTH_SHORT).show();
							}
				}, currentTime.get(Calendar.HOUR_OF_DAY), currentTime.get(Calendar.MINUTE), false).show();
			}
		});
	}
}

上面使用瞭一個時間設置組件TimePickDialog來設置時間,設置完時間後使用AlarmManager的set方法設置鬧鐘,值得註意的是上面有一個PendingIntent,這個和Intent的區別是PendIntent表示即將發生的意圖,常和AlarmManager與Notifycation同時使用。另外,AlarmManager.RTC_WAKEUP表示一個定時器且會發出警報。

鬧鐘到時間後啟動AlarmActivity來播放音樂

package com.example.alarmtest;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.media.MediaPlayer;
import android.os.Bundle;

public class AlarmActivity extends Activity{
	MediaPlayer alarmMusic;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//加載指定音樂,並為之創建MediaPlayer對象
		alarmMusic = MediaPlayer.create(this, R.raw.nswdy);
		alarmMusic.setLooping(true);
		//播放鬧鐘
		alarmMusic.start();
		//創建一個對話框
		new AlertDialog.Builder(AlarmActivity.this).setTitle("鬧鐘")
			.setMessage("鬧鐘響瞭,快起床啦!")
			.setPositiveButton("確定", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//停止音樂
					alarmMusic.stop();
					AlarmActivity.this.finish();
				}
			}).show();
	}
}

最後的運行結果:

源代碼下載:https://download.csdn.net/detail/lxq_xsyu/6963763

發佈留言