android Demo 闹钟

蒋永宁
2023-12-01

MP3是可以设成来电铃声的,你在内存卡里,建立一个media的文件夹,再在这个文件夹里面建立名为audio的文件夹,最后再在audio文件夹里建立三个文件夹,分别是notifications(放置在这个文件夹里的铃声可以设置短信音)、ringtones(这个用于设置来电铃声)、ALARMS(这个用于设置闹铃声)

package com.lx;

import java.util.Calendar;
import java.util.Date;
import java.util.zip.DataFormatException;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;


public class AlarmClockActivity extends Activity {
 
 private static final String TAG= "AlarmClockActivity";
    Button btnStart; 
    Button btnStop; 
 
    TextView mTextView; 
    private Button btnReal;
    Calendar calendar; 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);  
      
        setContentView(R.layout.main);  
        calendar = Calendar.getInstance();  
 
        mTextView = (TextView) findViewById(R.id.mTextView);  
        btnStart = (Button) findViewById(R.id.btnStart);  
        btnStop = (Button) findViewById(R.id.btnStop);  
        btnReal = (Button) findViewById(R.id.btnReal);
       
       
        btnReal.setOnClickListener(new View.OnClickListener() {
 
   @Override
   public void onClick(View v) {
    AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
    int requestCode = 0;
    PendingIntent pendIntent = PendingIntent.getBroadcast(getApplicationContext(),
      requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
    // 5秒后发送广播,然后每个10秒重复发广播。广播都是直接发到AlarmReceiver的
    long triggerAtTime = SystemClock.elapsedRealtime() + 5 * 1000;
    int interval = 10 * 1000;
    alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, interval, pendIntent);
    
   }
  });
       
        btnStart.setOnClickListener(new View.OnClickListener() {  
            public void onClick(View v) {  
                calendar.setTimeInMillis(System.currentTimeMillis());  
                int mHour = calendar.get(Calendar.HOUR_OF_DAY);  
                int mMinute = calendar.get(Calendar.MINUTE);  
                new TimePickerDialog(AlarmClockActivity.this,  
                        new TimePickerDialog.OnTimeSetListener() {  
                            public void onTimeSet(TimePicker view,  
                                    int hourOfDay, int minute) {  
                                calendar.setTimeInMillis(System  
                                        .currentTimeMillis());  
                                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);  
                                calendar.set(Calendar.MINUTE, minute);  
                                calendar.set(Calendar.SECOND, 0);  
                                calendar.set(Calendar.MILLISECOND, 0);  
                                /* 建立Intent和PendingIntent,来调用目标组件 */ 
                                Intent intent = new Intent(AlarmClockActivity.this,  
                                        AlarmReceiver.class);  
                                PendingIntent pendingIntent = PendingIntent  
                                        .getBroadcast(AlarmClockActivity.this, 0,  
                                                intent, 0);  
                                AlarmManager am;  
                                /* 获取闹钟管理的实例 */ 
                                am = (AlarmManager) getSystemService(ALARM_SERVICE);  
                                /* 设置闹钟 */ 
                                am.set(AlarmManager.RTC_WAKEUP, calendar  
                                        .getTimeInMillis(), pendingIntent);  
                               
                                Date date = calendar.getTime();
                               
                                long l = calendar.getTimeInMillis();
                               
                                DateFormat format = new DateFormat();
                               
                              final CharSequence s =  format.format("MM-dd-yyyy h:mmaa", date);
                                Log.i(TAG, "------>format: "+ s);
                               
                                /* 设置周期闹 */ 
                                am.setRepeating(AlarmManager.RTC_WAKEUP, l
                                        , (24 * 60 * 60 * 1000),  
                                        pendingIntent);  
                                String tmpS = "设置闹钟时间为" + format(hourOfDay)  
                                        + ":" + format(minute);  
                                mTextView.setText(tmpS);  
                            }  
                        }, mHour, mMinute, true).show();  
            }  
        });  

       
        btnStop.setOnClickListener(new View.OnClickListener() {  
            public void onClick(View v) {  
                Intent intent = new Intent(AlarmClockActivity.this, AlarmReceiver.class);  
                PendingIntent pendingIntent = PendingIntent.getBroadcast(  
                  AlarmClockActivity.this, 0, intent, 0);  
                AlarmManager am;  
                /* 获取闹钟管理的实例 */ 
                am = (AlarmManager) getSystemService(ALARM_SERVICE);  
                /* 取消 */ 
                am.cancel(pendingIntent);  
                mTextView.setText("闹钟已取消!");  
            }  
        });  

    }
    /* 格式化字符串(7:3->07:03) */ 
    private String format(int x) {  
        String s = "" + x;  
        if (s.length() == 1)  
            s = "0" + s;  
        return s;  
    }  

}

----------------------------------------------------------- main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  android:id="@+id/mTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
   
    <Button
        android:id="@+id/btnStart"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="startClock"  
   
    /> 
   
    <Button android:id="@+id/btnReal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="real"
   
    />
     <Button
        android:id="@+id/btnStop"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="stopClock"  
   
    /> 
   
</LinearLayout>
-------------------------------------------

package com.lx;

import java.io.File;
import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver  {

 private static final String TAG = "AlarmReceiver";
 private MediaPlayer mPlayer = null;


 @Override
 public void onReceive(Context arg0, Intent arg1) {
  
   Toast.makeText(arg0, "你设置的闹钟时间到了", Toast.LENGTH_LONG).show(); 
         try {
   doPlay();
  } catch (IllegalArgumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalStateException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (Exception e) {
   DestoryPlay();
   e.printStackTrace();
  }
 }

 public String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()  
                            .equals(android.os.Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if   (sdCardExist)  
        {                              
          sdDir = Environment.getExternalStorageDirectory();//获取跟目录
       }  
        return sdDir.toString();
       
 }
 private void doPlay() throws IllegalArgumentException, IllegalStateException, IOException{
  
  mPlayer = new MediaPlayer();
  String path = getSDPath()+ "/"+ "music/2007060905434704.mp3";
  Log.i(TAG, "====>Path "+ path);
  mPlayer.setDataSource(path);
  mPlayer.prepare();
  mPlayer.start();
  
 }
 
 private void DestoryPlay(){
  if (null != mPlayer){
   mPlayer.stop();
   mPlayer.release();
   mPlayer = null;
  }
 }
}
-----------------------------------------------------------------AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.lx"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="9" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AlarmClockActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


    <receiver android:name=".AlarmReceiver"  />
   
    </application>
   
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
</manifest>

 

 类似资料: