2016-09-24 4 views
3

앱이 완전히 닫히면 프로그래밍 방식으로 알림을 보내는 방법은 무엇입니까?앱 폐쇄시 알림 보내기

예 : 사용자가 Android Taskmanager에서도 응용 프로그램을 종료하고 기다립니다. 앱은 X 초 후 또는 앱이 업데이트를 확인할 때 알림을 보내야합니다.

나는이 코드 예제와 함께 작동하도록 시도했지만 :

당신은, 예를 들어 그것을 설명하려고 할 수 있다면, 때문에 (나 같은) 초보자 이런 식으로 쉽게 배울 수 있습니다.

답변

1

이 서비스를 사용하려면 활동 라이프 사이클에서 onStop() 서비스를 시작하기 만하면됩니다. 이 코드 : startService(new Intent(this, NotificationService.class)); 는 당신은 새로운 자바 클래스를 생성 할 수 있으며이 코드를 붙여 : 당신은 단지 manifest.xml과 서비스를 결합해야 이후

public class NotificationService extends Service{ 

Timer timer; 
TimerTask timerTask; 
String TAG = "Timers"; 
int Your_X_SECS = 5; 


@Override 
public IBinder onBind(Intent arg0) 
{ 
    return null; 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId){ 
    Log.e(TAG, "onStartCommand"); 
    super.onStartCommand(intent, flags, startId); 

    startTimer(); 

    return START_STICKY; 
} 


@Override 
public void onCreate(){ 
    Log.e(TAG, "onCreate"); 


} 

@Override 
public void onDestroy(){ 
    Log.e(TAG, "onDestroy"); 
    stoptimertask(); 
    super.onDestroy(); 


} 

//we are going to use a handler to be able to run in our TimerTask 
final Handler handler = new Handler(); 


public void startTimer() { 
    //set a new Timer 
    timer = new Timer(); 

    //initialize the TimerTask's job 
    initializeTimerTask(); 

    //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms 
    timer.schedule(timerTask, 5000, Your_X_SECS*1000); // 
    //timer.schedule(timerTask, 5000,1000); // 
} 

public void stoptimertask() { 
    //stop the timer, if it's not already null 
    if (timer != null) { 
     timer.cancel(); 
     timer = null; 
    } 
} 

public void initializeTimerTask() { 

    timerTask = new TimerTask() { 
     public void run() { 

      //use a handler to run a toast that shows the current timestamp 
      handler.post(new Runnable() { 
       public void run() { 

        //TODO CALL NOTIFICATION FUNC 
        YOURNOTIFICATIONFUNCTION(); 

       } 
      }); 
     } 
    }; 
} 

}

을 :

<service 
      android:name=".NotificationService" 
      android:label="@string/app_name" 
      <intent-filter> 
       <action android:name="your.app.domain.NotificationService" /> 

       <category android:name="android.intent.category.DEFAULT" /> 
      </intent-filter> 
     </service> 
+0

고마워요! 내 애플 리케이션에 대한 귀하의 코드를 테스트하고 그것은 작동합니다! – Excel1

+0

[이 기사에 따르면 (https://guides.codepath.com/android/Repeating-Periodic-Tasks), "TimerTask - UIThread에서 실행되지 않고 신뢰할 수 없습니다. [TimerTask]를 사용하지 않는 것이 좋습니다 (http://www.mopri.de/2010/timertask-bad-do-it-the-android-way-use-a-handler/). " Nikhil Gupta의 대답이 더 좋습니다. – NargothBond

2

알람 관리자를 사용하여이를 수행 할 수 있습니다. 다음 단계를 따르십시오 :

1) alarmmanager를 사용하여 X 초 후에 알람을 생성하십시오.

Intent intent = new Intent(this, AlarmReceiver.class); 
intent.putExtra("NotificationText", "some text"); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, ledgerId, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); 
alarmManager.set(AlarmManager.RTC_WAKEUP, 'X seconds in milliseconds', pendingIntent); 

2) 앱에서 AlarmBroadCast 수신기를 사용하십시오. 매니페스트 파일에서

선언 :

<receiver android:name=".utils.AlarmReceiver"> 
    <intent-filter> 
     <action android:name="android.media.action.DISPLAY_NOTIFICATION" /> 

     <category android:name="android.intent.category.DEFAULT" /> 
    </intent-filter> 
</receiver> 

3) 방송 수신기의에에서 당신이 알림을 만들 수 있습니다받을 수 있습니다.

public class AlarmReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // create notification here 
    } 
} 
+0

답변 해 주셔서 감사합니다. 나는 당신의 코드로 그것을 시도하고 이미 작동합니다. @Vaibhav Kadam의 코드를 사용하기로 결정한 이유는 내 개인적 용도가 더 매력적 이었기 때문입니다. – Excel1

+0

이것이 더 바람직한 접근 방법 인 것 같습니다. https://guides.codepath.com/android/Starting-Background-Services#using-with-alarmmanager-for-periodic-tasks는보다 자세한 설명을 제공합니다. – NargothBond

0

서비스가 작동중인 앱을 확인하고 활동이 실행 중이 아닌 경우 알림을 표시 할 수 있습니다.