Android - 当 Activity 设置为 Single Top 时无法检索 Intent

Android - unable to retrieve Intent when Activity is set to Single Top

我正在开发具有以下场景的应用程序:

Activity A -> Activity B -> Activity C -> Activity A

我通过 Intent 在每个 Activity 之间传递我的值,它有效,但是当我回到 Activity A 时,似乎所有值都被清除了。

来自 Activity C 的代码:

Intent client = new Intent(getApplicationContext(), ActivityA.class);
            client.putExtra("TOKEN_VALUE", TOKEN_VALUE);
            client.putExtra("PARAMS", params); // Hashmap with {"id":"value"}
            client.putExtra("PICLIST", picArray);
            client.putExtra("TESTLIST", testArray);
            client.putExtra("TESTDATA", myData);
            client.putExtra("TESTTEMP", myTemp);
            client.putExtra("COMPTEUR", compteur);
            client.putExtra("LAUNCH",first_launch);
            client.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(client);

当我尝试获取这些值时,它们都是 null

编辑:

这是 onCreate()onNewIntent() 的代码:

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    // init the gps to get a location
    locationListener = new MyLocationListener();
    locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);


    // Checking if Wifi is enabled
    final WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    if (isSharingWiFi(wifi)) {
        new AlertDialog.Builder(this)
                .setCancelable(false)
                .setMessage("L' application requiert une connexion à Internet")
                .setPositiveButton("Accéder aux paramètres wifi ", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    }

                })
                .setNegativeButton("Accéder aux paramètres du réseau mobile", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show().getWindow().setLayout(1000, 600);
    }

    mId = (EditText) findViewById(R.id.exam_valve);
    mName = (EditText) findViewById(R.id.exam_op);
    b1 = (Button) findViewById(R.id.take_picture);
    b2 = (Button) findViewById(R.id.add_exam_button);
    b3 = (Button) findViewById(R.id.addTest_button);
    b1.setOnClickListener(clickListenerBoutons);

    // Init and fill the two spinners
    condition_status = (Spinner) findViewById(R.id.spinner_valve_condition);
    reason_status = (Spinner) findViewById(R.id.spinner_exam_reason);

    ArrayAdapter<String> valve_condition_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item) {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return super.getView(position, convertView, parent);
        }
    };

    valve_condition_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    valve_condition_adapter.add(getResources().getString(R.string.ok));
    conditionArray[0] = "ok";
    valve_condition_adapter.add(getResources().getString(R.string.rusty));
    conditionArray[1] = "rusty";
    valve_condition_adapter.add(getResources().getString(R.string.damaged));
    conditionArray[2] = "damaged";
    valve_condition_adapter.add(getResources().getString(R.string.broken));
    conditionArray[3] = "broken";
    condition_status.setAdapter(valve_condition_adapter);


    ArrayAdapter<String> exam_reason_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item) {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return super.getView(position, convertView, parent);
        }
    };

    exam_reason_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    exam_reason_adapter.add(getResources().getString(R.string.programmed));
    reasonArray[0] = "programmed";
    exam_reason_adapter.add(getResources().getString(R.string.valve_installation));
    reasonArray[1] = "valve-installation";
    exam_reason_adapter.add(getResources().getString(R.string.improvised));
    reasonArray[2] = "improvised";
    reason_status.setAdapter(exam_reason_adapter);


    condition_status.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            condition = conditionArray[position];
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    reason_status.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            reason = reasonArray[position];
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    // Init the request queue
    mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    mRequestQueue.start();

    // Creating the Token to connect to the REST server


    final String myUrl = MY_SERVER_ADDRESS;
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, myUrl, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jsonObject) {
            exponent = jsonObject.optString("publicExponent");
            modulus = jsonObject.optString("publicModulus");
            ex = new BigInteger(exponent);
            mo = new BigInteger(modulus);
            Log.i("TEST REST ", ex.toString());
            Log.i("TEST REST ", mo.toString());
            try {
                key = RSACrypt.encrypt("temporary password", mo, ex);
                Log.i("TOKEN GENERATION", "La clé est : " + key);
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("password", key);
                String body = new JSONObject(params).toString().replace("\", "");
                Log.i("JSON OBJECT", body);
                JsonRequest tokenRequest = new JsonStringRequest(Request.Method.POST, myUrl, body, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        TOKEN_VALUE = jsonObject.optString("token");
                        Log.i("TOKEN GENERATION", "Le token est : " + TOKEN_VALUE);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        String message = new String(volleyError.networkResponse.data);
                        Log.i("REQUETE 2", "Erreur" + volleyError.getMessage() + message);
                    }
                });
                mRequestQueue.add(tokenRequest);
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("ERROR TOKEN GENERATION", e.getMessage());
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            TOKEN_VALUE = "HOSTUNREACHABLE";
            Log.i("REQUETE 1", "Erreur" + volleyError.getMessage());
        }
    });
    mRequestQueue.add(request);

    // Sending the request with all parameters
    b2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Getting the current date
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
            String date = df.format(Calendar.getInstance().getTime());
            lon = locationMangaer.getLastKnownLocation(LOCATION_SERVICE).getLongitude();
            lat = locationMangaer.getLastKnownLocation(LOCATION_SERVICE).getLatitude();
            // Filling params
            params.put(REASON, reason);
            params.put(ID_VALVE, mId.getText().toString());
            params.put(OPERATOR, mName.getText().toString());
            params.put(DATE, date + "T00:00:00");
            params.put(CONDITION, condition);
            params.put(LONGITUDE, Double.toString(lon));
            params.put(LATITUDE, Double.toString(lat));

            for (int k = 0; k < pictureNameArray.length; k++) {
                Bitmap bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/MyApp/MyImages/" + pictureNameArray[k] + ".jpg");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
                byte[] b = baos.toByteArray();
                String encodedImage = Base64.encodeToString(b, Base64.NO_WRAP);
                Log.i("PICTURE data", encodedImage);
                HashMap<String, String> currentPic = new HashMap<String, String>();
                currentPic.put(DATA, encodedImage);
                currentPic.put(FILENAME, pictureNameArray[k]);
                currentPic.put(MEDIATYPE, "image/jpg");
                PicList.put(new JSONObject(currentPic));
            }


            AlertDialog.Builder alert = new AlertDialog.Builder(HomeActivity.this);
            final EditText edittext = new EditText(getApplicationContext());
            alert.setMessage("Veuillez saisir un commentaire sur l'examen");
            alert.setTitle("Commentaire");
            alert.setView(edittext);
            alert.setPositiveButton("Continuer", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String myComment = edittext.getText().toString();
                    params.put(COMMENT, myComment);

                    if (TOKEN_VALUE == "HOSTUNREACHABLE") {
                        // Save on SQL Lite + alert
                    } else {
                        Intent intent = new Intent(HomeActivity.this, SendMyRequestService.class);
                        intent.putExtra("PARAMS", params);
                        intent.putExtra("PICLIST", pictureNameArray);
                        intent.putExtra("TESTLIST", TestList.toString());
                        startActivity(intent);
                    }
                }
            });

            alert.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    params.clear();
                }
            });

            alert.show();


        }
    });

    b3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            params.put(REASON, reason);
            params.put(ID_VALVE, mId.getText().toString());
            params.put(OPERATOR, mName.getText().toString());
            params.put(CONDITION, condition);

            Intent intent = new Intent(HomeActivity.this, ListDeviceActivity.class);
            intent.putExtra("COMPTEUR", pictureNumber);
            intent.putExtra("TOKEN_VALUE", TOKEN_VALUE);
            intent.putExtra("PARAMS", params);
            intent.putExtra("PICLIST", pictureNameArray);
            intent.putExtra("TESTLIST", TestList.toString());
            startActivity(intent);
        }
    });


@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String TOKEN_VALUE = intent.getStringExtra("TOKEN_VALUE");
    String params = intent.getStringExtra("params");
    String test_data = intent.getStringExtra("TESTDATA");
    String test_temp = intent.getStringExtra("TESTTEMP");
    String testArray = intent.getStringExtra("TESTLIST");

    try {
        JSONObject parameters = new JSONObject(params);
        Log.i("Id valve récuperé", parameters.optString("ID_VALVE"));
        Log.i("Raison récuperée", parameters.optString("REASON"));
        Log.i("Nom opérateur récuperé", parameters.optString("OPERATOR"));
        Log.i("Condition récuperée", parameters.optString("CONDITION"));
        if (parameters.optString("ID_VALVE") != null)
            mId.setText(parameters.optString("ID_VALVE"));
        if (parameters.optString("REASON") != null) {
            int i = this.getResources().getIdentifier(parameters.optString("REASON"), "string", this.getPackageName());
            reason_status.setSelection(i);
        }
        if (parameters.optString("OPERATOR") != null)
            mName.setText(parameters.optString("OPERATOR"));
        if (parameters.optString("CONDITION") != null) {
            int j = this.getResources().getIdentifier(parameters.optString("CONDITION"), "string", this.getPackageName());
            condition_status.setSelection(j);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (intent.getStringArrayExtra("PICLIST") != null) {
        pictureNameArray = intent.getStringArrayExtra("PICLIST");
    }
    HashMap<String, String> currentTest = new HashMap<String, String>();
    if (testArray != null) {
        try {
            TestList = new JSONArray(testArray);
            currentTest.put(TDATA, test_data);
            currentTest.put(TEMP, test_temp);
            TestList.put(new JSONObject(currentTest));
            } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        currentTest.put(TDATA, test_data);
        currentTest.put(TEMP, test_temp);
        TestList.put(new JSONObject(currentTest));

    }
}

删除:

client.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

ActivityA中使用:

   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
       if (resultCode == Activity.RESULT_OK && data != null) {
     //do some action
    }

 }

当你使用FLAG_ACTIVITY_SINGLE_TOP时,你可以在onNewIntent()方法中检索Intent,而不是在onCreate().

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String TOKEN_VALUE = intent.getStringExtra("TOKEN_VALUE");
    String params = intent.getStringExtra("params");
    // and so on ....
}

对于 singleTop Activities,onNewIntent() 方法充当入口点而不是 onCreate() 执行。因为 Activity 已经存在于某处,所以不会调用 onCreate()

此外,在这种情况下使用 startActivityForResult() 是错误的,正如其他一些帖子所建议的那样。 onActivityResult() 的回调将在 C 中,而不是在 A 中。

用 Activity C:

中的代码替换您的代码
Intent i = new Intent(ActivityC.this, ActivityA.class);
i.putExtra("TOKEN_VALUE", TOKEN_VALUE);
i.putExtra("PARAMS", params);
startActivity(i);

并且在 Activity A 中,只需通过以下方式获取值:

Intent intent= getIntent();
String value1 = intent.getStringExtra("TOKEN_VALUE");
String value2 = intent.getStringExtra("params");