【问题标题】:Updating status on server in onDestroy method在 onDestroy 方法中更新服务器上的状态
【发布时间】:2016-12-22 18:42:58
【问题描述】:

我想在用户直接关闭其应用时更新用户状态。

我试过了,但这不起作用:

public class ExitService extends IntentService {

private static String TAG = ExitService.class.getSimpleName();

public ExitService() {
    super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        String callNo = intent.getStringExtra("callNo");
        String status = intent.getStringExtra("status");
        updateExitStatus(callNo, status);
    }
}
public void updateExitStatus(final String callNo,final String status){
    StringRequest strReq1= new StringRequest(Request.Method.POST,
            Config.UTL_STATUS, new Response.Listener<String>(){
        public void onResponse(String response) {

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();

            params.put("callNo", callNo);
            params.put("status",status);

            Log.e(TAG, "Posting params: " + params.toString());
            return params;
        }

    };

    // Adding request to request queue
    MyApplication.getInstance().addToRequestQueue(strReq1);
}

}

我有 onResume 会将状态更新为“1”(在线取 1,离线取 0)

应用程序也应该在后台运行,因此 onStoponPause 从这个等式中排除。

【问题讨论】:

  • “不工作”是什么意思?onDestroy 方法没有被调用?事实上,你不能确保当用户关闭你的应用时 onDestroy 会被调用。
  • 顺便说一句,您似乎在主线程中进行网络请求,这是一个坏主意。只需使用新线程或 AsyncTask 之类的东西来进行网络请求。
  • @SamMao 我正在使用的 api 将状态保存在数据库中,所以如果我直接关闭我的应用程序,那么该状态根本不会改变,这就是我确保 destroy 方法中的代码不起作用的方式跨度>
  • @SamMao onDestroy 方法里面的 volley 怎么样?
  • 我不知道volley是否同步执行网络请求,请自己检查并确保网络工作在新线程中完成。并确保在用户关闭您的应用程序时调用您的更新状态代码。我已经测试,如果用户在最近的应用程序中滑动您的应用程序,您的 onDestroy 甚至 onStop 方法可能不会被调用。

标签: android


【解决方案1】:

试试这个对我有用...

 public class App_killed extends Service {

    @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() {
        super.onDestroy();
        Log.d("ClearFromRecentService", "Service Destroyed");
    }

    public void onTaskRemoved(Intent rootIntent) {
        Log.e("ClearFromRecentService", "END");
        //Code here call your network call using volley/Asynch task..
        App_close();
        Toast.makeText(getApplicationContext(), "Warning: App killed", Toast.LENGTH_LONG).show();
        //stopSelf();
    }

    private void App_close() {
        // Tag used to cancel the request

        String tag_string_req = "close_app";

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_CLOSE_APP, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d("close App", "Killed Response: " + response.toString());

                } catch (Exception e) {
                    // JSON error
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("close app", "Killed Error: " + error.getMessage());
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("status", status);
                params.put("mobile", callNo);
                return params;
            }

        };
        // Adding request to request queue
        VollyGlobal.getInstance().addToRequestQueue(strReq, tag_string_req);
    }
}

IN 清单

<service
        android:name=".App_killed"
        android:stopWithTask="false" />

现在在您的 MainActivity 中启动该服务;

startService(new Intent(getBaseContext(), App_killed.class));

现在在您的 VolleyGlobal 课程中:

    public class VollyGlobal extends Application {

    private static Context context;

    public static final String TAG = VollyGlobal.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static VollyGlobal mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        VollyGlobal.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return VollyGlobal.context;
    }

    public static synchronized VollyGlobal getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

    private Request<?> setDefaultRetryPolicy(Request<?> request) {
        request.setRetryPolicy(new DefaultRetryPolicy(0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        return request;
    }
}

【讨论】:

  • 查看我的代码 我已经在这样做了,但是您已经做了一些更改,请查看我的代码
  • 我正在调用该活动的 onDestroy 中的意图
  • 假设状态代替 otp 就是这样
  • public void onDestroy(){ flag=false; pulsator.stop(); callNo=userNo.getText().toString();状态=“0”;意图 msgIntent = new Intent(this, ExitService.class); msgIntent.putExtra("callNo",callNo); msgIntent.putExtra("状态",状态);启动服务(msgIntent); super.onDestroy(); }
  • 有什么我们知道应用程序已关闭.....整个应用程序不是一个活动?
【解决方案2】:

在 Intent Service 中调用 Server 并在 super.onDestory() 之前从 onDestroy 调用该服务。

@Override
    protected void onDestroy() {
        startService(new Intent(this, ServerUpdateIntentService.class));
        super.onDestroy();
    }

对于意向服务,请使用此链接:
https://code.tutsplus.com/tutorials/android-fundamentals-intentservice-basics--mobile-6183

【讨论】:

  • 更多关于如何实现intentService,你可以参考提供的链接。
  • 我试试这个我已经使用过这种类型的服务,但我试试看它是否有效
  • Sahil Munjal 我想我不需要步骤 4-7,因为我只是在服务器上发送和更新状态我跳过广播接收器方法可以吗?
  • 是的,只需实现Service并在Manifest中定义它并从onDestroy调用它。
  • 在清单中我必须这样做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多