是否可以在onTaskRemoved中执行网络任务?

时间:2018-08-13 04:17:07

标签: android android-service

我需要在我的应用程序完全关闭(从backgrond清除)后将请求发布到服务器,并且当响应服务停止工作时,这是我的Service类:

public class OnClearFromRecentService extends Service {

    private SharedPreferences prefs;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ClearFromRecentService", "Service Started");

        return START_STICKY;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        Log.d("ClearFromRecentService", "Service Destroyed");

    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {

        Log.e("ClearFromRecentService", "END");

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(App.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface requestInterface = retrofit.create(RequestInterface.class);

        String authorization = prefs.getString("token_type","")+" "+prefs.getString("access_token","");

        Call<JsonArray> response = requestInterface.AppOff(ChatList.offline_user,authorization);

        response.enqueue(new Callback<JsonArray>() {
            @Override
            public void onResponse(Call<JsonArray> call, retrofit2.Response<JsonArray> response) {

                String asd = "asd";



                stopSelf();
            }

            @Override
            public void onFailure(Call<JsonArray> call, Throwable t) {

                Log.d(t.getLocalizedMessage(),"failed");

                stopSelf();

            }
        });


    }

清单中的定义:

 <service android:name="com.iranMobleh.OnClearFromRecentService" android:stopWithTask="false" />

并从MainActivity启动服务,如下所示:

 startService(new Intent(this, OnClearFromRecentService.class));

看起来这段代码是正确的,但是问题是当应用关闭时,它不能等待改造响应

3 个答案:

答案 0 :(得分:0)

使用WorkManager在后台运行工作程序类。

或者使用Evernote的android-job。

evernote android-job库的链接:https://github.com/evernote/android-job

答案 1 :(得分:0)

您可以尝试在服务类中尝试使用onDestroy方法,因为如果应用程序被强制关闭,则有时不要求使用onTaskRemoved方法,因此我建议在服务等级,以及

您可以使用Intent Service实现您的目标,并在onDestroy中使用该服务

您可以看以下示例。

http://stacktips.com/tutorials/android/creating-a-background-service-in-android

答案 2 :(得分:0)

首先,如果您设置 [HttpGet] [Route("myapplication")] [AllowAnonymous] private System.Net.Http.HttpResponseMessage GeneratePDF(string guid, bool isAr, out string fileName) { string htmlString = ApplicationService.GeneratePDFHTMLString(guid, isAr, out fileName); string pdf_page_size = "A4"; PdfPageSize pageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pdf_page_size, true); string pdf_orientation = "Portrait"; PdfPageOrientation pdfOrientation = (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation), pdf_orientation, true); int webPageWidth = 748; int webPageHeight = 0; // instantiate a html to pdf converter object HtmlToPdf converter = new HtmlToPdf(); // set converter options converter.Options.PdfPageSize = pageSize; converter.Options.PdfPageOrientation = pdfOrientation; converter.Options.WebPageWidth = webPageWidth; converter.Options.MarginTop = 20; converter.Options.WebPageHeight = webPageHeight; converter.Options.ExternalLinksEnabled = true; converter.Options.EmbedFonts = true; converter.Options.KeepTextsTogether = true; try { // create a new pdf document converting an url PdfDocument doc = converter.ConvertHtmlString(htmlString); doc.CompressionLevel = PdfCompressionLevel.NoCompression; //var contents = doc.Save(); //doc.Close(); //return contents; MemoryStream pdfStream = new MemoryStream(); // save pdf document into a MemoryStream doc.Save(pdfStream); // reset stream position pdfStream.Position = 0; System.Net.Http.HttpResponseMessage response = new System.Net.Http.HttpResponseMessage(); response.StatusCode = System.Net.HttpStatusCode.OK; //response.Content = new System.Net.Http.StreamContent(pdfStream); response.Content = new System.Net.Http.ByteArrayContent(pdfStream.ToArray()); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "foo.pdf" }; response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); doc.Close(); return response; } catch (Exception ex) { throw ex; } } ,则不会调用android:stopWithTask="false"。因此,将其设置为onTaskRemoved。参见 Service Documentation

现在我们转到解决方案。您必须将网络服务呼叫放入新的服务/工作中。并在调用android:stopWithTask="true"时通过AlarmManagerWorkManagerEvernoteJobsJobScheduler启动该服务/工作。

不要再写同样的东西。我发现两个很好的答案非常适合您的要求。 This This

以上答案中只有一个更改。我认为EvernoteJobs或WorkManager会比AlarmManager更好。

易于实现。

onTaskRemoved

访问 Evernote-jobs 页面进行集成。

更新

您必须使您的项目与库兼容。这是库使用的版本。因此,请确保您至少使用这些版本。

public class DemoSyncJob extends Job {

    public static final String TAG = "job_demo_tag";

    @Override
    @NonNull
    protected Result onRunJob(Params params) {
        // run api call here
        return Result.SUCCESS;
    }

   public static void runJobImmediately() {
    int jobId = new JobRequest.Builder(DemoSyncJob.TAG)
            .startNow()
            .build()
            .schedule();
    }
}