代码之家  ›  专栏  ›  技术社区  ›  Cagri Yalcin

终止应用程序时使用Asynctask

  •  1
  • Cagri Yalcin  · 技术社区  · 7 年前

    我需要使用 AsyncTask 当我的应用程序被刷卡杀死时,这叫做“注销”。我用过 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));
    

    有没有办法解决这个问题?谢谢

    编辑: 我改变了我的 异步任务 密码我在所有的线后面放了一些圆木。当我看到我的日志时,“test1”、“test2”、“test3”、“test4”显示,但“test5”和其他显示不出来。

    2 回复  |  直到 7 年前
        1
  •  2
  •   goodev    7 年前

    编辑: 我今天用手机测试,并在其他过程中使用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();
        }
    }
    

    注销服务。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中,不要选择“仅显示所选应用程序”过滤器,您应该使用no filter和filter by tag“MyService | LogoutService”。


    为什么不使用 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);
        }
    }
    
        2
  •  0
  •   Chetan Kumar Patel    7 年前
    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();
                }
            }
        }
        }
    

    试试这个