Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android Alarm鬧鐘發送廣播播放音樂

android Alarm鬧鐘發送廣播播放音樂

編輯:關於Android編程

通過網上的例子 自己根據相關功能修改的 如有不合理的地方 請提出來 互相學習


一共有3個類 MainActivity.java 主程序
AlarmReceiver.java 廣播接收器
MusicService.java service播放音樂

MainActivity.java
package com.yqy.yqy_alarm;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends Activity {

	private TextView tv = null;  
    private Button setTime,cancelTime;  
    private Calendar c = null;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);
        String alarm = getIntent().getStringExtra("alarm");
        if(alarm != null&&alarm.equals("alarm")){
            stopService(new Intent("com.yqy.yqy_alarm.MUSIC"));  
        }
        
        tv = (TextView)findViewById(R.id.tv);  
        setTime = (Button)findViewById(R.id.setAlarm);  
        cancelTime = (Button)findViewById(R.id.cancelAlarm);  
        //得到日歷實例,主要是為了下面的獲取時間  
        c = Calendar.getInstance();  
        setTime.setOnClickListener(new Button.OnClickListener()  
        {  
  
            @Override  
            public void onClick(View arg0) {  
                c.setTimeInMillis(System.currentTimeMillis());  
                int hour = c.get(Calendar.HOUR_OF_DAY);  
                int minute = c.get(Calendar.MINUTE);  
                new TimePickerDialog(MainActivity.this, minute, new TimePickerDialog.OnTimeSetListener() {  
                    @Override  
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {  
                        //是設置日歷的時間,主要是讓日歷的年月日和當前同步  
                        c.setTimeInMillis(System.currentTimeMillis());  
                        //設置小時分鐘,秒和毫秒都設置為0  
                        c.set(Calendar.HOUR_OF_DAY, hourOfDay);  
                        c.set(Calendar.MINUTE, minute);  
                        c.set(Calendar.SECOND, 0);  
                        c.set(Calendar.MILLISECOND, 0);  
                          
                        int requestCode = 0;//鬧鐘的唯一標示
                        Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);  
                        intent.putExtra("requestCode", requestCode);
                        PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, requestCode, intent, 0);  
                        //得到AlarmManager實例  
                        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);  
                        //根據當前時間預設一個警報  
                        am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);  
                        /** 
                         * 第一個參數是警報類型;第二個參數是第一次執行的延遲時間,可以延遲,也可以馬上執行;第三個參數是重復周期為一天 
                         * 這句話的意思是設置鬧鈴重復周期,也就是執行警報的間隔時間 
                         */  
//                      am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+(60*1000),   
//                              (24*60*60*1000), pi);  
//                        am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),   
//                                1000*60*5, pi);  
                  
                        String msg = hourOfDay+":"+minute;  
                        tv.setText("當前設置的鬧鐘時間:"+msg);  
                    }  
                }, hour, minute, true).show();  
                //上面的TimePickerDialog中的5個參數參考:http://blog.csdn.net/yang_hui1986527/article/details/6839342  
            }  
              
        });  
          
        cancelTime.setOnClickListener(new Button.OnClickListener()  
        {  
  
            @Override  
            public void onClick(View v) {  
                Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);  
                PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0,  
                        intent, 0);  
                AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);  
                //取消警報  
                am.cancel(pi);  
                tv.setText("鬧鐘取消");  
                //取消鬧鐘的同時取消音樂  
                stopService(new Intent("com.yqy.yqy_alarm.MUSIC"));  
            }  
              
        });  
    }  
}  

AlarmReceiver
package com.yqy.yqy_alarm;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

	Intent intent;
	int requestCode = -1;

	@Override
	public void onReceive(Context context, Intent arg1) {
		
		requestCode = arg1.getIntExtra("requestCode", 0);
		
		NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);               
		Notification n = new Notification(R.drawable.ic_launcher, "Hello,there!", System.currentTimeMillis());             
		n.flags = Notification.FLAG_AUTO_CANCEL;    
		intent = new Intent(context, MainActivity.class);
		intent.putExtra("alarm", "alarm");
		intent.setComponent(new ComponentName("com.yqy.yqy_alarm", "com.yqy.yqy_alarm.MainActivity"));
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);//關鍵的一步,設置啟動模式
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,  intent, PendingIntent.FLAG_CANCEL_CURRENT);  
		
		n.setLatestEventInfo(
		        context,
		        "Hello,there!", 
		        "Hello,there,I'm john.", 
		        contentIntent);
		nm.notify(R.string.app_name, n);
		
        Toast.makeText(context, "鬧鐘時間到", Toast.LENGTH_SHORT).show();  
        intent = new Intent("com.yqy.yqy_alarm.MUSIC");
        //啟動Service播放音樂  
        context.stopService(new Intent("com.yqy.yqy_alarm.MUSIC"));
        context.startService(intent);  
		
		
	}
	
}

MusicService
package com.yqy.yqy_alarm;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MusicService extends Service {  
    private MediaPlayer player;  
    @Override  
    public IBinder onBind(Intent intent) {  
        // TODO Auto-generated method stub  
        return null;  
    }  
      
    public void onStart(Intent intent, int startId)  
    {  
        super.onStart(intent, startId);  
        player = MediaPlayer.create(this, R.raw.beep);  
        player.setLooping(true);
        player.start();  
    }  
    public void onDestroy()  
    {  
        super.onDestroy();  
        if(player != null){
            player.stop();      
        }
    }  
  
}  



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved