即使关闭应用程序,如何保持警报管理器运行?

时间:2019-02-03 14:13:02

标签: android alarmmanager intentservice

我想在MainActivity.java文件中使用一个AlarmManager,它会每分钟触发一次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();
                }
            }
       }

    }
}

在这里,我只是追加到文件中,只是为了检查服务是否在关闭应用程序后仍运行,并且没有运行。

这是我的接收者:     公共类MyAlarmReceiver扩展了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 :(得分:0)

使用AlarmManager非常不可靠,尤其是从Android M开始。电话打ze模式将忽略警报事件。我使用Firebase JobDispatcher https://github.com/firebase/firebase-jobdispatcher-android来达到此目的。码: 摇篮:

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);

这应该有效,至少对我有用。