我是Android/Java开发新手。我正在尝试在Android Studio中制作一个应用程序,扫描QR码并将扫描的数据自动发送到电话号码。到目前为止,我有一个QR码扫描器的源代码,我从Github得到的,运行良好,但它只是扫描,不能让它发送扫描的数据,我需要添加什么代码发生。由于
下面是代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CodeScannerView scannerView = findViewById(R.id.scanner_view);
mCodeScanner = new CodeScanner(this, scannerView);
mCodeScanner.setDecodeCallback(new DecodeCallback() {
@Override
public void onDecoded(@NonNull final Result result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result.getText(), Toast.LENGTH_SHORT).show();
}
});
}
});
scannerView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCodeScanner.startPreview();
}
});
}
@Override
protected void onResume() {
super.onResume();
mCodeScanner.startPreview();
}
@Override
protected void onPause() {
mCodeScanner.releaseResources();
super.onPause();
}
}
你应该得到一个代码片段发送短信在谷歌搜索的任何地方,因为你做了QRCode scanner
部分。如果有帮助的话,下面是
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
String phoneNo;// make sure to put your phone number here
String message;
protected void sendSMSMessage() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
然后在收到扫描码结果时调用sendSMSMessage("12312312", message);
。或者像下面这样:
mCodeScanner.setDecodeCallback(new DecodeCallback() {
@Override
public void onDecoded(@NonNull final Result result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
message = result.getText();
sendSMSMessage();
Toast.makeText(MainActivity.this, result.getText(), Toast.LENGTH_SHORT).show();
}
});
}
});