首页 > 解决方案 > 在后台调用 Web 服务的最佳方式是什么?

问题描述

我有一个 Android 应用程序,我需要每隔一分钟在后台调用一次 Web 服务,如果有票为他打开,则根据 Web 服务响应向用户发送通知。做这个的最好方式是什么?请注意目标 SDK 是 26

标签: androidbackgroundalarmmanagerscheduling

解决方案


The new JobService must be registered in the Android manifest with the BIND_JOB_SERVICE 
permission.

 <service
        android:name=".TestJobService"
        android:label="Word service"
        android:permission="android.permission.BIND_JOB_SERVICE" >

 </service>

创建以下实用程序类。

 public class Util {

// schedule the start of the service every 10 - 30 seconds
public static void scheduleJob(Context context) {
     ComponentName serviceComponent = new ComponentName(context, 
 TestJobService.class);
    JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
    builder.setMinimumLatency(1 * 1000); // wait at least
    builder.setOverrideDeadline(3 * 1000); // maximum delay
    //builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); // require unmetered network
    //builder.setRequiresDeviceIdle(true); // device should be idle
    //builder.setRequiresCharging(false); // we don't care if the device is charging or not
    JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
    jobScheduler.schedule(builder.build());
}

} 

创建以下接收器

public class MyStartServiceReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Util.scheduleJob(context);
}
}

在 Android 清单中为 BOOT_COMPLETED 事件注册接收器。

<receiver android:name="MyStartServiceReceiver" >
<intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>

创造你的工作

  /**
  * JobService to be scheduled by the JobScheduler.
  * start another service
  */
public class TestJobService extends JobService {
private static final String TAG = "SyncService";

@Override
public boolean onStartJob(JobParameters params) {
    Intent service = new Intent(getApplicationContext(), LocalWordService.class);
    getApplicationContext().startService(service);
    Util.scheduleJob(getApplicationContext()); // reschedule the job
    return true;
}

@Override
public boolean onStopJob(JobParameters params) {
    return true;
}

}

参考这个链接

https://www.vogella.com/tutorials/AndroidTaskScheduling/article.html


推荐阅读