-1

So I'm writing a voice assistant app for my final in Intro to Android, and I got most of it to work however I would like the intent for Instagram to open the app not the website. (That would be good enough for now) I have tried several solutions from here to no avail. Ideally, I would like for it to get a list of installed apps and throw those in an array that just responds to the apps name I have the code is as follows, written in Java. Any help will be appreciated.

package com.example.kako;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.text.format.DateUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import static android.text.format.DateUtils.FORMAT_SHOW_TIME;
import static android.text.format.DateUtils.formatDateTime;



public class MainActivity extends AppCompatActivity {

//Requesting run-time permissions

//Create placeholder for user's consent to record_audio permission.

//This will be used in handling callback

private final int MY_PERMISSIONS_RECORD_AUDIO = 1;

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) {

        //Go ahead with recording audio now
        recordAudio();
    }
}

    private TextToSpeech myTTS;
    private SpeechRecognizer mySpeechRecognizer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                        RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
                mySpeechRecognizer.startListening(intent);
            }
        });

        initializeTextToSpeech();
        initializeSpeechRecognizer();
    }


    private void initializeSpeechRecognizer() {
        if(SpeechRecognizer.isRecognitionAvailable(this)){
            mySpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
            mySpeechRecognizer.setRecognitionListener(new RecognitionListener() {
                @Override
                public void onReadyForSpeech(Bundle params) {

                }

                @Override
                public void onBeginningOfSpeech() {

                }

                @Override
                public void onRmsChanged(float rmsdB) {

                }

                @Override
                public void onBufferReceived(byte[] buffer) {

                }

                @Override
                public void onEndOfSpeech() {

                }

                @Override
                public void onError(int error) {

                }

                @Override
                public void onResults(Bundle bundle) {
                    List<String> results = bundle.getStringArrayList(
                        SpeechRecognizer.RESULTS_RECOGNITION
                    );
                    processResult(Objects.requireNonNull(results).get(0));

                }

                @Override
                public void onPartialResults(Bundle partialResults) {

                }

                @Override
                public void onEvent(int eventType, Bundle params) {

                }
            });
        }
    }

    private void processResult(String command) {
        command = command.toLowerCase();

        //what is your name?
        //what is the time?
        //open a browser
        //private browser
        //youtube
        //applications

        if(command.indexOf("what") != -1){
            if(command.indexOf("your name") != -1) {
                speak("Hi! I'm KayKo!");
            }
            if(command.indexOf("time") != -1) {
                Date now = new Date();
                String time = formatDateTime(this, now.getTime(),
                        FORMAT_SHOW_TIME);
                speak("the time is " + time);
            }
            if(command.indexOf("date") != -1) {
                Date now = new Date();
                String date = formatDateTime(this, now.getTime(),
                        DateUtils.FORMAT_SHOW_DATE);
                speak("the Date is " + date);
            }

        }
        else if ( command.indexOf( "open" ) != -1 ) {
            if ( command.indexOf( "browser" ) != -1 ) {
                Intent intent;
                intent = new Intent( Intent.ACTION_VIEW,
                                     Uri.parse( "https://www.google.com/" ) );
                startActivity( intent );

            }
        }
        else if (command.indexOf("private") != -1) {
            if (command.indexOf("browser") != -1) {
                Intent intent;
                intent = new Intent( Intent.ACTION_VIEW,
                                     Uri.parse( "https://duckduckgo.com/" ) );
                startActivity( intent );

            }
        }else if (command.indexOf("youtube") != -1) {
            Intent intent;
            intent = new Intent( Intent.ACTION_VIEW,
                                 Uri.parse( "https://youtube.com/") );
            startActivity( intent );

        }else if (command.indexOf("instagram") != -1) {
            Intent intent;
            intent = new Intent( Intent.ACTION_VIEW,
                                 Uri.parse( "https://www.instagram.com/artsyphotosllc/") );
            startActivity( intent );

        }
    }

    private void initializeTextToSpeech() {
        myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int i) {
                if(myTTS.getEngines().size() ==0){
                    Toast.makeText(MainActivity.this,"There is no TTS engine installed on this device"
                            , Toast.LENGTH_LONG).show();
                    finish();
                } else{
                    myTTS.setLanguage(Locale.getDefault());
                    speak("Ready");
                }

            }
        });
    }

    private void speak(String message){
        if(Build.VERSION.SDK_INT >= 21){
            myTTS.speak(message, TextToSpeech.QUEUE_FLUSH, null, null);
        }else {
            myTTS.speak(message, TextToSpeech.QUEUE_FLUSH, null);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @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) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPause() {
        super.onPause();
        myTTS.shutdown();
    }
}
  • "I have tried several solutions from here to no avail." – Please [edit] your question to show us those attempts, and to explain what problems you had with them, so others don't just repeat the same things here, if they're not going to work for you. – Mike M. Dec 04 '19 at 06:24
  • Apologies, I find that a bit confusing when searching for a solution that works. but I will go back and document some of the other things I have tried when I get a chance. – EntryLevDev Dec 04 '19 at 15:15

1 Answers1

1
PackageManager pm = getPackageManager();

//apps package names

String instagram = "com.instagram.android",
       youtube = "com.google.android.youtube",
       facebook = "com.facebook.katana",
       whatsapp = "com.whatsapp";
       //other apps package names
       // can be found in url of app in play store in the browser
       //ex: https://play.google.com/store/apps/details?id=***com.whatsapp***&hl=en

//launch the app

Intent appIntent = pm.getLaunchIntentForPackage(instagram);//change app package name
if(appIntent != null)
  startActivity(appIntent);
else {
//App not installed !
}
Naveen Avidi
  • 3,004
  • 1
  • 11
  • 23
  • Thank you this is working to launch Instagram, Now I will work on getting all apps installed on a device to populate into an array with the packagename so it doesn't need to be hardcoded. – EntryLevDev Dec 04 '19 at 15:10
  • is there a way to have the program scan the device on load for 3rd party apps, and then put those string names and package names in an array list and then pull from that list so that it would not need to be hardcoded. As every device will have different apps on it? – EntryLevDev Dec 09 '19 at 00:42
  • You can get more details like label, icon etc. https://stackoverflow.com/a/2696617/5557479 – Naveen Avidi Dec 09 '19 at 02:58
  • I could really use some help understanding why the app won't request runtime permissions for the Microphone to record audio. – EntryLevDev Dec 11 '19 at 01:17
  • I didn't see calling requestRuntimePermissions in your activity ? – Naveen Avidi Dec 11 '19 at 02:57
  • It's right under public class MainActivity extends AppCompatActivity { or am I doing something wrong? – EntryLevDev Dec 11 '19 at 03:25
  • I must be doing it wrong can you show me the right way? and I have less than an hour to get it done and turned in. – EntryLevDev Dec 11 '19 at 03:59
  • call requestAudioPermissions() before initializing text to speech ! – Naveen Avidi Dec 11 '19 at 05:00
  • Thanks so much I knew it was something simple. – EntryLevDev Dec 11 '19 at 05:10