I am using a Bluetooth printer and zxing barcode scanner for this project. My problem is that after I have the Bluetooth printer connected and I try to scan a barcode, using zxing, it disconnects the Bluetooth printer. Here is my code.
package com.zj.printdemo;
import com.zj.printdemo.R;
import android.app.Fragment;
import android.content.Intent;
import com.zj.btsdk.BluetoothService;
import com.zj.btsdk.PrintPic;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.view.View.OnClickListener;
import android.util.Log;
import android.view.ViewGroup;
public class PrintDemo extends Activity {
Button btnSearch;
Button btnSendDraw;
Button btnSend;
//Button btnClose;
Button clearBtn;
Button btnBarcode;
EditText edtContext;
EditText edtContextQTY;
EditText edtPrint;
private static final int REQUEST_ENABLE_BT = 2;
BluetoothService mService = null;
BluetoothDevice con_dev = null;
private static final int REQUEST_CONNECT_DEVICE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
//Button clearBtn = (Button)findViewById(R.id.btnClear);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//edtContext = (EditText) findViewById(R.id.txt_content);
mService = new BluetoothService(this, mHandler);
if( mService.isAvailable() == false ){
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
clearBtn = (Button)findViewById(R.id.btnClear);
OnClickListener ClearOnClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
edtContext.setText("");
edtContextQTY.setText("");
}
};
clearBtn.setOnClickListener(ClearOnClickListener);
btnBarcode = (Button) findViewById(R.id.btnBarcode);
OnClickListener BarcodeOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnBarcode) {
IntentIntegrator integrator = new IntentIntegrator(PrintDemo.this);
integrator.initiateScan();
}
}
};
btnBarcode.setOnClickListener(BarcodeOnClickListener);
}
public void onStart() {
super.onStart();
if( mService.isBTopen() == false)
{
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_test);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btnSend);
btnSend.setOnClickListener(new ClickEvent());
//btnClose = (Button) this.findViewById(R.id.btnClose);
//btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
edtContextQTY = (EditText) findViewById(R.id.txt_contentQTY);
//btnClose.setEnabled(false);
btnSend.setEnabled(false);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("������Ϣ",ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this,DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
String msg = edtContext.getText().toString();
String msgQTY = edtContextQTY.getText().toString();
if( msg.length() > 0 ){
mService.sendMessage("ItemID:"+msg+"\n","ItemQTY:"+msgQTY+"\n");
}
} //else if (v == btnClose) {
//mService.stop();}
else if (v == btnSendDraw) {
String msg = "";
String lang = getString(R.string.strLang);
//printImage();
byte[] cmd = new byte[3];
cmd[0] = 0x1b;
cmd[1] = 0x21;
if((lang.compareTo("en")) == 0){
cmd[2] |= 0x10;
mService.write(cmd);
mService.sendMessage("Congratulations!\n", "GBK");
cmd[2] &= 0xEF;
mService.write(cmd);
msg = " You have sucessfully created communications between your device and our bluetooth printer.\n\n"
+" the company is a high-tech enterprise which specializes" +
" in R&D,manufacturing,marketing of thermal printers and barcode scanners.\n\n";
mService.sendMessage(msg,"GBK");
}else if((lang.compareTo("ch")) == 0){
cmd[2] |= 0x10;
mService.write(cmd);
mService.sendMessage("��ϲ����\n", "GBK");
cmd[2] &= 0xEF;
mService.write(cmd);
msg = " ���Ѿ��ɹ��������������ǵ�������ӡ����\n\n"
+ " ����˾��һ��רҵ�����з�����������������Ʊ�ݴ�ӡ��������ɨ���豸��һ��ĸ߿Ƽ���ҵ.\n\n";
mService.sendMessage(msg,"GBK");
}
}
}
}
/**
* Handler BluetoothService
*/
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
//btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("��������","��������.....");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("StateNone","�ȴ�����.....");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
//btnClose.setEnabled(false);
btnSend.setEnabled(false);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
case IntentIntegrator.REQUEST_CODE:
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
//formatTxt.setText("FORMAT: " + scanFormat);
edtContext.setText(scanContent);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData = null;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, "/mnt/sdcard/icon.jpg");
sendData = pg.printDraw();
mService.write(sendData);
}
}
My goal is to connect the printer, scan a barcode, and print a tag with the ID and quantity. Manual entry works, the printer works, and the barcode scanning works. Its only when you use the barcode scanner after you connect the printer that it will disconnect the printer.
Related
I'm a new android developer and trying to make image to text app. I watched some tutorials and pretty sure that i don't make any mistakes. I'm using ML Kit for this project and got error when i tried to convert the image to text.
My main activity
package com.gorkemtand.textrecognition;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.latin.TextRecognizerOptions;
import java.io.IOException;
import java.security.Permission;
public class MainActivity extends AppCompatActivity {
private MaterialButton inputImageBtn;
private MaterialButton recognizeTextBtn;
private ShapeableImageView imageIv;
private EditText recognizedTextEt;
private static final String TAG = "MAIN_TAG";
private Uri imageUri = null;
//to handle the result of Camere/Gallery permissions
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 101;
//arrays of permission required to pick image from Camera,gallery
private String[] cameraPermissions;
private String[] storagePermissions;
private ProgressDialog progressDialog;
private TextRecognizer textRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputImageBtn = findViewById(R.id.inputImageBtn);
recognizeTextBtn = findViewById(R.id.recognizeBtn);
imageIv = findViewById(R.id.imageIv);
recognizedTextEt = findViewById(R.id.recognizedTextEd);
cameraPermissions = new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please Wait");
progressDialog.setCanceledOnTouchOutside(false);
textRecognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
inputImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showInputImageDialog();
}
});
recognizeTextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imageUri == null){
Toast.makeText(MainActivity.this,"Pick image first...",Toast.LENGTH_SHORT).show();
}
else {
recognizeTextFromImage();
}
}
});
}
private void recognizeTextFromImage() {
Log.d(TAG, "recognizeTextFromImage: ");
progressDialog.setMessage("Preparing image...");
progressDialog.show();
try {
InputImage inputImage = InputImage.fromFilePath(this,imageUri);
progressDialog.setMessage("Recognizing text...");
Task<Text> textTaskResult = textRecognizer.process(inputImage).addOnSuccessListener(new OnSuccessListener<Text>() {
#Override
public void onSuccess(Text text) {
progressDialog.dismiss();
String recognizedText = text.getText();
Log.d(TAG, "onSuccess: recognizedText: "+recognizedText);
recognizedTextEt.setText(recognizedText);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Log.e(TAG, "onFailure: ",e);
Toast.makeText(MainActivity.this,"Failed recognizing text due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
progressDialog.dismiss();
Log.e(TAG, "recognizeTextFromImage: ",e);
Toast.makeText(MainActivity.this,"Failed preparing image due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
private void showInputImageDialog() {
PopupMenu popupMenu = new PopupMenu(this, inputImageBtn);
popupMenu.getMenu().add(Menu.NONE,1,1,"CAMERA");
popupMenu.getMenu().add(Menu.NONE,2,2,"GALLERY");
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if(id == 1){
Log.d(TAG, "onMenuItemClick: Camera Clicked...");
if(checkCameraPermissions()){
pickImageCamera();
}
else{
requestCameraPermissions();
}
}
else if(id == 2){
Log.d(TAG, "onMenuItemClick: Gallery Clicked...");
if(checkStoragePermision()){
pickImageGallery();
}
else{
requestStoragePermission();
}
}
return false;
}
});
}
private void pickImageGallery(){
Log.d(TAG, "pickImageGallery: ");
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
galleryActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> galleryActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
//image picked
Intent data = result.getData();
imageUri = data.getData();
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
//set to imageview
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled...",Toast.LENGTH_SHORT).show();
}
}
}
);
private void pickImageCamera(){
Log.d(TAG, "pickImageCamera: ");
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Sample Title");
values.put(MediaStore.Images.Media.DESCRIPTION, "Sample Description");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
cameraActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> cameraActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
);
private boolean checkStoragePermision(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission(){
ActivityCompat.requestPermissions(this,storagePermissions,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermissions(){
boolean cameraResult = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean storafeResult = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return cameraResult && storafeResult;
}
private void requestCameraPermissions(){
ActivityCompat.requestPermissions(this,cameraPermissions, CAMERA_REQUEST_CODE);
}
//handle permission results
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && storageAccepted){
pickImageCamera();
}
else {
Toast.makeText(this, "Camera && Storage permissions are required", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(this,"Cancelled",Toast.LENGTH_SHORT).show();
}
}
break;
case STORAGE_REQUEST_CODE:{
if(grantResults.length>0){
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (storageAccepted) {
pickImageGallery();
}
else {
Toast.makeText(this, "Storage permission is required", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
}
Also i implemented these two
implementation 'com.google.android.gms:play-services-mlkit-text-recognition:18.0.2'
implementation 'com.google.android.gms:play-services-mlkit-text-recognition-common:18.0.0'
And give the permissions to manifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the error i got:
Error
I searched the google and cnat find a solution. If u can help me i will be very happy.
I searched google and can't find anything works.
I solved by implementing com.google.mlkit:text-recognition:16.0.0-beta6
Are you testing on device without play store services? For example on an emulator? In order to use com.google.android.gms:play-services-mlkit-text-recognition:18.0.2 it has to be on a device with play store services.
Basically i have two java activities where i have implemented textToSpeech in one activity but when i go to another activity using on click view and when i pressed back for returning to the mainactivity then it will again execute texttospeech method.
But i want to execute this method only once when the user starts the app after that it will stop.
Below is my code and i want to execute the code only once how it will done?
package com.example.software2.ocrhy;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import androidx.appcompat.app.AppCompatActivity;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final int REQ_CODE_SPEECH_INPUT = 100;
private static int firstTime = 0;
private TextView mVoiceInputTv;
float x1, x2, y1, y2;
private TextView mSpeakBtn;
private static TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.US);
textToSpeech.setSpeechRate(1.1f);
if (firstTime == 0)
textToSpeech.setSpeechRate(1.1f);
textToSpeech.speak("Welcome to Blind App. Swipe left to listen the features of the app or swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
}
public boolean onTouchEvent(MotionEvent touchEvent) {
firstTime = 1;
switch (touchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
y1 = touchEvent.getY();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
y2 = touchEvent.getY();
if (x1 < x2) {
textToSpeech.speak(" Say Read for reading, calculator for calculator, time and date, weather for weather, battery for battery. Swipe right and say what you want ", TextToSpeech.QUEUE_FLUSH, null);
} else if (x1 > x2) {
startVoiceInput();
}
break;
}
return false;
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
a.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE_SPEECH_INPUT) {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
if (mVoiceInputTv.getText().toString().equals("read")) {
Intent intent = new Intent(getApplicationContext(), MainActivity2.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().equals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().equals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().equals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().equals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak("Do not understand tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().equals("yes")) {
textToSpeech.speak(" Say Read for reading, calculator for calculator, time and date, weather for weather, battery for battery. Do you want to listen again", TextToSpeech.QUEUE_FLUSH, null);
mVoiceInputTv.setText(null);
} else if ((mVoiceInputTv.getText().toString().equals("no"))) {
textToSpeech.speak("then tap on the screen and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
} else if (mVoiceInputTv.getText().toString().equals("exit")) {
finish();
}
}
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
public boolean onKeyDown(int keyCode, #Nullable KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
textToSpeech.speak("You are already in the main menu", TextToSpeech.QUEUE_FLUSH, null);
}
return true;
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
Make Text to Speak variable in Global and at these code in your onStop / onPause method.
public static void releaseTts() {
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
}
Replace these code in your MainActivity.class
private static final int REQ_CODE_SPEECH_INPUT = 100;
private static int firstTime = 0;
private TextView mVoiceInputTv;
private ImageButton mSpeakBtn;
private static TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.US);
if (firstTime == 0)
textToSpeech.speak("Welcome to Blind App. Tap on the screen. Say Read for reading . Say calculator for calculator.say time and date. say weather for weather. say battery for battery.", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
mSpeakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstTime = 1;
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
a.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE_SPEECH_INPUT) {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
if (mVoiceInputTv.getText().toString().equals("read")) {
Intent intent = new Intent(getApplicationContext(), MainActivity2.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().equals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().equals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().equals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().equals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
}
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
My current android app can turn on Bluetooth, make itself discoverable, list paired devices, and select a file from the device ( ie an image). However when I attempted to hit "send" the app seems to crash with an error. Not sure if it's refusing to send, or if it's not actually obtaining the file (yesterday I had a problem where it refused to send the selected, saying for me to select a file repeatedly. I will post the crash results and my mainActivity code. If anyone suggestions or ideas, please let me know.
Error: Debugging device
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bluetooth_demoproject, PID: 17593
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=300, data=null} to activity {com.example.bluetooth_demoproject/com.example.bluetooth_demoproject.MainActivity}: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.app.ActivityThread.deliverResults(ActivityThread.java:4107)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6120)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
at android.net.Uri.checkFileUriExposed(Uri.java:2346)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8909)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8894)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at com.example.bluetooth_demoproject.MainActivity.onActivityResult(MainActivity.java:350)
at android.app.Activity.dispatchActivityResult(Activity.java:6917)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4103)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6120)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Disconnected from the target VM, address: 'localhost:8601', transport: 'socket'
Here is my MainActivity
package com.example.bluetooth_demoproject;
import android.app.Activity;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
public class MainActivity extends Activity {
// Creating objects -----------------------------
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_BLU = 1;
// private static final int REQUEST_DISCOVER_BT_ = 1;
private static int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
TextView mBluetoothStatus, mPairedDevicesList, mTextFolder;
ImageView mBluetoothIcon;
Button mOnButton, mDiscoverableButton, mPairedDevices, mbuttonOpenDialog, msendBluetooth, mbuttonUp;
File root, fileroot, curFolder;
EditText dataPath;
private static final int DISCOVER_DURATION = 300;
private List<String> fileList = new ArrayList<String>();
// -------------------------------------------------------
BluetoothAdapter mBlueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataPath =(EditText)findViewById(R.id.FilePath);
mTextFolder = findViewById(R.id.folder);
mBluetoothStatus = findViewById(R.id.BluetoothStatus);
mBluetoothIcon = findViewById(R.id.bluetoothIcon);
mOnButton = findViewById(R.id.onButton);
// mOffButton = findViewById(R.id.offButton);
mDiscoverableButton = findViewById(R.id.discoverableButton);
mPairedDevices = findViewById(R.id.pairedDevices);
mPairedDevicesList = findViewById(R.id.pairedDeviceList);
mbuttonOpenDialog = findViewById(R.id.opendailog);
msendBluetooth = findViewById(R.id.sendBluetooth);
mbuttonUp = findViewById(R.id.up);
mbuttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPath.setText("");
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new
File(Environment.getExternalStorageDirectory().getAbsolutePath());
curFolder = root;
msendBluetooth.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
sendViaBluetooth();
}
});
//adapter
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBlueAdapter == null){
mBluetoothStatus.setText("Bluetooth is not available");
return;
}
else {
mBluetoothStatus.setText("Bluetooth is available");
}
//if Bluetooth isnt enabled, enable it
if (!mBlueAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//set image according to bluetooth Status
if (mBlueAdapter.isEnabled()) {
mBluetoothIcon.setImageResource(R.drawable.action_on);
}
else {
mBluetoothIcon.setImageResource(R.drawable.action_off);
}
//on button Click
mOnButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (!mBlueAdapter.isEnabled()) {
showToast("Turning Bluetooth on...");
// intent to on bluetooth
Intent intent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
else {
showToast("Bluetooth is already on");
}
}
});
//discover Bluetooth button
mDiscoverableButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (!mBlueAdapter.isDiscovering()) {
showToast("Making device discoverable");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_BLU);
}
}
});
// off button click
// mOffButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (mBlueAdapter.isEnabled()) {
// showToast("Turning Bluetooth off...");
// // intent to turn off bluetooth
// mBluetoothIcon.setImageResource(R.drawable.action_off);
// }
// else{
// showToast("Bluetooth is already off");
// }
//
// }
//});
//get paired device button click
mPairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()) {
mPairedDevices.setText("Paired Devices");
Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
for (BluetoothDevice device : devices){
mPairedDevices.append("\nDevice: " + device.getName() + "," + device );
}
}
else {
//bluetooth is off and cant get paired devices
showToast("Turn on bluetooth to get paired devices");
}
}
});
}
// #Override
// protected void onPrepareDialog(int id, Dialog dialog) {
// super.onPrepareDialog(id, dialog);
// switch (id) {
// case CUSTOM_DIALOG_ID:
// ListDir(curFolder);
// break;
// }
// }
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == CUSTOM_DIALOG_ID) {
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dailoglayout);
dialog.setTitle("Select Files");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
mTextFolder = (TextView) dialog.findViewById(R.id.folder);
mbuttonUp = (Button) dialog.findViewById(R.id.up);
mbuttonUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListDir(curFolder.getParentFile());
}
});
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File selected = new File(fileList.get(position));
if (selected.isDirectory()) {
ListDir(selected);
}
else if (selected.isFile()) {
getSelectedFile(selected);
}
else {
dismissDialog(CUSTOM_DIALOG_ID);
}
}
});
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (id == CUSTOM_DIALOG_ID) {
ListDir(curFolder);
}
}
public void getSelectedFile(File f) {
dataPath.setText(f.getAbsolutePath());
fileList.clear();
dismissDialog(CUSTOM_DIALOG_ID);
}
public void ListDir(File f) {
if (f.equals(root)) {
mbuttonUp.setEnabled(false);
}
else {
mbuttonUp.setEnabled(true);
}
curFolder = f;
mTextFolder.setText(f.getAbsolutePath());
dataPath.setText(f.getAbsolutePath());
File[] files = f.listFiles();
fileList.clear();
for (File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
// exits to app --------------------------------
public void exit(View V) {
mBlueAdapter.disable();
Toast.makeText(this, "*** Now bluetooth is off...", Toast.LENGTH_LONG).show();
finish();
}
// send file via bluetooth ------------------------
public void sendViaBluetooth() {
if(!dataPath.equals(null)) {
if(mBlueAdapter == null) {
Toast.makeText(this, "Device doesnt support bluetooth", Toast.LENGTH_LONG).show();
}
else {
enableBluetooth();
}
}
else {
Toast.makeText(this, "please select a file", Toast.LENGTH_LONG).show();
}
}
public void enableBluetooth() {
showToast("Making device discoverable");
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU) {
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);// STOPPED HERE-----------------------------------------------------------------
i.setType("*/*");
File file = new File(dataPath.getText().toString());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(i, 0);
if (list.size() > 0) {
String packageName = null;
String className = null;
boolean found = false;
for (ResolveInfo info : list) {
packageName = info.activityInfo.packageName;
if (packageName.equals("com.android.bluetooth")) {
className = info.activityInfo.name;
found = true;
break;
}
}
//CHECK BLUETOOTH available or not------------------------------------------------
if (!found) {
Toast.makeText(this, "Bluetooth not been found", Toast.LENGTH_LONG).show();
} else {
i.setClassName(packageName, className);
startActivity(i);
}
}
} else {
Toast.makeText(this, "Bluetooth is cancelled", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// Toast.makeText(this, "**********************************\nDeveloper: www.santoshkumarsingh.com\n**********************************", Toast.LENGTH_LONG).show();
// return true;
// }
return super.onOptionsItemSelected(item);
}
//toast message function
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT) .show();
}
}
You have trouble with file exchange not with BLE.
Did you ever read Android FileUriExposedException?
I want to make an application which can speak a different language, the text of which which will be written in a text field, which may be English, Bengali or any other language. I use this code but can not speak in different language. It is always speaking in English or which language I set in Google-Text-speech from phone setting.
Here is my java code
package com.example.texttospeech;
import android.util.Log;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnClickListener {
TextToSpeech tts;
EditText input;
TextView TextCount;
Button b1, b2;
Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.editText);
TextCount = (TextView) findViewById(R.id.TextCount);
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
tts = new TextToSpeech(this, this);
TextCountNow();
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
String text = input.getText().toString();
if (text.isEmpty()) {
String EmptyText = "Nothing found in text fild. please Write something to read.";
tts.speak(EmptyText, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(MainActivity.this, "Text is empty", Toast.LENGTH_LONG).show();
} else if (text.length() > 5000) {
String FaildText = "Text Ought of length. Maximum length is 5000. Please remove some text and try again";
tts.speak(FaildText, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(getApplicationContext(), "Ought of length. Maximum length is 5000.", Toast.LENGTH_LONG).show();
} else {
String ReadingText = text + ". Text reading completed";
tts.speak(ReadingText, TextToSpeech.QUEUE_FLUSH, null);
}
break;
case R.id.button1:
input.setText("");
break;
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
#SuppressWarnings("deprecation")
Locale bahasa = tts.getLanguage();
int result = tts.setLanguage(bahasa);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(MainActivity.this, "This Language is not supported", Toast.LENGTH_SHORT).show();
Log.e("TTS", "This Language is not supported");
} else {
//do nathing
}
} else {
Log.e("TTS", "initialization faild");
}
}
public void TextCountNow(){
final Handler h = new Handler();
Runnable r = new Runnable() {
public void run() {
int textLanth = input.getText().length();
TextCount.setText("" + textLanth);
h.postDelayed(this, 500);
}
};
h.postDelayed(r, 500);
}
}
For Bengali Language :
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
int result = textToSpeechService.setLanguage(new Locale("bn"));
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED
) {
Toast.makeText(mContext, "Speech Service Not Ready", Toast.LENGTH_SHORT).show();
} else {
textToSpeechService.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
stopBanglaReading();
}
#Override
public void onError(String utteranceId) {
}
});
int voicePitch = settings.getInt("ExplVoicePitch", 10);
int voiceSpeed = settings.getInt("ExplVoiceSpeed", 8);
textToSpeechService.setSpeechRate((float) voiceSpeed / 10);
textToSpeechService.setPitch((float) voicePitch / 10);
startSpeaking(onubad);
}
} else {
Toast.makeText(mContext, "Speech Service Not Ready, Please Try Again....", Toast.LENGTH_LONG).show();
}
}
});
I'm totally new to Android and I decided to create a Siri look-a-like app, which is working fine, I searched before asking but I can't get it to work: Android speech Recognition App Without Pop Up
So I want to hide the pop-up inside my Android app, but I really don't now how to do it properly. I'll be very glad if someone could help me doing this. I have already added the correct permissions in Android Manifest...
Here is my full source:
/**
* Giovanni Terlingen
* PWS Project
* 3 november 2014
* Original file from http://github.com/gi097/PWS
*/
package nl.giovanniterlingen.pws;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity implements OnInitListener {
private static final String TAG = "PWS";
private TextView result;
private TextToSpeech tts;
private Button speak;
private int SPEECH_REQUEST_CODE = 1234;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
speak = (Button) findViewById(R.id.bt_speak);
speak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRecognizeIntent();
}
});
speak.setEnabled(false);
result = (TextView) findViewById(R.id.tv_result);
tts = new TextToSpeech(this, this);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
speak.setEnabled(true);
} else {
// failed to init
finish();
}
}
private void sendRecognizeIntent() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Aan het luisteren...");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 100);
startActivityForResult(intent, SPEECH_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SPEECH_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (matches.size() == 0) {
tts.speak("Ik heb niks gehoord, probeer het nog eens",
TextToSpeech.QUEUE_FLUSH, null);
} else {
String mostLikelyThingHeard = matches.get(0);
result.setText("Dit heeft u gezegd: "
+ mostLikelyThingHeard + ".");
mostLikelyThingHeard = mostLikelyThingHeard.toLowerCase();
boolean found = false;
String[] groeten = { "hallo", "heey", "hoi", "hey", "he",
"hee", "hay" };
for (String strings : groeten) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Hey leuk dat je er bent!",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] okay = { "oké, oke, ok, okay, okee" };
for (String strings : okay) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Okiedokie!",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] vragen = { "hoe gaat het", "hoe gaat het met je", "hoe gaat het met jou", "hoe gaat het met u", "hoe is het"};
for (String strings : vragen) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Met mij gaat het altijd goed, met jou?",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] wie = { "wie ben", "hoe heet je", "hoe heet jij", "wat is je naam", "wat is uw naam"};
for (String strings : wie) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Ik ben PWS, ik ben gemaakt als profielwerkstuk door Giovanni Terlingen.",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] leeftijd = { "hoe oud ben" };
for (String strings : leeftijd) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Ik ben op 3 november 2014 van start gegaan dus dat mag je zelf uitrekenen",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] lachen = { "haha", "hah", "ha" };
for (String strings : okay) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Haha leuk grapje",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
if (!found) {
String doei = "doei";
if (mostLikelyThingHeard.equals(doei)) {
tts.speak("Okay tot de volgende keer!",
TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak("Ik begrijp niet wat je bedoeld met "
+ mostLikelyThingHeard
+ " probeer het anders te verwoorden.",
TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
} else {
Log.d(TAG, "result NOT ok");
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onDestroy() {
if (tts != null) {
tts.shutdown();
}
super.onDestroy();
}
}
Step 1
In Android Manifest.xml, add the permission.
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Step 2
In the Layout screen, i am using a Toggle Button to start/stop voice listening.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
.......
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:text="ToggleButton" />
......
</RelativeLayout>
Step 3 - Activity Class
package com.example.voice;
import java.util.ArrayList;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;
public class VoiceRecognitionActivity extends Activity implements
RecognitionListener {
private TextView returnedText;
private ToggleButton toggleButton;
private SpeechRecognizer speech = null;
private Intent recognizerIntent;
private String LOG_TAG = "VoiceRecognitionActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
returnedText = (TextView) findViewById(R.id.textView1);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,
"en");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
speech.startListening(recognizerIntent);
} else {
speech.stopListening();
}
}
});
}
#Override
public void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
if (speech != null) {
speech.destroy();
Log.i(LOG_TAG, "destroy");
}
}
#Override
public void onBeginningOfSpeech() {
Log.i(LOG_TAG, "onBeginningOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.i(LOG_TAG, "onBufferReceived: " + buffer);
}
#Override
public void onEndOfSpeech() {
Log.i(LOG_TAG, "onEndOfSpeech");
toggleButton.setChecked(false);
}
#Override
public void onError(int errorCode) {
String errorMessage = getErrorText(errorCode);
Log.d(LOG_TAG, "FAILED " + errorMessage);
returnedText.setText(errorMessage);
toggleButton.setChecked(false);
}
#Override
public void onEvent(int arg0, Bundle arg1) {
Log.i(LOG_TAG, "onEvent");
}
#Override
public void onPartialResults(Bundle arg0) {
Log.i(LOG_TAG, "onPartialResults");
}
#Override
public void onReadyForSpeech(Bundle arg0) {
Log.i(LOG_TAG, "onReadyForSpeech");
}
#Override
public void onResults(Bundle results) {
Log.i(LOG_TAG, "onResults");
ArrayList<String> matches = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String text = "";
for (String result : matches)
text += result + "\n";
returnedText.setText(text);
}
#Override
public void onRmsChanged(float rmsdB) {
Log.i(LOG_TAG, "onRmsChanged: " + rmsdB);
}
public static String getErrorText(int errorCode) {
String message;
switch (errorCode) {
case SpeechRecognizer.ERROR_AUDIO:
message = "Audio recording error";
break;
case SpeechRecognizer.ERROR_CLIENT:
message = "Client side error";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
message = "Insufficient permissions";
break;
case SpeechRecognizer.ERROR_NETWORK:
message = "Network error";
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
message = "Network timeout";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
message = "No match";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
message = "RecognitionService busy";
break;
case SpeechRecognizer.ERROR_SERVER:
message = "error from server";
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
message = "No speech input";
break;
default:
message = "Didn't understand, please try again.";
break;
}
return message;
}
}