几年后,我才重新开始编写代码,并决定尝试使用Android开发。我正在编写的应用程序使用条形码扫描仪,我希望主屏幕上有2个按钮来执行不同的任务,但最终以主要活动的“ onActivityResult”方法结束。我认为执行此操作的最佳方法是使用zxing执行此操作,即使用IntentIntegrator类中的setRequestCode方法。但是,当我这样做时,我的结果总是返回为null。如果我删除setRequestCode所在的行,则该应用程序运行良好。这是我的MainActivity。
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class MainActivity extends AppCompatActivity {
TextView tvResults;
Button btnScan;
final int SCAN = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResults = findViewById(R.id.tvResults);
btnScan = findViewById(R.id.btnScan);
btnScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(MainActivity.this); // `this` is the current Activity
integrator.setPrompt("Scan Something");
integrator.setOrientationLocked(false);
integrator.setRequestCode(SCAN);
integrator.initiateScan();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (requestCode==SCAN) {
Toast.makeText(this, "Request Code is: " + requestCode, Toast.LENGTH_LONG).show();
}
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
tvResults.setText(result.getContents());
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}