T
T
TILLhen2018-04-17 12:17:24
Java
TILLhen, 2018-04-17 12:17:24

How to launch a method of the second Activity, using a button on the first Activity?

I am creating an application in which I have embedded a QR-code scanner. I need to make it so that when a button is pressed on one Activity, a button is pressed on another Activity, or when a button is pressed on the first Activity, a scanner immediately opens on the second Activity.
5ad5bb04b35f3922954823.png5ad5bb0d1a305679331643.png
This is how I use an intent to navigate to another Activity:

ImageButton scannerButton;

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

    scannerButton = (ImageButton) findViewById(R.id.scannerButton);
    scannerButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(HomeActivity.this, ScannerActivity.class);
            startActivity(intent);
        }
    });
}
}

Code of the scanner itself:
static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";

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

// Запуск сканера qr-кода:
public void scanQR(View v) {
    try {

        // Запускаем переход на com.google.zxing.client.android.SCAN с помощью intent:
        Intent intent = new Intent(ACTION_SCAN);
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    } catch (ActivityNotFoundException anfe) {

        // Предлагаем загрузить с Play Market:
        showDialog(ScannerActivity.this, "Сканнер не найден", "Установить сканер с Play Market?", "Да", "Нет").show();
    }
}

// alert dialog для перехода к загрузке приложения сканера:
private static AlertDialog showDialog(final Activity act, CharSequence title,
                                      CharSequence message,CharSequence buttonYes, CharSequence buttonNo) {
    AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
    downloadDialog.setTitle(title);
    downloadDialog.setMessage(message);
    downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {

            // Ссылка поискового запроса для загрузки приложения:
            Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            try {
                act.startActivity(intent);
            } catch (ActivityNotFoundException anfe) {

            }
        }
    });
    downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
        }
    });
    return downloadDialog.show();
}

// Обрабатываем результат, полученный от приложения сканера:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {

            // Получаем данные после работы сканера и выводим их в Toast сообщении:
            String contents = intent.getStringExtra("SCAN_RESULT");
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
            Toast toast = Toast.makeText(this, "Содержание: " + contents + " Формат: " + format, Toast.LENGTH_LONG);
            toast.show();
        }
    }
}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita, 2018-04-17
@vasilek-nik

When launching an activity through an Intent, you can pass data of the "key-value" type to it. In the launched activity, they can be received and processed.
Main activity:

Intent intent = new Intent(HomeActivity.this, ScannerActivity.class);
intent.putExtra("needScan", true);
startActivity(intent);

In the onCreate of the launched activity, this can be handled:
Intent intent = getIntent();
if (intent.getBooleanExtra("needScan", false))
    scanQR(null);

Data can be sent in different types. Read more about Intent in the documentation
I apologize for possible inaccuracies, I wrote from a slipper

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question