Search code examples
javaandroidvoice-recognition

Voice recognition dialog says network not connected


I'm making an app that uses Voice Recognition. And it works perfectly with Android KitKat 4.4.4 (API 19). But when I try it on Nouget 7.0 (API 24) or Lollipop voice recognition dialog box says Network not connected.

I have internet connection, and I have added permissions in Manifest. What might be the issue?

Here's my Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.woop.loudness">

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".WebList" android:label="@string/app_name" />
    <activity android:name=".AddWeb" android:label="@string/app_name" />
    <!--<service android:enabled="true" android:name=".UartService" />-->
</application>

</manifest>

As requested, my main activity:

public class MainActivity extends AppCompatActivity {

DBHelper myDb;

public int i;
public int b;

private static final int sampleRate = 44100;
private static final int bufferSizeFactor = 10;
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private final int MY_PERMISSIONS_RECORD_AUDIO = 1;

private AudioRecord audio;
private int bufferSize;
private ProgressBar level;
private Handler handler = new Handler();
private int lastLevel = 0;
Button btnView;

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


    myDb = new DBHelper(this);

    btnView = (Button) findViewById(R.id.button2);

    level = (ProgressBar) findViewById(R.id.progressbar_level);
    level.setMax(32676);

    bufferSize = AudioRecord.getMinBufferSize(sampleRate,
            AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT) * bufferSizeFactor;


    requestAudioPermissions();
        //audio.startRecording();

        Thread thread = new Thread(new Runnable() {
            public void run() {
                readAudioBuffer();
            }
        });

        thread.setPriority(Thread.currentThread().getThreadGroup().getMaxPriority());
        thread.start();

        handler.postDelayed(update, 100);


    btnView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MainActivity.this, WebList.class);
            startActivity(intent);
        }
    });
}

private void readAudioBuffer() {
    try {
        short[] buffer = new short[bufferSize];
        int bufferReadResult;
        do {
            bufferReadResult = audio.read(buffer, 0, bufferSize);
            for (int i = 0; i < bufferReadResult; i++){
                if (buffer[i] > lastLevel) {
                    lastLevel = buffer[i];
                }
            }
            // if sound level is over 20000 start voice recognition
            if (lastLevel > 20000){
                lastLevel = 0;
                startVoiceRecognitionActivity();
                Thread.sleep(7000);
            }

        } while (bufferReadResult > 0 && audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void startVoiceRecognitionActivity() {


    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            "Kalbėkite");
    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
        ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

        i = 0;


        if (matches.contains("Add") || matches.contains("add") || matches.contains("Pridėti") || matches.contains("pridėti")) {
            startActivity(new Intent(this, WebList.class));
        }

        if (matches.contains("List") || matches.contains("list") || matches.contains("Sąrašas") || matches.contains("sąrašas")) {
            startActivity(new Intent(this, AddWeb.class));
        }

        // Atidaro internetini puslapi
        Cursor web = myDb.getAllData();
                while (web.moveToNext()) {
                    if (matches.contains(web.getString(2))) {
                        b = i;
                        goToUrl();
                    }
                    i++;
                }
    }
}

private void goToUrl () {
    int temp = 0;
    WebView webview = new WebView(this);
    setContentView(webview);
    Cursor web = myDb.getAllData();
    while (web.moveToNext()) {
        if (temp == b) {
            webview.loadUrl("https://" + web.getString(1));
        }
        temp++;
    }
}

//delete this in final product
private Runnable update = new Runnable() {
    public void run() {
        MainActivity.this.level.setProgress(lastLevel);
        lastLevel *= .5;
        handler.postAtTime(this, SystemClock.uptimeMillis() + 500);
    }
};


private void requestAudioPermissions() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.RECORD_AUDIO)
            != PackageManager.PERMISSION_GRANTED) {

        //When permission is not granted by user, show them message why this permission is needed.
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.RECORD_AUDIO)) {
            Toast.makeText(this, "Please grant permissions to record audio", Toast.LENGTH_LONG).show();

            //Give user option to still opt-in the permissions
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    MY_PERMISSIONS_RECORD_AUDIO);

        } else {
            // Show user dialog to grant permission to record audio
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    MY_PERMISSIONS_RECORD_AUDIO);
        }
    }
    //If permission is granted, then go ahead recording audio
    else if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.RECORD_AUDIO)
            == PackageManager.PERMISSION_GRANTED) {


        audio = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate,
                AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
                bufferSize);
        //Go ahead with recording audio now
        audio.startRecording();
    }
}
}

Solution

  • I have copied your code, you are getting an error, take debug off of the "Selected App"

    Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393237 | Error code: 393222 | couldn't start recording, state is:1

    This is because you are still recording/capturing data in your main activity without releasing the audio, I added it here and it works fine, but do not forget to restart it again

    public void startVoiceRecognitionActivity() {
    
    audio.stop();
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
        RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
        "Kalbėkite");
    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }