【问题标题】:Activity keeps restarting when I leave the activity and come back to it当我离开活动并返回活动时,活动不断重新启动
【发布时间】:2018-03-05 12:47:04
【问题描述】:

我有两个活动,当我从活动 A 移动到 B 时,B 不断重启或“刷新”,当我从 B 回到 A 时,它也不断重启。代码很大,我在这里发布我认为问题原因的区域:

  Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                deviceStatus();

                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }

    });
    t.start();

这是 deviceStatus();

  public void deviceStatus(){
    try {
        RequestQueue requestQueue = Volley.newRequestQueue(InActivate.this);
        String URL = "http://gickuwait-dev.com/electionapi/api/DeviceStatus";
        JSONObject jsonBody = new JSONObject();

        jsonBody.put("device_PK", device_ID2);


        final String requestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {



                if(response.equals("true")){

                        Intent intent = new Intent(InActivate.this, Vote.class);
                        startActivity(intent);
                        finish();

                }else  if(response.equals("false")) {


                }
                // Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Log.e("VOLLEY", error.toString());
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return requestBody == null ? null : requestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                    return null;
                }
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {

                String responseString;
                String json = null;

                try {
                    json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                responseString = String.valueOf(json).trim();
                ArrayList<DeviceStatusResponse> list = new ArrayList<DeviceStatusResponse>();
                Type listType = new TypeToken<List<DeviceStatusResponse>>() {}.getType();
                list = new Gson().fromJson(responseString, listType);

                device_Status = list.get(0).getIsActive().toString();
                //  Toast.makeText(getApplicationContext(), ""+device_Status+" null ", Toast.LENGTH_LONG).show();
                return Response.success(device_Status, HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        requestQueue.add(stringRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

在活动 B 中,我有相同的代码来检查数据库中的设备状态,任何帮助将不胜感激

【问题讨论】:

  • 此代码不足以找出问题所在。只有一个新线程。 deviceStatus() 是做什么的?编辑您的问题。
  • 信息不足,请提供更多信息。
  • 我编辑了我的问题
  • t.start();您是否在 onPause 方法上向 API 发送请求? & 根据你的 Qus A-> InActivate B->投票活动?
  • B 是 InActivate,投票是 A,我使用线程每隔 1 刷新一次应用程序以检查设备是否被激活,但似乎 Activity 没有被刷新,它正在重新启动跨度>

标签: java android multithreading


【解决方案1】:

您可以使用 Handle 来检查重复的任务。

     private Handler delayHandler = new Handler();
    private Runnable runnable = new Runnable() {
            @Override
            public void run() {
deviceStatus();
      driverDelayHandler.postDelayed(runnable, 1000);

            }
        };

别忘了取消 onStop 方法。

 delayHandler.removeCallbacks(runnable);

【讨论】: