Aspen
Aspen

Reputation: 91

android: how to automatically run something after Activity start

my idea is after the activity starts, a button will be automatically clicked. Meanwhile, a dialogue pops out, asking you if want to interrupt. How can I implement this?


update: What I want is to remote control my phone. Via adb am to start the app, so I want some OnclickListener will be called automatically. Also, in the UI, it provides an option to interrupt this automation. I want the main activity start, and then Thread.sleep(5000). A dialog pops out asking you if you want automation or not. If I give an answer before that sleep ends, it will not get into automation state.

Thank you so much!

Upvotes: 0

Views: 417

Answers (1)

Jarno Argillander
Jarno Argillander

Reputation: 5945

In onCreate, just call onClick handler and give your button as an argument. Launch an AsyncTask inside to do lengthy operations in the background. Then simply show an AlertDialog for the user.

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

    Button launch = (Button) findViewById(R.id.launch);
    launch.setOnClickListener(this);

    onClick(launch); // Magic.
    showDialog(); // Show the interrupt dialog
}

@Override public void onClick(View v)
{
    Toast.makeText(this, "Wohoo!", Toast.LENGTH_SHORT).show();
    // Actually, launch an AsyncTask here.
}

private void showDialog()
{
    AlertDialog.Builder dlg = new AlertDialog.Builder(this);
    dlg.setTitle("Interrupt?");
    dlg.setMessage("Do you want to interrupt loading?");

    dlg.setPositiveButton("Yes", new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dlg, int item)
        {
            Toast.makeText(getApplicationContext(), "Yes!!!", Toast.LENGTH_SHORT).show();
        }
    });

    dlg.setNegativeButton("No", new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dlg, int item)
        {
            Toast.makeText(getApplicationContext(), "Noooo...", Toast.LENGTH_SHORT).show();
        }
    });

    dlg.show();
}

Upvotes: 1

Related Questions