2016-11-21 1 views
5

특정 날짜에 삭제해야하는 데이터베이스가 있는데 어떻게이 작업을 수행 할 수 있습니까? 나는 이것을 발견했다 :android에서 작업을 예약하는 방법

timer = new Timer(); 

timer.scheduleAtFixedRate(new TimerTask() { 

    synchronized public void run() { 

     \\ here your todo; 
     } 

    }}, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1)); 

그러나 나는 그것이 "만기일까지"작업을 "저장할지 확실하지 않다. 감사합니다

+0

[이 링크] (http://stackoverflow.com/a/8801990/3800164)의 대답은 앞으로 작업을 예약하는 데 도움이됩니다. –

+0

내 이해는 귀하의 앱이 종료되기 전에 _ 작업이 시작 되었으면 아니오, 실행되지 않는다는 것입니다. 응용 프로그램이 작업을 실행하는 동안 _ 종료하려고하면 OS가이를 차단할 수 있습니다. 아래 @jitesh의 답변이 당신이 찾고있는 것일 수 있습니다. –

답변

1

는 알람 관리기 클래스는 것을 반복 알람의 일정을 가능하게 alaram 관리자를 등록 앞으로 설정 지점에서 실행하십시오. AlarmManager에는 PendingIntent가 주어지며 알람이 예약 될 때마다 실행됩니다. 알람이 으로 트리거되면 등록 된 인 텐트는 안드로이드 시스템에 의해 브로드 캐스트되며 대상 애플리케이션이 아직 실행되지 않은 경우 시작됩니다.

BroadcastReceiver에서 상속하는 클래스를 만듭니다. BroadcastReceiver가 Intent 브로드 캐스트를 수신 할 때 호출되는 onReceive 메서드에서 우리는 우리 작업을 실행하는 코드를 설정합니다.

AlarmReceiver.java

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.widget.Toast; 

public class AlarmReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context arg0, Intent arg1) { 
     // For our recurring task, we'll just display a message 
     Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show(); 

    } 

} 

우리는 매니페스트 파일에 브로드 캐스트 리시버를 등록해야합니다. 매니페스트 파일에서 AlarmReceiver를 선언하십시오.

<application> 
    . 
    . 
    <receiver android:name=".AlarmReceiver"></receiver> 
    . 
    . 
</application> 

귀하의 전화 활동에는 다음 인스턴스 변수가 포함됩니다. 에서 onCreate에서

private PendingIntent pendingIntent; 
private AlarmManager manager; 

() 우리는 우리의 방송 수신 클래스를 참조하고 우리의 PendingIntent에서 그것을 사용하는 의도를 만듭니다.

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // Retrieve a PendingIntent that will perform a broadcast 
    Intent alarmIntent = new Intent(this, AlarmReceiver.class); 
    pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0); 
} 

그런 다음 되풀이 알람을 설정하는 방법이 포함됩니다. 일단 설정되면 매 X 시간마다 알람이 울리고 여기에 우리는 매일 10 초 동안 트리거하기 위해 이것을 계산할 수있는 10 초의 예제를 사용합니다.

public void startAlarm(View view) { 
    manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 
    int interval = 10000; 

    manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent); 
    Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show(); 
} 

다음으로 필요한 경우 cancelAlarm() 메서드를 설정하여 경보를 중지합니다.

public void cancelAlarm(View view) { 
    if (manager != null) { 
     manager.cancel(pendingIntent); 
     Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show(); 
    } 
} 
+0

안녕하세요, 나는 영역 데이터베이스를 사용하고 있습니다.하지만 '활동'인 컨텍스트를 전달해야합니다. 어떻게하면 이것을 onReceive로 전달할 수 있습니까? 덕분에 –

+0

그것은 작동하지 않습니다 ... "생성자 의도를 해결할 수 없습니다" 'Intent alarm = new Intent (this, AlarmReceiver.class); –

2

이렇게하려면 특정 시간이 지나면 호출 할 Alaram Manager를 사용해야합니다.

먼저 당신이이 alaram에게

public class DBActionReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 
     // perform delete operation here 
    } 

} 

둘째를 받게됩니다 방송 수신기를 선언 할 필요가 지금

AlarmManager alarms = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE); 

    DBActionReceiver receiver = new DBActionReceiver(); 
    IntentFilter filter = new IntentFilter("ALARM_ACTION"); 
    registerReceiver(receiver, filter); 

    Intent intent = new Intent("ALARM_ACTION"); 
    intent.putExtra("param", "My scheduled action"); 
    PendingIntent operation = PendingIntent.getBroadcast(this, 0, intent, 0); 
    // invoke broadcast after one minute of my app launch 
    alarms.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+(1000 * 60), operation) ; 
+0

위의 주어진 ans dosen't 당신을 위해 일하는 경우 알려 주시기 바랍니다 –

+0

내 대답을 받아 들일 수 있습니다. –

+0

너무 효과가 없습니다!'getSystemService'가 존재하지 않습니다 –

관련 문제