2017-05-03 1 views
0

로컬 알림을 사용하여 Android 애플리케이션을 개발 중입니다. 서비스를 사용하여 로컬 알림을 구현했습니다. 서비스 지역 알림은 작동하지만 앱을 종료하면 서비스가 파괴됩니다. 알림이 작동하지 않습니다. 이제 알람 관리자를 사용하여 로컬 알림을 구현하고 싶습니다. 어떻게 알람 관리자로이 작업을 수행 할 수 있습니까?Alarm Manager를 사용하여 로컬 알림 예약 android

여기는 서비스 클래스입니다. startForeground()의 문서에서

import android.app.AlarmManager; 
import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Binder; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.IBinder; 
import android.os.SystemClock; 
import android.support.annotation.Nullable; 
import android.support.v4.app.NotificationCompat; 
import android.util.Log; 
import android.widget.Toast; 

import com.deemsysinc.cyberhealthapp.R; 
import com.deemsysinc.cyberhealthapp.weightgoal.WeightGoalActivity; 
import com.google.gson.Gson; 

import java.text.DateFormat; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.HashSet; 
import java.util.Set; 
import java.util.StringTokenizer; 
import java.util.TimeZone; 
import java.util.Timer; 
import java.util.TimerTask; 

public class NotificationService extends Service{ 
    private IBinder iBinder=new MyBinder(); 
    SharedPreferences prefs; 
    SharedPreferences.Editor editor; 
    Handler handler; 
    // timer handling 
    NotificationManager manager; 
    Notification myNotication; 
    static TimerTask timerTask; 

    Date date1; 
    Date date2; 
    ArrayList<NotificationList> notificationLists; 

    int temp=0; 


    @Override 
    public void onRebind(Intent intent) { 
     super.onRebind(intent); 
    } 

    @Override 
    public boolean onUnbind(Intent intent) { 
     return true; 
    } 

    @Nullable 
    @Override 
    public IBinder onBind(Intent intent) { 
     return iBinder; 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     handler=new Handler(); 
     prefs = getSharedPreferences(configuration.AppPrefernce, MODE_PRIVATE); 
     editor = prefs.edit(); 
     notificationLists=new ArrayList<NotificationList>(); 


    } 


    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     timerStart(); 
     //Remove(); 
     return Service.START_STICKY; 
    } 

    public void showNotifications() 
    { 

     Calendar cal = Calendar.getInstance(); 
     Date currentLocalTime = cal.getTime(); 
     DateFormat date = new SimpleDateFormat("hh:mm a"); 
     String localTime = date.format(currentLocalTime); 
     String converted = localTime.replace("am", "AM").replace("pm", "PM"); 
     Toast.makeText(getApplicationContext(),"Timer Running",Toast.LENGTH_LONG).show(); 
     Log.d("Locals",""+local); 
     //Toast.makeText(getApplicationContext(),"Service Checked",Toast.LENGTH_SHORT).show(); 
     if(!prefs.getString("weight_hr","").equals("")) { 
      if (prefs.getString("weight_hr", "").equals(converted)) { 
       temp++; 
       Bundle bundle=new Bundle(); 
       //SimpleDateFormat writeformat = new SimpleDateFormat("dd/MM/yyyy"); 
       //String formattedDate = writeformat.format(calendar.getTime()); 
       if(temp==1) { 
        notificationLists.add(new NotificationList("Weight", "It's time to log your weight today. Click to update weight!", "")); 
        Gson gson = new Gson(); 
        String json = gson.toJson(notificationLists); 
        editor.putString("notificationlist", json); 
        editor.commit(); 
        bundle.putString("fromNotificationCenter","1"); 
       } 
       else 
       { 
        bundle.putString("fromNotificationCenter","0"); 
       } 
       manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
       Intent notificationIntent = new Intent(getApplicationContext(), WeightGoalActivity.class); 
       notificationIntent.putExtras(bundle); 
       PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 6, notificationIntent, 0); 
       NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); 
       builder.setAutoCancel(true); 
       builder.setContentTitle("Cyberhealths"); 
       builder.setContentText("It's time to log your weight today. Click to update weight!"); 
       builder.setSmallIcon(R.drawable.my_icon); 
       builder.setContentIntent(pendingIntent); 
       builder.setOngoing(false); 
       manager.notify(6, builder.build()); 

      } 
     } 











    } 





    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     timer.cancel(); 
     manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
     manager.cancel(6); 
     Toast.makeText(getApplicationContext(),"Service Destroyed",Toast.LENGTH_LONG).show(); 

    } 
    private void timerStart() { 
     timer = new Timer(); 
     timerTask = new TimerTask() { 
      @Override 
      public void run() { 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         try { 
          showNotifications(); 
         } catch (Exception e) { 

         } 

        } 
       }); 
      } 
     }; 
     timer.scheduleAtFixedRate(timerTask, 0, 65000); 

    } 


    @Override 
    public void onTaskRemoved(Intent rootIntent) { 
     super.onTaskRemoved(rootIntent); 
     Intent restartService = new Intent(getApplicationContext(), 
       this.getClass()); 
     restartService.setPackage(getPackageName()); 
     PendingIntent restartServicePI = PendingIntent.getService(
       getApplicationContext(), 1, restartService, 
       PendingIntent.FLAG_ONE_SHOT); 
     AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
     alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI); 

    } 

    private void runOnUiThread(Runnable runnable) { 
     handler.post(runnable); 
    } 
    public class MyBinder extends Binder { 
     public NotificationService getService() { 
      return NotificationService.this; 
     } 
    } 







} 
+0

서비스 중 '서비스 .START_STICKY'에 대해 언급 했습니까? 몇 가지 코드가 필요합니다. –

+0

좋아, 내 코드 – Hari

답변

0

:

가 진행 통지를 공급 전경이 서비스 실행 확인이 상태에있는 동안 사용자에게 표시합니다. 기본적으로 서비스는 배경이므로 웹에서 큰 페이지를 표시하는 등 더 많은 메모리를 회수하기 위해 시스템을 종료해야하는 경우 너무 많은 피해없이 살해 당할 수 있습니다. 서비스가 백그라운드 음악 재생을 수행하는 경우 과 같이 서비스를 중단하면 사용자가 방해를받을 수 있으므로 플래그를 설정할 수 있으므로 사용자 은 음악 재생이 중지 된 것을 알게됩니다. 서비스를 중지 할 필요가되면, 단순히 당신이 알림에 따라 전경에 서비스를 시작하셔야합니다 showNotification() 방법에서

,

int FOREGROUND_ID = 6; 
.... 
builder.setOngoing(false); 
Notification notification = builder.build(); 
manager.notify(FOREGROUND_ID, notification); 
startForeground(FOREGROUND_ID, notification); 

전화 :

stopForeground(**false/true**); 

패스 false 만약 당신이 돈 서비스가 중지되면 알림을 제거하고 싶지 않거나 알림을 자동으로 제거해야하는 경우 true을 원하십시오.

+0

을 게시 할 것입니다. 활동 클래스에서 다음과 같은 서비스를 시작했습니다. Intent intent = new Intent (SplashActivity.this, NotificationService.class); startService (의도); 이제 어떻게 서비스를 시작할 수 있습니까? – Hari

+0

@Hari No. 당신은 단지'showNotification()'메소드에서 그 변경을 할 필요가 있습니다. –

+0

ok 여기서 i stopForeground (** false/true **); 방법? – Hari

관련 문제