正文  多媒体 > 闹钟 >

Android 闹钟 android开发教程

/** Android 闹钟* Android API中提供了AlarmManager类,可以设置在指定的* 时间运行某些动作。* 主程序中以getSystemService(...

/*
 * Android 闹钟
 * Android API中提供了AlarmManager类,可以设置在指定的
 * 时间运行某些动作。
 * 主程序中以getSystemService(ALARM_SERVICE)取得AlarmManager
 * 并利用set()和setRepeating()两个方法来实现两种不同类型的闹钟。
 *
 * 1.只响一次的闹钟:当点击“设置闹钟”按钮时,会触发Button的
 * onClick事件,跳出TimePickerDialog来设置时间,设置完后,就以
 * PendingIntent.getBroadcast()生成PendingIntent,再利用
 * AlarmManager的set()将设置的时间与PendingIntent传入AlarmManager,
 * 最后以Toast提示用户以完成设置,并改变屏幕上的设置时间。
 *
 * 2.重复响起的闹钟:当点击“设置闹钟”按钮时,会触发Button的
 * onClick事件,跳出自定义的Layout的AlertDialog来设置开始时间与
 * 重复间隔。设置完成后,以PendingIntent.getBroadcast()生成
 * PendingIntent,再利用 AlarmManager的setReapting(),来设置开始
 * 时间、重复间隔与与PendingIntent传入AlarmManager,最后以Toast
 * 提示用户以完成设置,并改变屏幕上的设置时间。
 *
 * 程序中以cancel()这个方法来删除AlarmManager中设置的闹钟。
 */
import 略;
[java]
public class Ex06_10Activity extends Activity { 
    private TextView setTime1, setTime2; 
    private Button mButton1, mButton2, mButton3, mButton4; 
    private Calendar c = Calendar.getInstance(); 
 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
 
        // 只响一次闹钟设置 
        setTime1 = (TextView) findViewById(R.id.setTime1); 
        setTime2 = (TextView) findViewById(R.id.setTime2); 
        mButton1 = (Button) findViewById(R.id.mButton1); 
        mButton2 = (Button) findViewById(R.id.mButton2); 
        mButton3 = (Button) findViewById(R.id.mButton3); 
        mButton4 = (Button) findViewById(R.id.mButton4); 
 
        mButton1.setOnClickListener(new OnClickListener() { 
 
            @Override 
            public void onClick(View v) { 
                // TODO Auto-generated method stub 
                // 取得单击按钮时的时间作为TimePickerDialog的默认值 
                c.setTimeInMillis(System.currentTimeMillis()); 
                int mHour = c.get(Calendar.HOUR_OF_DAY); 
                int mMinute = c.get(Calendar.MINUTE); 
 
                // 跳出TimePickerDialog来设置时间 
                new TimePickerDialog(Ex06_10Activity.this, 
                        new TimePickerDialog.OnTimeSetListener() { 
 
                            @Override 
                            public void onTimeSet(TimePicker view, 
                                    int hourOfDay, int minute) { 
                                // TODO Auto-generated method stub 
                                // 取得设置后的时间,秒跟毫秒设为0 
                                c.setTimeInMillis(System.currentTimeMillis()); 
                                c.set(Calendar.HOUR_OF_DAY, hourOfDay); 
                                c.set(Calendar.MINUTE, minute); 
                                c.set(Calendar.SECOND, 0); 
                                c.set(Calendar.MILLISECOND, 0); 
                                // 指定闹钟设置的时间到时,要运行的CallAlarm.class 
                                Intent intent = new Intent( 
                                        Ex06_10Activity.this, CallAlarm.class); 
                                PendingIntent sender = PendingIntent 
                                        .getBroadcast( 
                                                Ex06_10Activity.this, 
                                                0, 
                                                intent, 
                                                PendingIntent.FLAG_UPDATE_CURRENT); 
                                // AlarmManaer.RTC_WAKEUP设置服务在系统休眠时同样会运行 
                                // 以set()设置的PendingIntent只会运行一次 
                                AlarmManager am; 
                                am = (AlarmManager) getSystemService(ALARM_SERVICE); 
                                am.set(AlarmManager.RTC_WAKEUP, 
                                        c.getTimeInMillis(), sender); 
                                // 更新显示的设置闹钟时间 
                                String tmpS = format(hourOfDay) + ":" 
                                        + format(minute); 
                                setTime1.setText(tmpS); 
                                Toast.makeText(Ex06_10Activity.this, 
                                        "设置的闹钟时间为:" + tmpS, Toast.LENGTH_LONG) 
                                        .show(); 
                            } 
                        }, mHour, mMinute, true).show(); 
            } 
        }); 
 
        // 只响一次的闹钟删除 
        mButton2.setOnClickListener(new OnClickListener() { 
            @Override 
            public void onClick(View v) { 
                // TODO Auto-generated method stub 
                Intent intent = new Intent(Ex06_10Activity.this, 
                        CallAlarm.class); 
                PendingIntent sender = PendingIntent.getBroadcast( 
                        Ex06_10Activity.this, 0, intent, 0); 
                AlarmManager am; 
                am = (AlarmManager) getSystemService(ALARM_SERVICE); 
                am.cancel(sender); 
                Toast.makeText(Ex06_10Activity.this, "闹钟已删除!", 
                        Toast.LENGTH_LONG).show(); 
                setTime1.setText("目前无设置!"); 
            } 
        }); 
        // 重复响起的闹钟设置///////////////////////////////// 
        // 重复响起的闹钟的设置画面,引用timeset.xml 
        LayoutInflater factory = LayoutInflater.from(this); 
        final View setView = factory.inflate(R.layout.timeset, null); 
        final TimePicker tPicker = (TimePicker) setView 
                .findViewById(R.id.tPicker); 
        tPicker.setIs24HourView(true); 
        final AlertDialog di = new AlertDialog.Builder(Ex06_10Activity.this) 
                .setIcon(R.drawable.clock).setTitle("设置").setView(setView) 
                .setPositiveButton("确定", new DialogInterface.OnClickListener() { 
                    @Override 
                    public void onClick(DialogInterface dialog, int which) { 
                        // TODO Auto-generated method stub 
                        // 取得设置的间隔秒数 
                        EditText ed = (EditText) setView 
                                .findViewById(R.id.mEdit); 
                        int times = Integer.parseInt(ed.getText().toString()) * 1000; 
                        // 取得设置后的时间,秒跟毫秒设为0 
                        c.setTimeInMillis(System.currentTimeMillis()); 
                        c.set(Calendar.HOUR_OF_DAY, tPicker.getCurrentHour()); 
                        c.set(Calendar.MINUTE, tPicker.getCurrentMinute()); 
                        c.set(Calendar.SECOND, 0); 
                        c.set(Calendar.MILLISECOND, 0); 
                        // 指定闹钟设置的时间到时,要运行的CallAlarm.class 
                        Intent intent = new Intent(Ex06_10Activity.this, 
                                CallAlarm.class); 
                        PendingIntent sender = PendingIntent.getBroadcast( 
                                Ex06_10Activity.this, 1, intent, 0); 
                        // setReapting()可让闹钟重复运行 
                        AlarmManager am; 
                        am = (AlarmManager) getSystemService(ALARM_SERVICE); 
                        am.setRepeating(AlarmManager.RTC_WAKEUP, 
                                c.getTimeInMillis(), times, sender); 
                        // 更新显示的设置闹钟时间 
                        String tmpS = format(tPicker.getCurrentHour()) + ":" 
                                + format(tPicker.getCurrentMinute()); 
                        setTime2.setText(tmpS); 
                        Toast.makeText( 
                                Ex06_10Activity.this, 
                                "设置的闹钟时间为:" + tmpS + "\n重复时间间隔是:" + times 
                                        / 1000+"秒", Toast.LENGTH_SHORT).show(); 
                    } 
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() { 
                     
                    @Override 
                    public void onClick(DialogInterface dialog, int which) { 
                        // TODO Auto-generated method stub 
                         
                    } 
                }).create(); 
 
        // 重复响起闹钟设置的按钮 
        mButton3.setOnClickListener(new OnClickListener() { 
 
            @Override 
            public void onClick(View v) { 
                // TODO Auto-generated method stub 
                // 取得单击按钮时的时间作为tPicker的默认值 
                c.setTimeInMillis(System.currentTimeMillis()); 
                tPicker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY)); 
                tPicker.setCurrentMinute(c.get(Calendar.MINUTE)); 
                di.show(); 
            } 
        }); 
 
        // 重复响的闹钟 删除 
        mButton4.setOnClickListener(new OnClickListener() { 
            @Override 
            public void onClick(View v) { 
                // TODO Auto-generated method stub 
                Intent intent = new Intent(Ex06_10Activity.this, 
                        CallAlarm.class); 
                PendingIntent sender = PendingIntent.getBroadcast( 
                        Ex06_10Activity.this, 1, intent, 0); 
                AlarmManager am; 
                am = (AlarmManager) getSystemService(ALARM_SERVICE); 
                am.cancel(sender); 
                Toast.makeText(Ex06_10Activity.this, "闹钟已删除!", 
                        Toast.LENGTH_LONG).show(); 
                setTime2.setText("目前无设置!"); 
            } 
        }); 
    } 
 
    private String format(int x) { 
        // TODO Auto-generated method stub 
        String s = "" + x; 
        if (s.length() == 1) { 
            s = "0" + s; 
        } 
        return s; 
    } 

闹钟实际运行的动作AlarmAlert.java代码:
[java] 
public class AlarmAlert extends Activity { 
    public void onCreate(Bundle SavedInstanceState) { 
        super.onCreate(SavedInstanceState); 
        new AlertDialog.Builder(AlarmAlert.this).setIcon(R.drawable.clock) 
                .setTitle("闹钟响了。。。").setMessage("快起床!!!") 
                .setPositiveButton("关闭", new DialogInterface.OnClickListener() { 
 
                    @Override 
                    public void onClick(DialogInterface dialog, int which) { 
                        // TODO Auto-generated method stub 
                        AlarmAlert.this.finish(); 
                    } 
                }).show(); 
    } 

调用闹钟Alert的Receive,CallAlarm.java代码:
[java]
public class CallAlarm extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
        // TODO Auto-generated method stub 
        Intent i = new Intent(context, AlarmAlert.class); 
        Bundle bundleRet = new Bundle(); 
        bundleRet.putString("SRC_CALLER", ""); 
        i.putExtras(bundleRet); 
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        context.startActivity(i); 
    } 

下面我们来看看布局代码:main.xml
[html]
<?xml version="1.0" encoding="utf-8"?> 
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/layout1" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@drawable/white" > 
 
    <DigitalClock 
        android:id="@+id/dClock" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_x="30dp" 
        android:layout_y="32dp" 
        android:textColor="@drawable/blue" 
        android:textSize="40sp" /> 
 
    <TextView 
        android:id="@+id/text1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_x="10dp" 
        android:layout_y="90dp" 
        android:text="@string/str_title1" 
        android:textColor="@drawable/black" 
        android:textSize="20sp" /> 
 
    <Button 
        android:id="@+id/mButton1" 
        android:layout_width="wrap_content" 
        android:layout_height="40dp" 
        android:layout_x="160dp" 
        android:layout_y="86dp" 
        android:text="@string/str_button1" 
        android:textColor="@drawable/black" 
        android:textSize="18sp" /> 
 
    <TextView 
        android:id="@+id/text2" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_x="10dp" 
        android:layout_y="227dp" 
        android:text="@string/str_title2" 
        android:textColor="@drawable/black" 
        android:textSize="20sp" /> 
 
    <Button 
        android:id="@+id/mButton4" 
        android:layout_width="wrap_content" 
        android:layout_height="40dp" 
        android:layout_x="160dp" 
        android:layout_y="269dp" 
        android:text="@string/str_button2" 
        android:textColor="@drawable/black" 
        android:textSize="18sp" /> 
 
    <Button 
        android:id="@+id/mButton2" 
        android:layout_width="wrap_content" 
        android:layout_height="40dp" 
        android:layout_x="160dp" 
        android:layout_y="140dp" 
        android:text="@string/str_button2" 
        android:textColor="@drawable/black" 
        android:textSize="18sp" /> 
 
    <Button 
        android:id="@+id/mButton3" 
        android:layout_width="wrap_content" 
        android:layout_height="40dp" 
        android:layout_x="160dp" 
        android:layout_y="220dp" 
        android:text="@string/str_button1" 
        android:textColor="@drawable/black" 
        android:textSize="18sp" /> 
 
    <TextView 
        android:id="@+id/setTime2" 
        android:layout_width="135dp" 
        android:layout_height="wrap_content" 
        android:layout_x="10dp" 
        android:layout_y="278dp" 
        android:text="@string/str_default" 
        android:textColor="@drawable/red" 
        android:textSize="16sp" /> 
 
    <TextView 
        android:id="@+id/setTime1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_x="10dp" 
        android:layout_y="150dp" 
        android:text="@string/str_default" 
        android:textColor="@drawable/red" 
        android:textSize="16sp" /> 
 
</AbsoluteLayout> 
 

timeset.xml代码:
[html]
<?xml version="1.0" encoding="utf-8"?> 
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/layout2" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 
 
    <EditText 
        android:id="@+id/mEdit" 
        android:layout_width="52dp" 
        android:layout_height="46dp" 
        android:layout_x="112dp" 
        android:layout_y="188dp" 
        android:inputType="number" 
        android:text="10" 
        android:textSize="16sp" > 
 
        <requestFocus /> 
    </EditText> 
 
    <TimePicker 
        android:id="@+id/tPicker" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_x="27dp" 
        android:layout_y="47dp" /> 
 
    <TextView 
        android:id="@+id/text1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_x="14dp" 
        android:layout_y="17dp" 
        android:text="@string/str_text1" 
        android:textColor="@drawable/white" 
        android:textSize="16sp" /> 
 
    <TextView 
        android:id="@+id/text2" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_x="6dp" 
        android:layout_y="196dp" 
        android:text="@string/str_text2" 
        android:textColor="@drawable/white" 
        android:textSize="16sp" /> 
 
    <TextView 
        android:id="@+id/text3" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_x="178dp" 
        android:layout_y="196dp" 
        android:text="@string/str_text3" 
        android:textColor="@drawable/white" 
        android:textSize="16sp" /> 
 
</AbsoluteLayout> 

下面我们来看看程序运行后的结果:

 


AndroidManifest.xml里必须先添加CallAlarm的receiver设置,让应用程序在被启动时就先注册这个Receive。
     </activity>
        <activity android:name=".AlarmAlert" >
      </activity>


作者:Jasonzhou613