如何使用另一个按钮执行活动?

时间:2016-02-19 14:47:57

标签: java android android-intent

如何在不进行操作的情况下在另一个活动中执行一项活动? 我的意思是,我有 MainActivity ,我从意图中获取了 ReadFromAssetActivity 的一些int数组。但要获得这些int数组,我需要首先执行 ReadFromAssetActivity ,然后转到 MainActivity 并执行它。 我想要的是按 MainActivity 中的按钮,执行 ReadFromAssetActivity ,而无需进行该活动。

MainActivity

public class MainActivity extends AppCompatActivity {

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

        // Getting reference to the button btn_chart
        Button btnChart = (Button) findViewById(R.id.btn_chart);

        // Defining click event listener for the button btn_chart
        View.OnClickListener clickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Draw the Chart
                openChart();
            }
        };

        // Setting event click listener for the button btn_chart of the SensorGraph layout
        btnChart.setOnClickListener(clickListener);

    }

    private void openChart() {

        Intent intent = getIntent();

        int[] force_l = intent.getIntArrayExtra("force_l");
        int[] force_r = intent.getIntArrayExtra("force_r");
        int[] x = new int[force_l.length];
(...)

ReadFromAssetActivity

public class ReadFromAssetActivity extends AppCompatActivity {
    private Button read_Button;
    int[] force_l = null;
    int[] force_r = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_from_asset);

        initializeUI();
    }

    private void initializeUI() {
        read_Button = (Button) findViewById(R.id.ReadFromAssetActivity_start_reading_button);
        read_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ReadFromAsset().execute();
            }
        });
    }

    private class ReadFromAsset extends AsyncTask<Void, Void, Void> {

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

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(getAssets().open("test.txt")));
                String mLine = null;
                int count = 0;
                while ((mLine = reader.readLine()) != null) {
                    String[] integer_Strings = mLine.split(" ");
                    //System.out.println(Arrays.deepToString(integer_Strings));
                    if (count == 0) {
                        force_l = new int[integer_Strings.length];
                        for (int i = 0; i < integer_Strings.length; i++) {
                             force_l[i] = Integer.parseInt(integer_Strings[i]);
                        }
                        count++;
                    } else if (count == 1) {
                        force_r = new int[integer_Strings.length];
                        for (int i = 0; i < integer_Strings.length; i++) {
                            force_r[i] = Integer.parseInt(integer_Strings[i]);
                        }
                     }

                }

                Intent intent = new Intent(ReadFromAssetActivity.this, MainActivity.class);
                intent.putExtra("force_l", force_l);
                intent.putExtra("force_r", force_r);
                startActivity(intent);

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

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

你打算实现的目标并不是纯粹的Android方式。您不需要单独的ReadFromAssetActivity&#39;或任何其他活动来运行您的AsyncTask。最好的想法是将ReadFromAsset放入MainActivity并从openChart方法调用。在回调接口中从AsyncTask获取int数组。

如果您的任务实际上比您在此代码段中向我们展示的要复杂得多,请考虑使用IntentService的可能性。

答案 1 :(得分:1)

使您的ReadFromAsset任务成为一个单独的类(不是活动的内部类),并将数组存储为&#34;结果&#34;。同时给这个任务一个方法来记住一个&#34;听众&#34;这样.onPostExecute()可以将这些数组发送回监听器(在本例中是您的主要活动)。 我会输出一个一般的例子但是我在移动设备上已经有很多例子了。 编辑:一个例子:

/*
 * This consumer could be anything -- an activity, a service, a data
 * object, whatever. All it needs to do is implement the task's
 * listener interface.
 */
public class Example
implements MyTask.Listener
{
    // other code

    public void doThings()
    {
        (new MyTask()).setListener(this)
            .setInputFile( "flargle.txt" )
            .execute()
            ;
    }

    /** Specified by MyTask.Listener, called by MyTask#onPostExecute() */
    public void onMyTaskComplete( MyTaskResult res )
    {
        // Do something with the result.
    }
}

public class MyTaskResult
{
    // Stores whatever complex data you want the task to create.
    // Necessary only if what you're creating is really complex.
}

public class MyTask extends AsyncTask<Void,Void,MyTaskResult>
{
    public interface Listener
    {
        void onMyTaskComplete( MyTaskResult res ) ;
    }

    protected Listener m_lstn ;
    protected String m_sFilename ;

    public MyTask setListener( Listener lstn )
    {
        m_lstn = lstn ;
        return this ;
    }

    public MyTask setInputFile( String sFilename )
    {
        m_sFilename = sFilename ;
        return this ;
    }

    @Override
    public MyTaskResult doInBackground( Void... aNulls )
    {
        MyTaskResult res = new MyTaskResult() ;
        // Do stuff that produces a MyTaskResult.
        return res ;
    }

    @Override
    public void onPostExecute( MyTaskResult res )
    {
        m_lstn.onMyTaskCompleted( res ) ;
    }
}

答案 2 :(得分:0)

只需在ReadFromAssetActivity中创建一个公共静态方法即可。现在,您可以根据需要添加。您可以根据您的要求调用该方法并从Main活动执行。