我是android java开发的新手。我尝试实现QR-Code-Scanner。我找到了一个很好的类来实现这个功能。但我想分开这堂课。
我有两节课。
public class MainActivity extends AppCompatActivity {
public class QrCodeScanner extends Activity
从我想要调用方法的MainActivity
public void scanQR(View v)
这怎么办?
我无法从QrCodeScanner
类创建实例。
提前致谢!
public class QrCodeScanner extends Activity {
static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the main content layout of the Activity
setContentView(R.layout.activity_main);
}
//product qr code mode
public void scanQR(View v) {
try {
//start the scanning activity from the 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) {
//on catch, show the download dialog
showDialog(QrCodeScanner.this, "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
//alert dialog for downloadDialog
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();
}
//on ActivityResult method
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
//get the extras that are returned from the intent
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
}
}
}
}
答案 0 :(得分:0)
你的方法实际上只是为另一个活动开始一个意图,所以你为什么不在另一个类中创建这个方法,所以你可以从任何有上下文参数的地方调用它:
//product qr code mode
public void scanQR(View v, Context ctx) {
try {
//start the scanning activity from the com.google.zxing.client.android.SCAN intent
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
((Activity) ctx).startActivityForResult(intent, 0);
} catch (ActivityNotFoundException anfe) {
//on catch, show the download dialog
}
}
扫描结果应该传递给持有上下文的活动。