簡體   English   中英

在后台調用 web 服務的最佳方式是什么?

[英]What is the best way to call a web service in background?

我有一個 Android 應用程序我需要每隔一分鍾在后台調用一次 web 服務,並且取決於 web 服務響應是否向用戶發送通知。 做這個的最好方式是什么? 請注意目標 SDK 是 26

在 android 中使用作業調度程序

這將有助於按時間間隔安排工作

https://developer.android.com/reference/android/app/job/JobScheduler

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>

創建以下實用程序 class。

 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM