마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

알림설정부분 도와주세요...

0 추천

기능은 시간표 만들기에서 시간이랑 과목명을 다 입력하고 저장하고나서 저장한 것을 시간표 불러오기에서 불러오고 나서 과제추가랑 알람 설정을 다하고 저장합니다.

그리고 메인화면으로 갔는데 메인화면에서 알람이 울립니다.

그리고 앱을 종료하고 난 후 제가 설정한 시간에 알람이 울리지 않아서 어플을 실행해보니 그때 알람이 울리기 시작합니다.이거 어떻게 해야됩니까...?

한마디로 정리해드리면 과제등록한것을 알람 설정해놓으면 설정해놓은 시간에 울려야 되는데 제대로 울리지 않습니다.

package kr.co.timetable;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * 공유설정에서 알람시간을 가져와
 * 알람을 실행하고 알람시간이 되면 브로드캐스팅을 한다.
 */
public class AlarmService extends Service {
 private Calendar calendar = null; // 현재시간
 private AlarmManager am = null;   // 알람 서비스
 private Location mLocation;
 private PendingIntent sender;   // 알람 notification을 위한 팬딩인텐트

 /** 서비스가 실행될때  */
 @Override
 public int onStartCommand(final Intent intent, final int flags, final int startId) {
  // TODO Auto-generated method stub
  SharedPreferences defaultSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
  int beforeMin = Integer.valueOf(defaultSharedPref.getString("beforeAlarm", "10")); // minus

  calendar = getAlarmDate(beforeMin); // 알람시간이 설정된 calendar를 가져온다.

  if(calendar == null){ // 설정된 알람시간이 없으면 종료
   return 0;
  }

  //before.
  Log.i("hw",
    "알람시간 : " + calendar.get(Calendar.HOUR_OF_DAY) + ":" +
        calendar.get(Calendar.MINUTE));
  // 시스템서비스에서 알람매니져를 얻어온다.
  am = (AlarmManager)getSystemService(ALARM_SERVICE);
  // 브로드케스트 리시버에 보낼 팬딩인텐트, 이전 팬딩인텐트가 있으면 취소하고 새로 실행
  Intent i = new Intent(getBaseContext(), AlarmReceiver.class);
  sender = PendingIntent.getBroadcast(getBaseContext(),
    0,  i, PendingIntent.FLAG_CANCEL_CURRENT);
  am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender); // 알람설정
  Log.i("hw", "onstartCommand");
  return 0;
 }

 /**
  * DB에서 가장 현재시간과 가까운 알람시간을 가져온다.
  * @return
  */
 private Calendar getAlarmDate(final int beforeMin) {
  Calendar cal = Calendar.getInstance();
  // 단말기의 시간을 가져온다.
  cal.setTimeInMillis(System.currentTimeMillis());
  // 몇분전 알람시간 설정
  
  
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  String date = sdf.format(cal.getTime());
  Log.i("hw", "현재 시간--->" + date);
  Database dbhp = new Database(this);
  SQLiteDatabase db = dbhp.getReadableDatabase();
  Cursor cursor = null;
  // 현재시간보다 큰 알람 시간
  cursor = db.query("HomeWork", null,
    "time > ? and alarm = 1", new String[]{date, }, null, null, null);
  if(cursor.getCount() <= 0){ // 내역이 없으면 끝낸다.
   db.close();
   return null;
  }
  if( cursor.moveToFirst() ){ // 가장 최신 한개만 가져온다.
   date = cursor.getString(cursor.getColumnIndex("time"));
   date = date.substring(0, 16);
   Log.i("hw", "가져온 시간--->" + date);
  }
  // 불러낸 데이터로 calendar 셋팅
  try {
   cal.setTime(sdf.parse(date));
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  // 디비를 닫아준다.
  cursor.close();
  db.close();
  // 몇분전 알람시간 설정
  cal.add(Calendar.MINUTE, -(beforeMin) );
  Log.i("hw", "알람 시간--->" + sdf.format(cal.getTime()));
  return cal;
 }

 @Override
 public void onCreate() {
  // TODO Auto-generated method stub
  super.onCreate();
 }

 @Override
 public void onDestroy() {
  // TODO Auto-generated method stub
  Log.i("dservice", "stop!");
  stopSelf();
  if(am != null){ // 알람이 설정되어 있으면 취소
   am.cancel(sender);  // 알람 취소
  }
  super.onDestroy();
 }

 @Override
 public IBinder onBind(final Intent arg0) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public boolean onUnbind(final Intent intent) {
  // TODO Auto-generated method stub
  return super.onUnbind(intent);
 }
}

알람서비스를 만들어 놓긴했는데도 어플 종료후 다시 울리네요... 고쳐주시거나 어떤 부분 오류가 있는지 갈쳐주십시오...

고도칸 (120 포인트) 님이 2013년 10월 31일 질문
고도칸님이 2013년 10월 31일 수정

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...