이것저것/My_Work

android - AlaramManager & Service 실행

우담바라 2015. 3. 27. 14:46


[ AlaramManager & Service 실행 ]


부팅 후, 알람메니저를 실행하여, 주기적으로 알람을 발생하고, 


그때마다 service(서비스)를 호출하여, 필요에 따라 'NotificationManager' 로 알림메세지를 전송



먼저, 이전 게시물에서 재부팅 후, 자동으로 앱 실행하는 함수가져와서 수정

http://wabar.tistory.com/928 



1. AndroidManifest.xml 수정 ('RECEIVE_BOOT_COMPLETED'관련 권한 및 코드 추가)


2. 클래스 추가(기존 코드 수정)


ex) StartReceiver.java 

 

public class StartReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {


try {

setAlarm(context);                    //알람 설정코드

} catch (Exception e) {

e.printStackTrace();

}

}


public void setAlarm(Context context)throws Exception{


AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(context, TimeCheckService.class);

PendingIntent sender = PendingIntent.getService(context, 0, intent, 0);

        

      try

      {

// '2012-02-25 07:00:00'에  처음 시작해서, 일정(12)시간 마다 실행되게

java.util.Date tomorrow = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2012-02-25 07:00:00");            

am.setInexactRepeating(AlarmManager.RTC, tomorrow.getTime(), 12 * 60 * 60 * 1000, sender);


        } catch (ParseException e)

        {

            e.printStackTrace();

        }

}

}



3.  AndroidManifest.xml 수정


<service android:name=".TimeCheckService" android:enabled="true"  android:process=":remote" >



4. Alarm 을 받을 서비스 구현  ( TimeCheckService )



public class TimeCheckService extends Service {


public void onCreate() {

...

}


...


@Override

public int onStartCommand(Intent intent, int flags, int startId) {


Toast.makeText(this, "Service onStart", Toast.LENGTH_SHORT).show();


mHandler.sendEmptyMessage(0);                    //Handler 를 통한 메세지 송신


return  START_REDELIVER_INTENT ;

}

private Handler mHandler = new Handler() {

public void handleMessage(Message msg) {        


NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


// 알람 클릭시 MainActivity를 화면에 띄운다.

Intent intent = new Intent(getApplicationContext(), MainActivity.class);


intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK

| Intent.FLAG_ACTIVITY_CLEAR_TOP

| Intent.FLAG_ACTIVITY_SINGLE_TOP);


intent.putExtra("msg", msg);

NotificationCompat.Builder builder = new NotificationCompat.Builder( TimeCheckService.this );

builder.setSmallIcon(R.drawable.icon1).setContentTitle("알림 타이틀")

.setStyle(new NotificationCompat.BigTextStyle().bigText(strMSG))    //strMSG => 출력 메세지 

.setContentText(strMSG)

.setAutoCancel(true) // 알림바에서 자동 삭제

.setVibrate(new long[] { 100, 300, 100 });

// autoCancel : 한번 누르면 알림바에서 사라진다.

// vibrate : 쉬고, 울리고, 쉬고, 울리고... 밀리세컨

// 진동이 되려면 AndroidManifest.xml에 진동 권한을 줘야 한다.

PendingIntent pIntent = PendingIntent.getActivity( getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

builder.setContentIntent(pIntent);

manager.notify(1, builder.build());

};

};

}