`
jandroid
  • 浏览: 1939971 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

Android闹钟拓展版【安卓闹钟可换壁纸版】

 
阅读更多

经过写上篇文章Android闹钟最终版【android源码闹钟解析】 .发现有一些留邮箱的,但凡留邮箱的,我就发源码过去了,不错,基本上收到邮箱的都留言感谢了,这样我的成就感就多一点,也能有更多留邮箱的。学习是一个相互的过程,就像师说中“问道有先后,术业有专攻,仅此而已!”知识就是一层窗户纸,捅破了就没什么了,-------->个人浅薄的拙见,在这表达一下!


前段时间参加一个CMDN的讲座,讲的是Android主题,其中就有小米手机的UI工程师,董红光简单介绍了5中换肤的方法。所以就想简单练手一下,拿上个闹钟来换个背景试一试。好多应用都有更换自己应用壁纸的功能,例如熊猫看书就有这个功能,还有韩国的SKY手机,也可以更换mainmeun的背景,我也小试牛刀一下;


转载请标明出处:http://blog.csdn.net/wdaming1986/article/details/7479359


在做这个更换背景的大致思路如下:

(1)用ImageSwitcher来切换图片,效果就和更换手机系统的壁纸类似,下面有个gallery,滚动gallery,当gallery,选中哪个的时候,就用ImageSwitcher来切换与之对应的大的图片。

(2)SetBackGround extends Activity implements AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory, OnClickListener。重写与之对应的方法。

(3)利用android提供的映射机制,当选中那个图片的时候,找到对应的gen下的R.java对应的16进制的值。

(4)用SharedPreferences保存这个id的值,下次进入这个程序,就可以取出来用了。就能永久保存了。


遇到的问题如下

(1)在DeskClockMainActivity.java中用startActivityForResult(intent, request);这个方法来启动SetBackGround.java这个类,当点击设置后,finish()这个SetBackGround类,传递给DeskClockMainActivity的onActivityResult()方法一个int的值。问题:startActivityForResult启动的时候,当SetBackGround这个类finish()的时候,onActivityResult()方法接受到的intent为空,resultCode==cancel,我就查资料,原来是DeskClockMainActivity的launcherMode=“singleInstance”导致的,它会启动一个新的栈,导致返回的时候不在一个栈中,传递intent传递不过去,我猜测是不同栈,intent回传的时候android有问题。修改方法,launcherMode=“singleTask”就可以了。详细参见api的startActivityForResult()介绍;

(2)SetBackGround设置背景的类有个button,当声明一个button类型的时候,像常规那样写:

button = (Button) findViewById(R.id.setButton_bg);这时候报错,说类型不匹配。解决办法有两种:1、把button声明为view类的对象,这样再像常规那样找id就不报错了。2、让类实现一个OnClickListener监听,通过:findViewById(R.id.setButton_bg).setOnClickListener(this);这样写就ok了,实现onClick(View v) 的点击方法就ok了。


先看效果图,如下:


点击图中画红圈的图片,进入换背景界面; 点击menu--->点击---->设置背景,


进入到更换背景的界面: 点击设置背景,即背景设成功



下面把主要的类贴出来,供大家参考:

一、DeskClockMainActivity.java类中的代码,这个是程序的入口类:

package com.cn.daming.deskclock;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class DeskClockMainActivity extends Activity implements OnItemClickListener{
	
    static final String PREFERENCES = "AlarmClock";

    /** This must be false for production.  If true, turns on logging,
        test code, etc. */
    static final boolean DEBUG = false;

    private SharedPreferences mPrefs;
    private LayoutInflater mFactory;
    private ListView mAlarmsList;
    private Cursor mCursor;
    private LinearLayout mBglinearlayout;
    private static final int REQ_SET_BG = 100;
    private static final String SETBACKGROUND = "deskclock_bground";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //取自定义布局的LayoutInflater
        mFactory = LayoutInflater.from(this);
        //取getSharedPreferences的实例
        mPrefs = getSharedPreferences(PREFERENCES, 0);
        //获取闹钟的cursor
        mCursor = Alarms.getAlarmsCursor(getContentResolver());
        
        //更新布局界面
        updateLayout();

    }
    
	//加载更新界面布局
    private void updateLayout() {
    	setContentView(R.layout.alarm_clock);
    	mBglinearlayout = (LinearLayout) findViewById(R.id.base_layout);
        mAlarmsList = (ListView) findViewById(R.id.alarms_list);
        AlarmTimeAdapter adapter = new AlarmTimeAdapter(this, mCursor);
        mAlarmsList.setAdapter(adapter);
        mAlarmsList.setVerticalScrollBarEnabled(true);
        mAlarmsList.setOnItemClickListener(this);
        mAlarmsList.setOnCreateContextMenuListener(this);

        View addAlarm = findViewById(R.id.add_alarm);
        addAlarm.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    addNewAlarm();
                }
            });
        // Make the entire view selected when focused.
        addAlarm.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                public void onFocusChange(View v, boolean hasFocus) {
                    v.setSelected(hasFocus);
                }
        });

        ImageButton deskClock =
                (ImageButton) findViewById(R.id.desk_clock_button);
        deskClock.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                	/**
                	 * modify by wangxianming in 2012-4-17
                	 * enter the set background class SetBackGround
                	 * author:wangxianming
                	 */
                	Intent intent = new Intent();
                	intent.setClass(DeskClockMainActivity.this, SetBackGround.class);
                	startActivityForResult(intent, REQ_SET_BG);
                }
        });
    }
    
    @Override
	protected void onResume() {
    	SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    	int setBgId = sharedPreferences.getInt(SETBACKGROUND, 0);
    	Log.v("wangxianming", "DeskClockMainActivity onResume() setBgId == "+setBgId);
    	if(setBgId != 0){
    		//设置背景 add by wangxianming in 2012-04-17
    		mBglinearlayout.setBackgroundResource(setBgId);
    	}
		super.onResume();
	}
    
    private void addNewAlarm() {
        startActivity(new Intent(this, SetAlarm.class));
    }
    
    /**
     * listview的适配器继承CursorAdapter
     * @author wangxianming
     * 也可以使用BaseAdapter
     */
    private class AlarmTimeAdapter extends CursorAdapter {
        public AlarmTimeAdapter(Context context, Cursor cursor) {
            super(context, cursor);
        }

        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View ret = mFactory.inflate(R.layout.alarm_time, parent, false);

            DigitalClock digitalClock =
                    (DigitalClock) ret.findViewById(R.id.digitalClock);
            digitalClock.setLive(false);
            return ret;
        }

        //把view绑定cursor的每一项
        public void bindView(View view, Context context, Cursor cursor) {
            final Alarm alarm = new Alarm(cursor);

            View indicator = view.findViewById(R.id.indicator);

            // Set the initial resource for the bar image.
            final ImageView barOnOff =
                    (ImageView) indicator.findViewById(R.id.bar_onoff);
            barOnOff.setImageResource(alarm.enabled ?
                    R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);

            // Set the initial state of the clock "checkbox"
            final CheckBox clockOnOff =
                    (CheckBox) indicator.findViewById(R.id.clock_onoff);
            clockOnOff.setChecked(alarm.enabled);

            // Clicking outside the "checkbox" should also change the state.
            //对checkbox设置监听,使里外一致
            indicator.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        clockOnOff.toggle();
                        updateIndicatorAndAlarm(clockOnOff.isChecked(),
                                barOnOff, alarm);
                    }
            });

            DigitalClock digitalClock =
                    (DigitalClock) view.findViewById(R.id.digitalClock);

            // set the alarm text
            final Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR_OF_DAY, alarm.hour);
            c.set(Calendar.MINUTE, alarm.minutes);
            digitalClock.updateTime(c);
            digitalClock.setTypeface(Typeface.DEFAULT);

            // Set the repeat text or leave it blank if it does not repeat.
            TextView daysOfWeekView =
                    (TextView) digitalClock.findViewById(R.id.daysOfWeek);
            final String daysOfWeekStr =
                    alarm.daysOfWeek.toString(DeskClockMainActivity.this, false);
            if (daysOfWeekStr != null && daysOfWeekStr.length() != 0) {
                daysOfWeekView.setText(daysOfWeekStr);
                daysOfWeekView.setVisibility(View.VISIBLE);
            } else {
                daysOfWeekView.setVisibility(View.GONE);
            }

            // Display the label
            TextView labelView =
                    (TextView) view.findViewById(R.id.label);
            if (alarm.label != null && alarm.label.length() != 0) {
                labelView.setText(alarm.label);
                labelView.setVisibility(View.VISIBLE);
            } else {
                labelView.setVisibility(View.GONE);
            }
        }
    };
    
    //更新checkbox
    private void updateIndicatorAndAlarm(boolean enabled, ImageView bar,
            Alarm alarm) {
        bar.setImageResource(enabled ? R.drawable.ic_indicator_on
                : R.drawable.ic_indicator_off);
        Alarms.enableAlarm(this, alarm.id, enabled);
        if (enabled) {
            SetAlarm.popAlarmSetToast(this, alarm.hour, alarm.minutes,
                    alarm.daysOfWeek);
        }
    }
    
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
     * 创建上下文菜单
     */
    @Override
    public boolean onContextItemSelected(final MenuItem item) {
        final AdapterContextMenuInfo info =
                (AdapterContextMenuInfo) item.getMenuInfo();
        final int id = (int) info.id;
        // Error check just in case.
        if (id == -1) {
            return super.onContextItemSelected(item);
        }
        switch (item.getItemId()) {
            case R.id.delete_alarm:
                // Confirm that the alarm will be deleted.
                new AlertDialog.Builder(this)
                        .setTitle(getString(R.string.delete_alarm))
                        .setMessage(getString(R.string.delete_alarm_confirm))
                        .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface d,
                                            int w) {
                                        Alarms.deleteAlarm(DeskClockMainActivity.this, id);
                                    }
                                })
                        .setNegativeButton(android.R.string.cancel, null)
                        .show();
                return true;

            case R.id.enable_alarm:
                final Cursor c = (Cursor) mAlarmsList.getAdapter()
                        .getItem(info.position);
                final Alarm alarm = new Alarm(c);
                Alarms.enableAlarm(this, alarm.id, !alarm.enabled);
                if (!alarm.enabled) {
                    SetAlarm.popAlarmSetToast(this, alarm.hour, alarm.minutes,
                            alarm.daysOfWeek);
                }
                return true;

            case R.id.edit_alarm:
                Intent intent = new Intent(this, SetAlarm.class);
                intent.putExtra(Alarms.ALARM_ID, id);
                startActivity(intent);
                return true;

            default:
                break;
        }
        return super.onContextItemSelected(item);
    }
    
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
     * 创建菜单
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view,
            ContextMenuInfo menuInfo) {
        // Inflate the menu from xml.
        getMenuInflater().inflate(R.menu.context_menu, menu);

        // Use the current item to create a custom view for the header.
        final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        final Cursor c =
                (Cursor) mAlarmsList.getAdapter().getItem((int) info.position);
        final Alarm alarm = new Alarm(c);

        // Construct the Calendar to compute the time.
        final Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, alarm.hour);
        cal.set(Calendar.MINUTE, alarm.minutes);
        final String time = Alarms.formatTime(this, cal);

        // Inflate the custom view and set each TextView's text.
        final View v = mFactory.inflate(R.layout.context_menu_header, null);
        TextView textView = (TextView) v.findViewById(R.id.header_time);
        textView.setText(time);
        textView = (TextView) v.findViewById(R.id.header_label);
        textView.setText(alarm.label);

        // Set the custom view on the menu.
        menu.setHeaderView(v);
        // Change the text based on the state of the alarm.
        if (alarm.enabled) {
            menu.findItem(R.id.enable_alarm).setTitle(R.string.disable_alarm);
        }
    }
    
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     * 设置菜单的点击事件的处理
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_item_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                return true;
            case R.id.menu_item_alarm_set_bg:
            	/**
            	 * modify by wangxianming in 2012-4-17
            	 * enter the set background class SetBackGround
            	 * author:wangxianming
            	 */
                startActivityForResult((new Intent(this, SetBackGround.class)), REQ_SET_BG);
                return true;
            case R.id.menu_item_add_alarm:
                addNewAlarm();
                return true;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    
	/*
     * (non-Javadoc)
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     * 创建菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.alarm_list_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
    
    /*
     * (non-Javadoc)
     * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
     * 创建菜单的点击事件响应
     */
	public void onItemClick(AdapterView<?> adapterView, View v, int pos, long id) {
		Intent intent = new Intent(this, SetAlarm.class);
        intent.putExtra(Alarms.ALARM_ID, (int) id);
        startActivity(intent);
		
	}
	
   @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	   SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
	   SharedPreferences.Editor editor = sharedPreferences.edit();
	   if(resultCode != RESULT_OK) {
		   return;
	   }
	   if(requestCode == REQ_SET_BG) {
		   switch(resultCode) {
		         case RESULT_OK:
		        	 Bundle b = data.getExtras();
		        	 int id = b.getInt("getDrawable");
		        	 editor.putInt(SETBACKGROUND, id);
		        	 editor.commit();
		        	 if(0 != id) {
		        		 //设置背景
		        		 mBglinearlayout.setBackgroundResource(id);
		        	 }
		        	 Log.v("wangxianming", "DeskClockMainActivity onActivityResult()----> id == "+id);
		        	 break;
		         default:
		        	 break;
		   }
	   }
		super.onActivityResult(requestCode, resultCode, data);
	}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ToastMaster.cancelToast();
        mCursor.close();
    }
}


二、SetBackGround.java类中的代码,这个是设置背景图片的类:

package com.cn.daming.deskclock;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class DeskClockMainActivity extends Activity implements OnItemClickListener{
	
    static final String PREFERENCES = "AlarmClock";

    /** This must be false for production.  If true, turns on logging,
        test code, etc. */
    static final boolean DEBUG = false;

    private SharedPreferences mPrefs;
    private LayoutInflater mFactory;
    private ListView mAlarmsList;
    private Cursor mCursor;
    private LinearLayout mBglinearlayout;
    private static final int REQ_SET_BG = 100;
    private static final String SETBACKGROUND = "deskclock_bground";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //取自定义布局的LayoutInflater
        mFactory = LayoutInflater.from(this);
        //取getSharedPreferences的实例
        mPrefs = getSharedPreferences(PREFERENCES, 0);
        //获取闹钟的cursor
        mCursor = Alarms.getAlarmsCursor(getContentResolver());
        
        //更新布局界面
        updateLayout();

    }
    
	//加载更新界面布局
    private void updateLayout() {
    	setContentView(R.layout.alarm_clock);
    	mBglinearlayout = (LinearLayout) findViewById(R.id.base_layout);
        mAlarmsList = (ListView) findViewById(R.id.alarms_list);
        AlarmTimeAdapter adapter = new AlarmTimeAdapter(this, mCursor);
        mAlarmsList.setAdapter(adapter);
        mAlarmsList.setVerticalScrollBarEnabled(true);
        mAlarmsList.setOnItemClickListener(this);
        mAlarmsList.setOnCreateContextMenuListener(this);

        View addAlarm = findViewById(R.id.add_alarm);
        addAlarm.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    addNewAlarm();
                }
            });
        // Make the entire view selected when focused.
        addAlarm.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                public void onFocusChange(View v, boolean hasFocus) {
                    v.setSelected(hasFocus);
                }
        });

        ImageButton deskClock =
                (ImageButton) findViewById(R.id.desk_clock_button);
        deskClock.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                	/**
                	 * modify by wangxianming in 2012-4-17
                	 * enter the set background class SetBackGround
                	 * author:wangxianming
                	 */
                	Intent intent = new Intent();
                	intent.setClass(DeskClockMainActivity.this, SetBackGround.class);
                	startActivityForResult(intent, REQ_SET_BG);
                }
        });
    }
    
    @Override
	protected void onResume() {
    	SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    	int setBgId = sharedPreferences.getInt(SETBACKGROUND, 0);
    	Log.v("wangxianming", "DeskClockMainActivity onResume() setBgId == "+setBgId);
    	if(setBgId != 0){
    		//设置背景 add by wangxianming in 2012-04-17
    		mBglinearlayout.setBackgroundResource(setBgId);
    	}
		super.onResume();
	}
    
    private void addNewAlarm() {
        startActivity(new Intent(this, SetAlarm.class));
    }
    
    /**
     * listview的适配器继承CursorAdapter
     * @author wangxianming
     * 也可以使用BaseAdapter
     */
    private class AlarmTimeAdapter extends CursorAdapter {
        public AlarmTimeAdapter(Context context, Cursor cursor) {
            super(context, cursor);
        }

        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View ret = mFactory.inflate(R.layout.alarm_time, parent, false);

            DigitalClock digitalClock =
                    (DigitalClock) ret.findViewById(R.id.digitalClock);
            digitalClock.setLive(false);
            return ret;
        }

        //把view绑定cursor的每一项
        public void bindView(View view, Context context, Cursor cursor) {
            final Alarm alarm = new Alarm(cursor);

            View indicator = view.findViewById(R.id.indicator);

            // Set the initial resource for the bar image.
            final ImageView barOnOff =
                    (ImageView) indicator.findViewById(R.id.bar_onoff);
            barOnOff.setImageResource(alarm.enabled ?
                    R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);

            // Set the initial state of the clock "checkbox"
            final CheckBox clockOnOff =
                    (CheckBox) indicator.findViewById(R.id.clock_onoff);
            clockOnOff.setChecked(alarm.enabled);

            // Clicking outside the "checkbox" should also change the state.
            //对checkbox设置监听,使里外一致
            indicator.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        clockOnOff.toggle();
                        updateIndicatorAndAlarm(clockOnOff.isChecked(),
                                barOnOff, alarm);
                    }
            });

            DigitalClock digitalClock =
                    (DigitalClock) view.findViewById(R.id.digitalClock);

            // set the alarm text
            final Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR_OF_DAY, alarm.hour);
            c.set(Calendar.MINUTE, alarm.minutes);
            digitalClock.updateTime(c);
            digitalClock.setTypeface(Typeface.DEFAULT);

            // Set the repeat text or leave it blank if it does not repeat.
            TextView daysOfWeekView =
                    (TextView) digitalClock.findViewById(R.id.daysOfWeek);
            final String daysOfWeekStr =
                    alarm.daysOfWeek.toString(DeskClockMainActivity.this, false);
            if (daysOfWeekStr != null && daysOfWeekStr.length() != 0) {
                daysOfWeekView.setText(daysOfWeekStr);
                daysOfWeekView.setVisibility(View.VISIBLE);
            } else {
                daysOfWeekView.setVisibility(View.GONE);
            }

            // Display the label
            TextView labelView =
                    (TextView) view.findViewById(R.id.label);
            if (alarm.label != null && alarm.label.length() != 0) {
                labelView.setText(alarm.label);
                labelView.setVisibility(View.VISIBLE);
            } else {
                labelView.setVisibility(View.GONE);
            }
        }
    };
    
    //更新checkbox
    private void updateIndicatorAndAlarm(boolean enabled, ImageView bar,
            Alarm alarm) {
        bar.setImageResource(enabled ? R.drawable.ic_indicator_on
                : R.drawable.ic_indicator_off);
        Alarms.enableAlarm(this, alarm.id, enabled);
        if (enabled) {
            SetAlarm.popAlarmSetToast(this, alarm.hour, alarm.minutes,
                    alarm.daysOfWeek);
        }
    }
    
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
     * 创建上下文菜单
     */
    @Override
    public boolean onContextItemSelected(final MenuItem item) {
        final AdapterContextMenuInfo info =
                (AdapterContextMenuInfo) item.getMenuInfo();
        final int id = (int) info.id;
        // Error check just in case.
        if (id == -1) {
            return super.onContextItemSelected(item);
        }
        switch (item.getItemId()) {
            case R.id.delete_alarm:
                // Confirm that the alarm will be deleted.
                new AlertDialog.Builder(this)
                        .setTitle(getString(R.string.delete_alarm))
                        .setMessage(getString(R.string.delete_alarm_confirm))
                        .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface d,
                                            int w) {
                                        Alarms.deleteAlarm(DeskClockMainActivity.this, id);
                                    }
                                })
                        .setNegativeButton(android.R.string.cancel, null)
                        .show();
                return true;

            case R.id.enable_alarm:
                final Cursor c = (Cursor) mAlarmsList.getAdapter()
                        .getItem(info.position);
                final Alarm alarm = new Alarm(c);
                Alarms.enableAlarm(this, alarm.id, !alarm.enabled);
                if (!alarm.enabled) {
                    SetAlarm.popAlarmSetToast(this, alarm.hour, alarm.minutes,
                            alarm.daysOfWeek);
                }
                return true;

            case R.id.edit_alarm:
                Intent intent = new Intent(this, SetAlarm.class);
                intent.putExtra(Alarms.ALARM_ID, id);
                startActivity(intent);
                return true;

            default:
                break;
        }
        return super.onContextItemSelected(item);
    }
    
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
     * 创建菜单
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view,
            ContextMenuInfo menuInfo) {
        // Inflate the menu from xml.
        getMenuInflater().inflate(R.menu.context_menu, menu);

        // Use the current item to create a custom view for the header.
        final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        final Cursor c =
                (Cursor) mAlarmsList.getAdapter().getItem((int) info.position);
        final Alarm alarm = new Alarm(c);

        // Construct the Calendar to compute the time.
        final Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, alarm.hour);
        cal.set(Calendar.MINUTE, alarm.minutes);
        final String time = Alarms.formatTime(this, cal);

        // Inflate the custom view and set each TextView's text.
        final View v = mFactory.inflate(R.layout.context_menu_header, null);
        TextView textView = (TextView) v.findViewById(R.id.header_time);
        textView.setText(time);
        textView = (TextView) v.findViewById(R.id.header_label);
        textView.setText(alarm.label);

        // Set the custom view on the menu.
        menu.setHeaderView(v);
        // Change the text based on the state of the alarm.
        if (alarm.enabled) {
            menu.findItem(R.id.enable_alarm).setTitle(R.string.disable_alarm);
        }
    }
    
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     * 设置菜单的点击事件的处理
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_item_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                return true;
            case R.id.menu_item_alarm_set_bg:
            	/**
            	 * modify by wangxianming in 2012-4-17
            	 * enter the set background class SetBackGround
            	 * author:wangxianming
            	 */
                startActivityForResult((new Intent(this, SetBackGround.class)), REQ_SET_BG);
                return true;
            case R.id.menu_item_add_alarm:
                addNewAlarm();
                return true;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    
	/*
     * (non-Javadoc)
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     * 创建菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.alarm_list_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
    
    /*
     * (non-Javadoc)
     * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
     * 创建菜单的点击事件响应
     */
	public void onItemClick(AdapterView<?> adapterView, View v, int pos, long id) {
		Intent intent = new Intent(this, SetAlarm.class);
        intent.putExtra(Alarms.ALARM_ID, (int) id);
        startActivity(intent);
		
	}
	
   @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	   SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
	   SharedPreferences.Editor editor = sharedPreferences.edit();
	   if(resultCode != RESULT_OK) {
		   return;
	   }
	   if(requestCode == REQ_SET_BG) {
		   switch(resultCode) {
		         case RESULT_OK:
		        	 Bundle b = data.getExtras();
		        	 int id = b.getInt("getDrawable");
		        	 editor.putInt(SETBACKGROUND, id);
		        	 editor.commit();
		        	 if(0 != id) {
		        		 //设置背景
		        		 mBglinearlayout.setBackgroundResource(id);
		        	 }
		        	 Log.v("wangxianming", "DeskClockMainActivity onActivityResult()----> id == "+id);
		        	 break;
		         default:
		        	 break;
		   }
	   }
		super.onActivityResult(requestCode, resultCode, data);
	}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ToastMaster.cancelToast();
        mCursor.close();
    }
}


【说明】有Android闹钟最终版【android源码闹钟解析】代码的,可以参照我的代码修改一下;

当然如果没有代码的:

(一)想要源码的可以留下邮箱,我看到后就给你发过去!

(二)也可以到我的csdn资源中下载:http://download.csdn.net/detail/wdaming1986/4240708

分享到:
评论

相关推荐

    Android闹钟.zip

    本压缩包"Android闹钟.zip"包含了一个实现此类功能的示例项目,帮助开发者了解如何在Android应用中创建和管理闹钟。 在Android开发中,`AlarmManager`是系统服务类,用于安排一次性或周期性的任务。`AlarmManager`...

    Android应用源码安卓闹钟简洁版注释详细

    标题中的“Android应用源码安卓闹钟简洁版注释详细”指的是一个开源的Android应用程序,其主要功能是实现一个简单的闹钟系统。这个项目对于学习Android应用开发,特别是闹钟功能的实现,提供了很好的参考。源码注释...

    android闹钟源代码

    本项目"android闹钟源代码"提供了一个实现五组闹钟功能的基础框架,同时也包含了秒表功能,这在实际应用中非常实用。下面将详细阐述这些功能的实现原理及其相关的编程概念。 1. **时间管理**:在Android中,处理...

    android 4.4 原生闹钟源码

    在Android 4.4.4系统中,原生闹钟应用是用户日常生活中不可或缺的一部分,它提供了设置和管理提醒的功能。对于开发者来说,深入理解其源码有助于优化自定义闹钟应用或者进行系统级功能扩展。现在我们来详细探讨这个...

    Android 小闹钟 源码

    本项目名为“Android小闹钟源码”,显然,它提供了一个完整的、可供学习和参考的Android应用实例,专注于闹钟功能的实现。下面我们将深入探讨Android小闹钟应用的开发知识点。 1. **AndroidManifest.xml**: - ...

    android studio 自定义adapter开发闹钟小案例

    本案例"android studio 自定义adapter开发闹钟小案例"将带你深入理解如何在Android Studio中利用Adapter来构建一个实用的闹钟功能,包括通知栏提醒以及数据持久化。 首先,`Adapter`是Android中连接数据源与UI组件...

    Android 闹钟源码.rar

    本资源“Android 闹钟源码.rar”提供了一个实现Android闹钟功能的代码示例,这对于开发者深入理解Android系统中的定时任务处理以及如何自定义闹钟应用非常有帮助。 首先,Android的闹钟功能主要由`AlarmManager`类...

    Android BrewClock闹钟.zip

    《Android BrewClock闹钟应用深度解析》 在Android平台中,各类应用程序如雨后春笋般涌现,其中BrewClock闹钟应用凭借其独特的功能和用户体验脱颖而出。本篇将深入探讨这款应用的设计理念、核心功能以及它如何充分...

    疯狂Android讲义源码

     2.4.10 可展开的列表组件(ExpandableListView) 101  2.4.11 网格视图(GridView)和  图像切换器(ImageSwitcher)  功能和用法 104  2.4.12 画廊视图(Gallery)的功能和  用法 107  2.5 对话框 110  ...

    安卓闹钟相关-本应用类似手机系统的时钟闹钟小工具框架简单代码简单需要仔细理解逻辑不复杂.rar

    在安卓平台上,开发一个类似于手机系统时钟的闹钟小工具涉及到多个关键知识点。这个压缩包文件提供的资源可能是一个简单的实现示例,旨在帮助开发者理解闹钟功能的底层逻辑,而不是一个完全可用的商业级应用。下面将...

    Android闹钟

    在本实例中,我们探讨的是一个简单的Android小闹钟应用,包含apk可执行文件以及源代码,是学习Android开发中闹钟功能的一个基础实践。 首先,Android的`AlarmManager`类是负责调度定时任务的核心组件。它允许应用...

    Android 8.0 系统自带 DeskClock

    8. **同步与备份**:如果设备支持 Google 账户同步,DeskClock 的闹钟、计时器和秒表设置可能可以自动备份到云端,换新设备或恢复出厂设置后可轻松恢复。 9. **通知整合**:在 Android 8.0 中,DeskClock 可能与...

    精通ANDROID 3(中文版)1/2

    第1章 Android计算平台简介  1.1 面向新PC的全新平台  1.2 Android的历史  1.3 Dalvik VM剖析  1.4 理解Android软件栈  1.5 使用Android SDK开发最终用户应用程序  1.5.1 Android模拟器  1.5.2 ...

    Android25闹钟项目——ArrayAdapter动态添加数据,显示数据,删除数据SharedPreferences存储数据,读取数据

    在Android应用开发中,ArrayAdapter是一种常用的视图适配器,它允许我们把数据集合绑定到ListView、Spinner等可滚动视图上。本项目“Android25闹钟项目”利用ArrayAdapter来动态添加、显示和删除数据,并通过...

    安卓Android源码——仿Siri的中文语音助理源码.zip

    这个压缩包文件"安卓Android源码——仿Siri的中文语音助理源码.zip"提供了一个实现这一功能的基础框架,帮助开发者理解和学习如何构建一个智能语音助手。下面我们将详细探讨其中涉及的关键知识点。 首先,语音识别...

    android应用源码闹钟+秒表+倒计时+时钟四合一源码-IT计算机-毕业设计.zip

    这篇IT技术文章将深入探讨基于Android平台的四合一应用程序源码,它包含了闹钟、秒表、倒计时和时钟功能。对于Android开发者,尤其是正在进行毕业设计的学生来说,这样的项目是一个宝贵的资源,有助于理解Android...

    timely闹铃提取

    在IT领域,尤其是在移动设备应用开发中,闹钟功能是一个不可或缺的部分。"Timely闹铃提取"这个主题涉及的是从名为"Timely"的应用程序中导出或提取闹钟声音文件的过程。Timely可能是一款专注于时间管理或者闹钟功能的...

    正点闹钟甜美气质版中文普通话女声报时语音包.rar

    6. **跨平台兼容性**:正点闹钟作为一款应用程序,需要考虑跨平台的兼容性,这意味着这个甜美女声语音包应该能够在Android、iOS或其他操作系统上正常工作。开发者需要确保不同平台上的音频播放效果一致。 7. **数据...

    简易闹钟应用(课程项目)

    - 使用Java的Calendar类或者Android的DatePicker和TimePicker组件来允许用户选择设定闹钟的时间。 - AlarmManager用于设置定时触发闹钟,它可以精确到秒,确保在指定时间唤醒设备。 4. **用户交互**: - 设置...

Global site tag (gtag.js) - Google Analytics