Как сохранить Alarm Manager запущенным даже после закрытия приложения? - PullRequest
0 голосов
/ 03 февраля 2019

Мне нужен AlarmManager в моем файле MainActivity.java, который будет запускать IntentService каждую минуту.

Код, который я написал:

public void scheduleAlarm() {
    Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);
    final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    long firstMillis = System.currentTimeMillis();
    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 60000, pendingIntent);
}

Это мой IntentService:

public class MyTestService extends IntentService {

    public MyTestService() {
        super("MyTestService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("tag_tag_tag", "Service running");

        String filename = "example.txt";
        String fileContents = "\ndone ";
        FileOutputStream fos = null;

    try {
            fos = openFileOutput(filename, MODE_APPEND);
            fos.write(fileContents.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
       }

    }
}

Здесь я просто добавляю файл, чтобы проверить, работает ли служба даже после закрытия приложения, а это не так.

Это мой Receiver: открытый класс MyAlarmReceiver extends BroadcastReceiver{

    public static final int REQEST_CODE = 12345;
    public static final String ACTION = "com.always_in_beta.bekar";

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MyTestService.class);
        i.putExtra("foo", "bar");
        context.startService(i);
    }
}

Я хочу, чтобы эта служба запускалась каждую минуту в фоновом режиме даже после закрытия приложения.

1 Ответ

0 голосов
/ 03 февраля 2019

Использование AlarmManager очень ненадежно, особенно с Android M и выше.Тревожные события игнорируются в режиме ожидания телефона.Я использую Firebase JobDispatcher https://github.com/firebase/firebase-jobdispatcher-android, который отлично подходит для этих целей.Код: Gradle:

implementation 'com.firebase:firebase-jobdispatcher:0.8.5'

Класс работы:

import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;

public class MyTestService extends JobService {
@Override
public boolean onStartJob(JobParameters job) {
    // something like
 Log.d("tag_tag_tag", "Service running");

    String filename = "example.txt";
    String fileContents = "\ndone ";
    FileOutputStream fos = null;

try {
        fos = openFileOutput(filename, MODE_APPEND);
        fos.write(fileContents.getBytes());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
   }

    return false; // Answers the question: "Is there still work going on?"
}

@Override
public boolean onStopJob(JobParameters job) {
    return false; // Answers the question: "Should this job be retried?"
}

}

Манифест:

<service
android:exported="false"
android:name=".MyTestService">
<intent-filter>
    <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
</intent-filter>

Вваша деятельность, создайте диспетчера:

// Create a new dispatcher using the Google Play driver.
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));

затем запланируйте работу:

Job myJob = dispatcher.newJobBuilder()
.setService(MyTestService.class) // the JobService that will be called
.setTag("my-unique-tag")        // uniquely identifies the job
.setRecurring(true)
.setTrigger(Trigger.executionWindow(1*60-10,1*60+10))//1 minute +/- 10 seconds
.build();

dispatcher.mustSchedule(myJob);

Это должно работать, по крайней мере, у меня работает.

...