在应用程序被杀死时使用Asynctask

时间:2018-03-06 10:54:13

标签: android service android-asynctask

我需要使用AsyncTask来调用" Logout"当我的应用程序被刷卡杀死。我使用Service来处理此事件,但它无法正常工作。

AndroidManifest.xml

中添加了服务代码
    <service
        android:name=".MyService"
        android:stopWithTask="false" />

我的服务代码

public class MyService extends Service {

    PostClass post = new PostClass();

    @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();
        new Logout().execute();
        Log.d("ClearFromRecentService", "Service Destroyed");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.e("ClearFromRecentService", "END");
        new Logout().execute();
        stopSelf();
    }

    private class Logout extends AsyncTask<Void, Void, Void> {
        JSONObject j;
        ProgressDialog pDialog;
        JSONObject jso;
        String veri_string = "";

    protected void onPreExecute() {
        Log.e("MyService", "onPreExecute()");
    }

    protected Void doInBackground(Void... unused) {
        Log.e("MyService", "doInBackground()");
        return null;
    }

    protected void onPostExecute(Void unused) {
        Log.e("MyService", "onPostExecute()");
    }
    }
    }

我在第一次活动中开始使用此服务。

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

有什么方法可以解决这个问题吗?感谢..

修改:我更改了我的AsyncTask代码。我把一些日志放在所有行之后。当我看到我的Logcat时,&#34; test1&#34;,&#34; test2&#34;,&#34; test3&#34;,&#34; test4&#34;正在展示但是&#34; test5&#34;而其他人则没有。

2 个答案:

答案 0 :(得分:1)

编辑: 我今天用我的手机测试,并在其他过程中使用IntentService正在运行:

    <service
        android:name=".LogoutService"
        android:process=":LogoutProcess"/>
    <!-- LogoutService use a different process, So when MyService is destroyed can
         start LogoutService -->
    <service
        android:name=".MyService"
        android:enabled="true"
        android:exported="false"
        android:stopWithTask="false"/>

这两个服务代码:

public class MyService extends Service {
    public static final String TAG = "MyService";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate() called");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand() called with: intent = [" + intent + "], flags = [" + flags + "], startId = [" + startId + "]");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Log.e(TAG, "onTaskRemoved() called with: rootIntent = [" + rootIntent + "]");
        Intent logoutService = new Intent(this, LogoutService.class);
        startService(logoutService);
        this.stopSelf();
    }
}

LogoutService.java代码

public class LogoutService extends IntentService {
    public static final String TAG = "LogoutService";
    public LogoutService() {
        super(TAG);
        Log.e(TAG, "LogoutService() called");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.e(TAG, "onHandleIntent() called with: intent = [" + intent + "]");
        // This is in the background thread, just call your logout logic:
        try {
            Log.e(TAG, "onHandleIntent: " );
            HttpURLConnection connection = (HttpURLConnection) new URL("https://www.google.com").openConnection();
            String result = readInputStreamToString(connection);
            Log.e(TAG, "onHandleIntent() result = [" + result + "]");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "onHandleIntent: 111e" );
        }
        Log.e(TAG, "onHandleIntent: 111a" );
    }
}

和logcat:

03-07 10:04:05.969 8146-8146/org.goodev E/MyService: onCreate() called
03-07 10:04:05.969 8146-8146/org.goodev E/MyService: onStartCommand() called with: intent = [Intent { cmp=org.goodev/com.google.samples.gridtopager.MyService }], flags = [0], startId = [1]
03-07 10:04:10.940 8146-8146/org.goodev E/MyService: onTaskRemoved() called with: rootIntent = [Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=org.goodev/com.google.samples.gridtopager.MainActivity }]
03-07 10:04:10.952 1126-1848/? I/ActivityManager: Start proc 8287:org.goodev:LogoutProcess/u0a248 for service org.goodev/com.google.samples.gridtopager.LogoutService
03-07 10:04:11.016 8287-8287/? E/LogoutService: LogoutService() called
03-07 10:04:11.018 8287-8302/? E/LogoutService: onHandleIntent() called with: intent = [Intent { cmp=org.goodev/com.google.samples.gridtopager.LogoutService }]
03-07 10:04:11.018 8287-8302/? E/LogoutService: onHandleIntent: 
03-07 10:04:12.154 8287-8302/org.goodev:LogoutProcess E/LogoutService: onHandleIntent() result = [<!doctype html><html lang="zh-HK"><head><meta content="width=device-width,minimum-scale=1.0" name="viewport"><meta content="telephone=no" name="format-detection"><meta content="address=no" name="format-detection">...orstr=#3f76d3,GradientType=0)}.gb_8a{display:none!import
03-07 10:04:12.154 8287-8302/org.goodev:LogoutProcess E/LogoutService: onHandleIntent: 111a

警告:因为LogoutService正在其他进程中运行。所以在你的logcat中不要选择&#34;只显示选定的应用程序&#34;过滤器,您应该不使用过滤器并按标签过滤&#34; MyService | LogoutService&#34;。

为什么不使用IntentService

  @Override
  protected void onDestroy() {
    // On your main activity's onDestroy method
    Intent logoutService = new Intent(this, LogoutService.class);
    startService(logoutService);
    super.onDestroy();
  }

public class LogoutService extends IntentService {
    public LogoutService() {
        super("LogoutService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        // This is in the background thread, just call your logout logic:
        List<NameValuePair> params = new ArrayList<>();
        try {
            veri_string = post.httpPost(cikisURL, "POST", params, 10000);
            jso = new JSONObject(veri_string);
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        Log.e("Response: ", veri_string);
    }
}

答案 1 :(得分:-1)

public class MyService extends Service {

    PostClass post = new PostClass();

    @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_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        new Logout().execute();
        Log.d("ClearFromRecentService", "Service Destroyed");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.e("ClearFromRecentService", "END");
        new Logout().execute();
        stopSelf();
    }

    private class Logout extends AsyncTask<Void, Void, Void> {
        JSONObject j;
        ProgressDialog pDialog;
        JSONObject jso;
        String veri_string = "";

        protected void onPreExecute() {
        }

        protected Void doInBackground(Void... unused) {
            List<NameValuePair> params = new ArrayList<>();
            try {
                veri_string = post.httpPost(cikisURL, "POST", params, 10000);
                jso = new JSONObject(veri_string);
            }
            catch (JSONException e){
                e.printStackTrace();
            }
            Log.e("Response: ", veri_string);

            return null;
        }

        protected void onPostExecute(Void unused) {
            try {
                if(jso.has("data")) {

                }
                else {

                }
                pDialog.dismiss();
            }
            super.onDestroy();
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    }

试试这个