以编程方式处理活动堆栈

时间:2012-09-24 10:07:52

标签: android android-activity activity-stack

我在申请表A中有四项活动 - > B - > C - > D.

我写了一个我自己的类 MyActivity ,它扩展了Activity类。我编写这个类来处理活动堆栈。这个类有两个方法addActivitiyTostack()和getActivityFromStack() 我使用堆栈来存储活动。

所有其他活动都在扩展此课程。 当我使用intent从一个活动移动到另一个活动时,它会添加到堆栈中。

当我移动后台活动时会弹出。 我可以正确地将活动添加到堆栈中,但是我在弹出活动时遇到了问题。

我还有所有活动的Logout Button,OnClick这个按钮我要关闭应用程序如何实现它?任何人都知道如何在android中处理活动堆栈。

这是我的代码。

package com.example.iprotect;

import java.util.Enumeration;
import java.util.Stack;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MyActivity extends Activity {

    private static Stack<Activity> stack = new Stack<Activity>();
    static int top=0;

    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        addActivityToStack(this);
    }


    public static void addActivityToStack(MyActivity myActivity) {
        // TODO Auto-generated method stub
        stack.push(myActivity);
        for (int i =0; i< stack.size() ; i++) {
            Activity act=stack.get(i);
            Log.i("Element in stack", ""+act);
        }
    }


    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //getActivityFromStack();
        //logoutFromApplication();

    }


    public static void logoutFromApplication() {
        // TODO Auto-generated method stub
        Enumeration<Activity> enm=stack.elements();

        while(enm.hasMoreElements())
        {
            Activity act=enm.nextElement();
            stack.pop();
        }

    }


    public static Activity getActivityFromStack() {
        return stack.pop();
    }

}

A - &GT;

public class WebServiceActivity extends MyActivity{

    EditText editText1, editText2;
    Button button;
    String response = "";
    String email, password;

    public final Pattern EMAIL_ADDRESS_PATTERN = Pattern
            .compile(".+@.+\\.[a-z]+");

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText editText1 = (EditText) findViewById(R.id.etEmail);
        final EditText editText2 = (EditText) findViewById(R.id.etPassword);

        button = (Button) findViewById(R.id.loginButton);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(editText1.getText().toString())) {
                    Toast.makeText(getApplicationContext(),
                            "please enter email id", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(editText2.getText().toString())) {

                    Toast.makeText(getApplicationContext(),
                            "please enter passwod", Toast.LENGTH_SHORT).show();
                } else {
                    Boolean bool = EMAIL_ADDRESS_PATTERN.matcher(
                            editText1.getText().toString()).matches();
                    if (bool == true) {

                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Invalid email id", Toast.LENGTH_SHORT).show();
                    }

                    email = editText1.getText().toString();
                    password = editText2.getText().toString();
                    // final ProgressDialog pd = ProgressDialog.show(
                    // WebServiceActivity.this, "Calling webservice...",

                    // "Please wait...", true, false);

                    final ProgressBar bar = (ProgressBar) findViewById(R.id.progressBar2);
                    bar.setVisibility(View.VISIBLE);

                    new AsyncTask<Void, Void, Void>() {
                        String r;

                        protected void onPreExecute() {
                        };

                        @Override
                        protected Void doInBackground(Void... params) {
                            r = invokeWebService();

                            return null;
                        };

                        protected void onPostExecute(Void result) {
                            bar.setVisibility(View.VISIBLE);

                        };

                    }.execute();

                }
            }

            private String invokeWebService() {
                String response = "";
                try {
                    WebService webService = new WebService(
                            "http://sphinx-solution.com/iProtect/api.php?");
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("action", "auth");
                    params.put("email", email);
                    params.put("password", password);
                    response = webService.WebGet("auth", params);

                    JSONObject jsonObject = new JSONObject(response);
                    String rr = jsonObject.optString("status");

                    if (TextUtils.equals(rr, "success")) {
                        Log.e("MSG", "status==success");
                        Intent intent = new Intent(WebServiceActivity.this,
                                SecondActivity.class);
                        //MyActivity.addActivityToStack(WebServiceActivity.this);
                        intent.putExtra("email", email);
                        intent.putExtra("password", password);
                        WebServiceActivity.this.startActivity(intent);
                        finish();

                    } else {
                        Log.e("MSG", "status ==failed");

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return response;
            }
        });
    }
}

乙 - &GT;

public class SecondActivity extends MyActivity {

    ListView listView;
    String email1, password1;
    ArrayList<JSONStructure> arrayList = new ArrayList<JSONStructure>();
    String r;
    String r1;
    String tablename;
    String rows;
    JSONObject jsonObject;
    String tablename2;

    @Override
    public void onCreate(Bundle savedInstanceState) {

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

        Intent intent = getIntent();
        email1 = intent.getExtras().getString("email");
        password1 = intent.getExtras().getString("password");

        Button btn1 = (Button) findViewById(R.id.refreshbutton);
        btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                final ProgressDialog pd = ProgressDialog.show(
                        SecondActivity.this, "Refresh List...",
                        "Please wait...", true, false);

                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        pd.dismiss();
                        r = invokeWebService();
                        return null;
                    }

                    protected void onPostExecute(Void result) {
                    };

                }.execute();

            }
        });

        Button btn = (Button) findViewById(R.id.logoutbutton);

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                final ProgressDialog pd = ProgressDialog.show(
                        SecondActivity.this, "Calling webservice...",
                        "Please wait...", true, false);

                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        pd.dismiss();
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        Intent intent = new Intent(SecondActivity.this,
                                WebServiceActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        SecondActivity.this.startActivity(intent);

                    }

                }.execute();

            }

        });

        listView = (ListView) findViewById(R.id.listview1);

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,
                    int position, long id) {

                JSONStructure jsonstructure = (JSONStructure) listView
                        .getAdapter().getItem(position);

                final String tablename1 = jsonstructure.getTableName()
                        .toString();

                Intent intent = new Intent(SecondActivity.this,
                        ProgressBarActivity.class);
                //MyActivity.addActivityToStack(SecondActivity.this);

                intent.putExtra("tablename", tablename1);
                intent.putExtra("Rows", rows);
                intent.putExtra("email", email1);
                intent.putExtra("password", password1);

                SecondActivity.this.startActivity(intent);

            }

        });

        new AsyncTask<Void, Void, Void>() {

            @Override
            protected void onPreExecute() {

                super.onPreExecute();
            }

            @Override
            protected Void doInBackground(Void... params) {
                r = invokeWebService();

                try {
                    JSONArray jsonArray = new JSONArray();
                    JSONObject jsonObject = new JSONObject(r);
                    jsonArray = jsonObject.getJSONArray("Records");

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject c = jsonArray.getJSONObject(i);
                        tablename = c.optString("TABLE NAME");
                        rows = c.optString("Rows");
                        JSONStructure jsonStructure = new JSONStructure();
                        jsonStructure.setTableName(tablename);
                        jsonStructure.setRows(rows);
                        arrayList.add(jsonStructure);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                return null;

            }

            @Override
            protected void onPostExecute(Void result) {
                if (arrayList != null && arrayList.size() > 0) {

                    MyAdapter adapter = new MyAdapter(SecondActivity.this,
                            arrayList);
                    listView.setAdapter(adapter);
                }
            }

        }.execute();

    }

    private String invokeWebService() {
        String response = "";
        try {
            WebService webService = new WebService(
                    "http://sphinx-solution.com/iProtect/api.php?");
            Map<String, String> params = new HashMap<String, String>();
            params.put("action", "getTables");
            params.put("email", email1);
            params.put("password", password1);
            response = webService.WebGet("getTables", params);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

}

C - &GT;

public class ThirdActivity extends MyActivity {
    String tablename1, row1, json1;
    ArrayList<JSONStructure> arrayList = new ArrayList<JSONStructure>();

    JSONArray jsonArray, jsonArray2;
    JSONObject jsonObject;
    String row;
    String email1, password1;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.third_layout);

        ListView listView = (ListView) findViewById(R.id.listview2);

        TextView textView = (TextView) findViewById(R.id.title_textview);

        Intent intent = getIntent();
        tablename1 = intent.getExtras().getString("tablename");
        row = intent.getExtras().getString("Rows");
        textView.setText(tablename1);
        json1 = intent.getExtras().getString("Json");
        email1 = intent.getExtras().getString("email");
        password1 = intent.getExtras().getString("password");

        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {

                return null;
            }

            @Override
            protected void onPostExecute(Void result) {

                Button button = (Button) findViewById(R.id.goback);
                button.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        Intent intent = new Intent(ThirdActivity.this,
                                SecondActivity.class);
                        MyActivity.getActivityFromStack();
                        intent.putExtra("email", email1);
                        intent.putExtra("password", password1);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        ThirdActivity.this.startActivity(intent);

                    }
                });

            }

        }.execute();

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,
                    final int position, long id) {
                final ProgressDialog pd = ProgressDialog.show(
                        ThirdActivity.this, "Calling webservice...",
                        "Please wait...", true, false);

                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... paramArrayOfParams) {

                        pd.dismiss();

                        try {

                            jsonObject = new JSONObject(json1);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        Intent intent = new Intent(ThirdActivity.this,
                                FinalActivity.class);
                        //MyActivity.addActivityToStack(ThirdActivity.this);
                        intent.putExtra("tablename", tablename1);
                        intent.putExtra("Json", jsonObject.toString());
                        intent.putExtra("Row", position);
                        intent.putExtra("email", email1);
                        intent.putExtra("password", password1);
                        ThirdActivity.this.startActivity(intent);

                    }

                }.execute();

            }

        });

        try {

            JSONObject jsonObject = new JSONObject(json1);
            JSONArray jsonArray = new JSONArray();
            jsonArray = jsonObject.getJSONArray("FirstThree");
            jsonArray2 = jsonObject.getJSONArray("Color");

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject c = jsonArray.getJSONObject(i);
                String one = c.optString("One");
                String two = c.optString("Two");
                String three = c.optString("Three");

                JSONObject c1 = jsonArray2.getJSONObject(i);

                String color = c1.optString("color");

                JSONStructure jsonStructure = new JSONStructure();
                jsonStructure.column1 = one;
                jsonStructure.column2 = two;
                jsonStructure.column3 = three;
                jsonStructure.setColumn1(one);
                jsonStructure.setColumn2(two);
                jsonStructure.setColumn3(three);
                jsonStructure.setColor(color);

                arrayList.add(jsonStructure);
                Log.e("one", c.optString("One"));
                Log.e("two", c.optString("Two"));
                Log.e("three", c.optString("Three"));
                Log.e("color", c1.optString("color"));

            }

        } catch (Exception e) {
            e.printStackTrace();

        }

        if (arrayList != null && arrayList.size() > 0) {

            MyAdapter1 adapter1 = new MyAdapter1(ThirdActivity.this, arrayList);
            listView.setAdapter(adapter1);

        }

        Button btn = (Button) findViewById(R.id.logoutbutton);

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                final ProgressDialog pd = ProgressDialog.show(
                        ThirdActivity.this, "Calling webservice...",
                        "Please wait...", true, false);

                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        pd.dismiss();
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        Intent intent = new Intent(ThirdActivity.this,
                                WebServiceActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        ThirdActivity.this.startActivity(intent);
                        super.onPostExecute(result);
                    }

                }.execute();

            }

        });

    }

}

任何人都有疑问,请随意问?

1 个答案:

答案 0 :(得分:1)

假设您需要此堆栈仅用于注销功能,则有更好的方法。改为使用广播。在MyActivity.onCreate中注册BroadcastReceiver。接收者应该只调用活动的结束()。从按钮的点击监听器发送广播(btn1?该按钮做什么?无法从名称猜测;需要更好的名称;))。就是这样。