今天在项目中遇到了一个类似闹铃的功能 突然想起一年以前 为了写个闹铃要费劲脑汁好久还没写好 现在就写下来 记录一下 算是学习android 一周年纪念 虽然过程中也是 网上找代码但是 构思和界面都是自己的,算是原创吧。
首先定义好闹铃界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/common_header_color_bg"
android:orientation="vertical" >
<include layout="@layout/common_header" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="50dip"
android:layout_marginRight="50dip"
android:layout_marginTop="20dip"
android:background="@drawable/addremind_bg"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
android:layout_width="45dip"
android:layout_height="45dip"
android:scaleType="fitXY"
android:src="@drawable/time" />
<Button
android:id="@+id/addremind"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="30dip"
android:background="@null"
android:text="添加考勤提醒"
android:textSize="20sp" />
</LinearLayout>
<ListView
android:id="@+id/remind_listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:background="@color/white"
android:divider="@color/common_header_color_bg"
android:dividerHeight="4dip" />
</LinearLayout>
然后在主界面 写好声明
private Button title_back, addRemindLayout;
private TextView head_title;
private ListView remindList;
private AttendanceReminderAdapter adapter;
List<AttRemind> reminds = new ArrayList<AttRemind>();
static final int ADDREMIND = 0x16;
private DbHelper dbHelper;
private void initViews() {
title_back = (Button) findViewById(R.id.common_head_back);
head_title = (TextView) findViewById(R.id.common_head_title);
addRemindLayout = (Button) findViewById(R.id.addremind);
remindList = (ListView) findViewById(R.id.remind_listview);
head_title.setText("考勤提醒");
title_back.setOnClickListener(this);
addRemindLayout.setOnClickListener(this);
adapter = new AttendanceReminderAdapter(reminds,
AttendanceReminder.this);
remindList.setAdapter(adapter);
remindList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(AttendanceReminder.this,
AddRemind.class);
AttRemind attRemind = reminds.get(arg2);
intent.putExtra("remind", attRemind);
startActivityForResult(intent, ADDREMIND);
}
});
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.common_head_back:
finish();
break;
case R.id.addremind:
showTimePicker();
break;
default:
break;
}
}
在这里 我选择点击按钮后弹出 timepickerdialog 设置时间,在timepicker的回调方法中使用startactivityforreuout 方法 跳转到另外一个界面 进行闹钟设置 然后在设置完成之后通过onActivityresult 方法 对设置好的闹钟进行保存,同时更新界面上的listview 显示闹钟,onactivityresult的方法如下
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
AttRemind attRemind; if (resultCode == RESULT_OK) { attRemind = (AttRemind) data.getSerializableExtra("attremind"); if (attRemind != null) { // reminds.add(attRemind); if (attRemind.getId() != -1) { ContentValues contentValues = new ContentValues(); contentValues.put(DBInfo.FIELD_REMIND_NAME, attRemind.getSeason()); contentValues.put(DBInfo.FIELD_REMIND_TIME, attRemind.getTime()); contentValues.put(DBInfo.FIELD_REMIND_TYPE, "true"); contentValues.put(DBInfo.FIELD_REPEAT_DATE, attRemind.getRepeatDay()); contentValues.put(DBInfo.FIELD_ROLLING_TYPE, attRemind.getRollingType()); dbHelper.update(attRemind.getId(), contentValues); Toast.makeText(getApplicationContext(), "修改考勤提醒成功", Toast.LENGTH_SHORT).show(); } else { addRemindToDB(attRemind); Toast.makeText(getApplicationContext(), "添加考勤提醒成功", Toast.LENGTH_SHORT).show(); } initDB(); adapter.notifyDataSetChanged(); startAlarm(reminds); } } };
对设置好的闹钟 我们要进行保存操作这里我选择用sqlite进行操作
在界面中操作sqlite的方法 如下
private void initDB() {
// TODO Auto-generated method stub dbHelper = new DbHelper(AttendanceReminder.this); Cursor c = dbHelper.selectAll(); if (c != null) { reminds.clear(); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { AttRemind attRemind = new AttRemind(); attRemind.setRepeatDay(c.getString(c .getColumnIndex(DBInfo.FIELD_REPEAT_DATE))); String time = c.getString(c .getColumnIndex(DBInfo.FIELD_REMIND_TIME)); try { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); Date date = sdf.parse(time); attRemind.setHours(date.getHours()); attRemind.setMinute(date.getMinutes()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } attRemind.setSeason(c.getString(c .getColumnIndex(DBInfo.FIELD_REMIND_NAME))); attRemind.setRolling(Boolean.getBoolean(c.getString(c .getColumnIndex(DBInfo.FIELD_REMIND_TYPE)))); attRemind.setId(c.getInt(c .getColumnIndex(DBInfo.FIELD_REMIND_ID))); reminds.add(attRemind); } } }
在执行以下方法之前需要自己建一个DBhepler类 进行数据库初始化操作以及创建闹钟所需要的表DBhelper 类如下package com.samon.wq.DB; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.samon.wq.bean.Bean; public class DbHelper extends SQLiteOpenHelper { private final static String DATABASE_NAME = "samon.db"; private final static int DATABASE_VERSION = 1; private final static String TABLE_NAME = DBInfo.TABLENAME; public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" + DBInfo.FIELD_REMIND_ID + " integer primary key autoincrement," + DBInfo.FIELD_REMIND_NAME + " text ," + DBInfo.FIELD_REPEAT_DATE + " text ," + DBInfo.FIELD_REMIND_TIME + " text ," + DBInfo.FIELD_ROLLING_TYPE + " text ," + DBInfo.FIELD_REMIND_TYPE + " boolean BLOB DEFAULT true);"; db.execSQL(sql); } /** * 插入数据 * * @param table * 表明 * @param data * 数据(实体类数据) */ public int Insert(String table, Object data) { Map<String, Object> datamap = null; try { datamap = Bean.objToHash(data); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { ContentValues cv = new ContentValues(); Iterator iter = datamap.keySet().iterator(); for (Entry<String, Object> entry : datamap.entrySet()) { String key = entry.getKey().toString(); if (key.equals("id")) { continue; } String value = entry.getValue().toString(); cv.put(key, value); } Log.i("execSQL", cv.toString()); getDatabase().insert(table, null, cv); } catch (Exception e) { Log.e("Insert data", e.toString()); return -1; } return getInsertId(); } public int getInsertId() { String sql = "SELECT last_insert_rowid() as last_id"; Cursor cursor = getDatabase().rawQuery(sql, null); cursor.moveToFirst(); return cursor.getInt(0); } private SQLiteDatabase database; public SQLiteDatabase getDatabase() { if (database == null) { database = this.getWritableDatabase(); } return database; } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub String sql = " DROP TABLE IF EXISTS " + TABLE_NAME; db.execSQL(sql); onCreate(db); } public Cursor selectAll() { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null); return cursor; } public Cursor select(String remindid) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where " + DBInfo.FIELD_REMIND_ID + "=?", new String[] { remindid.toString() }); return cursor; } public long insert(ContentValues contentValues) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(DBInfo.FIELD_REMIND_ID, contentValues.getAsInteger(DBInfo.FIELD_REMIND_ID)); cv.put(DBInfo.FIELD_REMIND_NAME, contentValues.getAsString(DBInfo.FIELD_REMIND_NAME)); cv.put(DBInfo.FIELD_REMIND_TYPE, contentValues.getAsBoolean(DBInfo.FIELD_REMIND_TYPE)); cv.put(DBInfo.FIELD_REMIND_TIME, contentValues.getAsString(DBInfo.FIELD_REMIND_TIME)); cv.put(DBInfo.FIELD_REPEAT_DATE, contentValues.getAsString(DBInfo.FIELD_REPEAT_DATE)); cv.put(DBInfo.FIELD_ROLLING_TYPE, contentValues.getAsString(DBInfo.FIELD_ROLLING_TYPE)); long row = db.insert(TABLE_NAME, null, cv); return row; } public void delete(int id) { SQLiteDatabase db = this.getWritableDatabase(); String where = DBInfo.FIELD_REMIND_ID + "=?"; String[] whereValue = { Integer.toString(id) }; db.delete(TABLE_NAME, where, whereValue); } public void update(int id, ContentValues cv) { SQLiteDatabase db = this.getWritableDatabase(); String where = DBInfo.FIELD_REMIND_ID + "=?"; String[] whereValue = { Integer.toString(id) }; db.update(TABLE_NAME, cv, where, whereValue); } }
数据库就设置完成了在activityresult 跳转回来之后要设置启动alarmmanager 进行循环操作 发送广播
private void startAlarm(List<AttRemind> att_reminds) { AppReceiver.stopPollingService(getApplicationContext(), AttendanceReminder.class, "com.samon.ALARM_REMINDACTION"); // 获得AlarmManager实例 final AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); // 实例化Intent Intent intent = new Intent(); // 设置Intent action属性 intent.setAction("com.samon.ALARM_REMINDACTION"); // 实例化PendingIntent final PendingIntent sender = PendingIntent.getBroadcast( AttendanceReminder.this, 0, intent, 0); // 获得系统时间 final long time = System.currentTimeMillis(); am.set(AlarmManager.RTC_WAKEUP, time + 1000 * 10, sender);// 5秒后闹铃 // 重复提示,从当前时间开始,间隔5秒 am.setRepeating(AlarmManager.RTC_WAKEUP, time, 10 * 1000, sender); }
设置时间并跳转
在启动的新的界面里 设置界面 初始化 设置时间和标题OnTimeSetListener onTimeSetListener = new OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub Intent intent = new Intent(AttendanceReminder.this, AddRemind.class); intent.putExtra("hours", hourOfDay); intent.putExtra("minutes", minute); startActivityForResult(intent, ADDREMIND); } }; private void showTimePicker() { Calendar calender = Calendar.getInstance(); TimePickerDialog timePickerDialog = new TimePickerDialog( AttendanceReminder.this, onTimeSetListener, calender.get(Calendar.HOUR_OF_DAY), calender.get(Calendar.MINUTE), true); timePickerDialog.show(); }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/main_bg_color" android:orientation="vertical" > <include layout="@layout/common_header" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dip" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="提示名称" /> <EditText android:id="@+id/repeat_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="上班考勤" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dip" android:gravity="center" android:text="重复日期" /> <com.samon.wq.views.MySpinner android:id="@+id/repeatdate" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dip" android:gravity="center" android:text="设置时间" /> <TextView android:id="@+id/timetext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dip" android:gravity="center" android:text="设置时间" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dip" android:gravity="center" android:text="设置铃声" /> <TextView android:id="@+id/rintoneName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dip" android:gravity="center" android:text="点击选择铃声" /> </LinearLayout> <Button android:id="@+id/addremind_btn" android:layout_width="match_parent" android:layout_height="48dip" android:layout_margin="10dip" android:background="@drawable/addremind_bg" android:text="添加提醒" android:textSize="20sp" /> </LinearLayout>
private TextView timetext; private EditText remindName; private Button addremind_btn; private Button title_back; TextView rintoneName; private MySpinner repeat_spinner; private ArrayAdapter<CharSequence> spinnerAdapter; int hours, minutes; AttRemind attRemind; String rollingType; // 用于选择铃声后作相应的判断标记 private static final int REQUEST_CODE_PICK_RINGTONE = 1; // 保存铃声的Uri的字符串形式 private String mRingtoneUri = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub setContentView(R.layout.activity_addremin); super.onCreate(savedInstanceState); Intent intent = getIntent(); hours = intent.getIntExtra("hours", -1); minutes = intent.getIntExtra("minutes", -1); attRemind = (AttRemind) intent.getSerializableExtra("remind"); initViews(); } private void initViews() { // TODO Auto-generated method stub title_back = (Button) findViewById(R.id.common_head_back); title_back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); repeat_spinner = (MySpinner) findViewById(R.id.repeatdate); spinnerAdapter = ArrayAdapter.createFromResource(this, R.array.repeatday, R.layout.simple_spinner_item); // 设置下拉列表的风格 spinnerAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); repeat_spinner.initContent(getResources().getStringArray( R.array.repeatday)); // 将adapter 添加到spinner中 // repeat_spinner.setAdapter(spinnerAdapter); // // // 添加事件Spinner事件监听 // repeat_spinner.setOnItemSelectedListener(new // SpinnerSelectedListener()); // // 设置默认值 repeat_spinner.setVisibility(View.VISIBLE); timetext = (TextView) findViewById(R.id.timetext); timetext.setText(hours + ":" + minutes); timetext.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub showTimePicker(); } }); rintoneName = (TextView) findViewById(R.id.rintoneName); rintoneName.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub doPickRingtone(); } }); remindName = (EditText) findViewById(R.id.repeat_name); addremind_btn = (Button) findViewById(R.id.addremind_btn); addremind_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String remindreason = remindName.getText().toString(); if (remindreason.isEmpty()) { remindreason = "考勤提醒"; } String repeatDate = repeat_spinner.getText().toString(); if (repeatDate.isEmpty()) { repeatDate = "每天"; } Intent intent = new Intent(AddRemind.this, AttendanceReminder.class); AttRemind setAttRemind = new AttRemind(); setAttRemind.setSeason(remindreason); setAttRemind.setRepeatDay(repeatDate); setAttRemind.setRollingType(rollingType); if (attRemind == null) { setAttRemind.setHours(hours); setAttRemind.setMinute(minutes); intent.putExtra("attremind", setAttRemind); setResult(RESULT_OK, intent); finish(); } else { try { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); Date date = sdf.parse(timetext.getText().toString()); setAttRemind.setHours(date.getHours()); setAttRemind.setMinute(date.getMinutes()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } setAttRemind.setId(attRemind.getId()); intent.putExtra("attremind", setAttRemind); setResult(RESULT_OK, intent); finish(); } } }); if (attRemind != null) { timetext.setText(attRemind.getTime()); remindName.setText(attRemind.getSeason()); repeat_spinner.setText(attRemind.getRepeatDay()); } } OnTimeSetListener onTimeSetListener = new OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub hours = hourOfDay; minutes = minute; timetext.setText(hours + ":" + minutes); } }; private void showTimePicker() { Calendar calender = Calendar.getInstance(); TimePickerDialog timePickerDialog = new TimePickerDialog( AddRemind.this, onTimeSetListener, calender.get(Calendar.HOUR_OF_DAY), calender.get(Calendar.MINUTE), true); timePickerDialog.show(); }
这里我选择用系统自带的方法去调用系统铃声 点击textview 然后弹出对话框 选择铃声
// 启动选择铃声的对话框。 private void doPickRingtone() { Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); // Allow user to pick 'Default' intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true); // Show only ringtones intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE); // Don't show 'Silent' intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false); Uri ringtoneUri; if (mRingtoneUri != null) { ringtoneUri = Uri.parse(mRingtoneUri); } else { // Otherwise pick default ringtone Uri so that something is // selected. ringtoneUri = RingtoneManager .getDefaultUri(RingtoneManager.TYPE_RINGTONE); } // Put checkmark next to the current ringtone for this contact intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, ringtoneUri); // Launch! // startActivityForResult(intent, REQUEST_CODE_PICK_RINGTONE); startActivityForResult(intent, REQUEST_CODE_PICK_RINGTONE); } // 选择铃声之后作相应的处理 @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK) { return; } switch (requestCode) { case REQUEST_CODE_PICK_RINGTONE: { Uri pickedUri = data .getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); handleRingtonePicked(pickedUri); break; } } } private void handleRingtonePicked(Uri pickedUri) { if (pickedUri == null || RingtoneManager.isDefault(pickedUri)) { mRingtoneUri = null; } else { mRingtoneUri = pickedUri.toString(); } if (mRingtoneUri != null) { rintoneName.setText(RingtoneManager .getRingtone(this, pickedUri).getTitle(this)); rollingType=pickedUri.toString(); } else { rintoneName.setText("闹铃声"); } }
到这里设置闹钟的功能就完成了闹钟设置完成后 需要新建一个类继承broadcastreceiver 对闹铃进行提示
package com.samon.wq.app; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.httpclient.URI; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.RingtoneManager; import android.net.Uri; import android.util.Log; import android.widget.Toast; import com.samon.wq.DB.DBInfo; import com.samon.wq.DB.DbHelper; import com.samon.wq.bean.AttRemind; public class AppReceiver extends BroadcastReceiver { private DbHelper dbHelper; private List<AttRemind> reminds = new ArrayList<AttRemind>(); @SuppressWarnings("unchecked") @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if (intent.getAction().equals("com.samon.ALARM_REMINDACTION")) { Calendar calendar = Calendar.getInstance(); int nhours = calendar.get(Calendar.HOUR_OF_DAY); int nminute = calendar.get(Calendar.MINUTE); Log.d("onReceive-->", "onReceive"); getRemind(context); for (int i = 0; i < reminds.size(); i++) { String msg = reminds.get(i).getSeason(); int hours = reminds.get(i).getHours(); int minute = reminds.get(i).getMinute(); Log.d("hours-->", hours + ""); Log.d("minute-->", minute + ""); if (hours == nhours && minute == nminute) { Toast.makeText(context, msg + "", Toast.LENGTH_SHORT) .show(); playRing(context, reminds.get(i).getRollingType()); } } } } //播放系统铃声 private void playRing(Context context, String url) { Uri alert; if (url != null) { alert = Uri.parse(url); } else { alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); } MediaPlayer mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(context, alert); } catch (Exception e) { e.printStackTrace(); } final AudioManager audioManager = (AudioManager) context .getSystemService(Context.AUDIO_SERVICE); if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) { mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mMediaPlayer.setLooping(true); try { mMediaPlayer.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } mMediaPlayer.start(); } } // 把数据库查出的数据转换成List private void getRemind(Context context) { // TODO Auto-generated method stub dbHelper = new DbHelper(context); Cursor c = dbHelper.selectAll(); if (c != null) { reminds.clear(); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { AttRemind attRemind = new AttRemind(); attRemind.setRepeatDay(c.getString(c .getColumnIndex(DBInfo.FIELD_REPEAT_DATE))); String time = c.getString(c .getColumnIndex(DBInfo.FIELD_REMIND_TIME)); try { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); Date date = sdf.parse(time); attRemind.setHours(date.getHours()); attRemind.setMinute(date.getMinutes()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } attRemind.setSeason(c.getString(c .getColumnIndex(DBInfo.FIELD_REMIND_NAME))); attRemind.setRolling(Boolean.getBoolean(c.getString(c .getColumnIndex(DBInfo.FIELD_REMIND_TYPE)))); attRemind.setRollingType(c.getString(c .getColumnIndex(DBInfo.FIELD_ROLLING_TYPE))); attRemind.setId(c.getInt(c .getColumnIndex(DBInfo.FIELD_REMIND_ID))); reminds.add(attRemind); } } } // 停止轮询服务 public static void stopPollingService(Context context, Class<?> cls, String action) { AlarmManager manager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, cls); intent.setAction(action); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // 取消正在执行的服务 manager.cancel(pendingIntent); } }
在这里 我在接受到广播之后查数据库中的所有数据 然后遍历出所有数据 跟当前时间进行对比 如果相同就播放音乐,别忘了 在清单文件中注册一下你的广播<receiver android:name="com.samon.wq.app.AppReceiver" > <intent-filter> <action android:name="com.samon.ALARM_REMINDACTION" /> </intent-filter> </receiver>
就这样 闹钟应该就可以运行了 我这里可能有部分代码没有贴出来 ,但是基本思路有了 只是为了纪念一年前抓心挠肝的工作 现在几个小时就能做完了,所以写个博客鼓励下自己,希望自己未来继续加油!这个闹钟还有部分功能未实现 设置的重复日期没有进行判断,因为那个我自定义的spinner 不是很满意想重新写 所以就没对spinner进行操作。