8手機當中肯定是有鬧鐘的,這是不用說的,要不然就不是手機了。對吧。
下面我根據(jù)廣播的方式寫了一個鬧鐘,大家請看圖:
下面讓我們看一下原代碼的是如何寫的,
package com.smart;
import java.util.Calendar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
public class AlarmReceiver extends BroadcastReceiver {
/**
* 通過廣播進行掃描,是否到達時間后再響起鬧鈴
*
* */
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences=context.getSharedPreferences("alarm_record", Activity.MODE_PRIVATE);
String hour=String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
String minute=String.valueOf(Calendar.getInstance().get(Calendar.MINUTE));
String time=sharedPreferences.getString(hour+":"+minute, null);//小時與分,
if(time!=null){//判斷是否為空,然后通過創(chuàng)建,
MediaPlayer mediaPlayer=MediaPlayer.create(context, R.raw.llb);
mediaPlayer.start();//開始
}
}
}
package com.smart;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
public class Main extends Activity implements OnClickListener{
private TextView alarmRecord;
private SharedPreferences sharedPreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button addAlarm=(Button)findViewById(R.id.addAlarm);
alarmRecord=(TextView)findViewById(R.id.alarmRecord);
addAlarm.setOnClickListener(this);
sharedPreferences=getSharedPreferences("alarm_record", Activity.MODE_PRIVATE);
AlarmManager aManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(this,AlarmReceiver.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this, 0, intent, 0);
aManager.setRepeating(AlarmManager.RTC, 0, 60*1000, pendingIntent);
}
@Override
public void onClick(View v) {
View view=getLayoutInflater().inflate(R.layout.llb, null);//
final TimePicker timePicker=(TimePicker)view.findViewById(R.id.timepicker);
timePicker.setIs24HourView(true);//
new AlertDialog.Builder(this).setTitle("設(shè)置鬧鈴時間").setView(view).setPositiveButton("確定", new DialogInterface.OnClickListener() {
//設(shè)置標題
@Override
public void onClick(DialogInterface dialog, int which) {
//按鈕事件觸發(fā)方法
String timeStr=String.valueOf(timePicker.getCurrentHour())+":"+String.valueOf(timePicker.getCurrentMinute());
alarmRecord.setText(alarmRecord.getText().toString()+"
"+timeStr);
sharedPreferences.edit().putString(timeStr, timeStr).commit();
}
}).setNegativeButton("取消", null).show();
}
}原代碼下載
|