Speech recognition supported languages on Android - android

I'm having a problem getting the supported languages. I have seen a solution
that is to create a Broadcast receiver and fill the list with the languages.
public class LanguageChecker extends BroadcastReceiver
{
private List<String> supportedLanguages;
private String languagePreference;
#Override
public void onReceive(Context context, Intent intent)
{
//Log.d(Constants.Tag,"OnReceive");
Bundle results = getResultExtras(true);
if (results.containsKey(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE))
{
languagePreference =
results.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE);
}
if (results.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES))
{
supportedLanguages =
results.getStringArrayList(
RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES);
}
}
public List<String> getSupportedLanguages() {
return supportedLanguages;
}
}
but the problem is that I need this supportedLanguages list to fill my spinner.
When I call the method getSupportedLanguages, I get null.
This is how I use the broadcast within onCreate:
try {
lang = new LanguageChecker();
Intent detailsIntent = new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS);
sendOrderedBroadcast(detailsIntent, null, lang, null, Activity.RESULT_OK, null, null);
supportedLanguagesForSpeech=lang.getSupportedLanguages();
Log.d(Constants.Tag, String.valueOf(supportedLanguagesForSpeech.size()));
}
catch (Exception e){
Log.d(Constants.Tag,e.getMessage());
}

You should solve it with a callback to make sure that supportedLanguages is assigned. You are getting null because you are not waiting onReceive to be called.
Here is my current solution to querying all the available speech recognition services for their supported languages:
https://github.com/Kaljurand/K6nele/blob/3e514edc87e07babb0be57fa31ab48be7e2226e7/app/src/ee/ioc/phon/android/speak/RecognitionServiceManager.java
You can see it in action in the Kõnele app (http://kaljurand.github.io/K6nele/about/), in the "Settings -> Recognition languages & services" list.

Related

How to check screen unlock type of device

I have search a lot but my query not match to it, i found the solution for lock and unlock the phone
Like this way I have created my broadcast with the 3 filters which I recieved:
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.e(TAG, "In Method: ACTION_SCREEN_OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.e(TAG, "In Method: ACTION_SCREEN_ON");
} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.e(TAG, "In Method: ACTION_USER_PRESENT");
}
}
}
I need to find out the way user is unlock screen with it type. if user has unlocked screen by using the password or pattern or fingerprint or by button.
So I am not able to get the particular event from which I can get the follow output.
So kindle help to go in the right direction.
To detect lock pattern I have used below code.So, I think it also help you.you can use Settings.Secure.LOCK_PATTERN_ENABLED flag. Show below:-
private static boolean CheckPatternSet(Context context)
{
ContentResolver contentResolver = context.getContentResolver();
try
{
int lockEnabled = Settings.Secure.getInt(contentResolver, Settings.Secure.LOCK_PATTERN_ENABLED);
return lockEnabled == 1;
}
catch (Settings.SettingNotFoundException e)
{
return false;
}
}
For More understanding you can show below stackoverflow link :-
Android check if lockscreen is set

Android Custom Keyboard with SpeechRecognizer

I have a fully functional custom android keyboard in which i have to add speech recognition. Here are the relevant parts of the implementation i have
public class CustomInputMethodService
extends InputMethodService
implements <random stuff> {
private SpeechRecognizer mSpeechRecognizer;
private RecognitionListener mSpeechlistener;
public void onCreate() {
super.onCreate();
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechlistener = new CustomRecognitionListener();
mSpeechRecognizer.setRecognitionListener(mSpeechlistener);
}
#Override
public void onPress(int primaryCode) {
if (primaryCode == KeyCodes.VOICE_INPUT) {
mSpeechRecognizer.startListening(getSpeechIntent());
}else if(..){
...
}
}
private Intent getSpeechIntent() {
Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
speechIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, false);
return speechIntent;
}
}
The relevant method of the CustomRecognitionListener is simply:
#Override
public void onResults(Bundle results) {
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Log.d(TAG, "onResults: ----> " + matches.get(0));
if(matches != null && matches.size() > 0) {
writeText(matches.get(0));
}
}
This code is working just fine. The twist here is that i want a similar behaviour to what happens on google keyboard when the uset taps the microphone key:
This would ideally by achieved by something like:
Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
try {
startActivityForResult(voiceIntent, Constants.RESULT_SPEECH);
} catch (ActivityNotFoundException ex) {
DebugLog.e(TAG, "Not found excpetion onKeyDown: " + ex);
}
However, since the key listener is on and InputMethodService im not able to call startActivityForResult.
What is the ideal way to accomplish this? Should i simply start a new activity without a layout and have a callback to the inputMethodService? seems messy
Your screenshot shows "Google voice typing", which is an independent IME that is called by the Google Keyboard when its microphone button is pressed. So, your IME should do the same: replace itself with an IME that provides voice typing, and hope that there is a backlink to your IME once the voice typing is done.
The simplest implementation would be Switching among IME Subtypes, but you might want to have more control, e.g. start a specific IME with specific input parameters, etc. I'm not sure what is the best/standard way to achieve this extra control.
For an example of a voice typing IME you could look into (my app) Kõnele.
Simple implementation of the solution:
// on mic tap we call
public void startVoiceListening() {
InputMethodManager imeManager = (InputMethodManager) getApplicationContext().getSystemService(INPUT_METHOD_SERVICE);
String voiceExists = voiceExists(imeManager);
if (voiceExists != null) {
final IBinder token = getWindow().getWindow().getAttributes().token;
imeManager.setInputMethod(token,voiceExists);
}
}
private String voiceExists(InputMethodManager imeManager) {
List<InputMethodInfo> list = imeManager.getInputMethodList();
for (InputMethodInfo el : list) {
// do something to check whatever IME we want.
// in this case "com.google.android.googlequicksearchbox"
}
return null;
}
Once we no longer want to use the current IME just close it and it will fall back to the previous one

Android MMS observer

I have the following code:
public class MmsObserver extends ContentObserver {
private Context context;
public MmsObserver(Handler handler) {
super(handler);
this.context = service.getBaseContext();
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Long largestDateCounted = Long.parseLong(UserPreferencesManager.getInstance().getValueFromPreferences(context, context.getString(R.string.preferences_current_counter), "0"));
String filter = "creator != ? and date > ?";
String[] args = new String[]{context.getPackageName(), Long.toString(largestDateCounted)};
Cursor c = context.getContentResolver().query(Constants.Mms, null, filter, args, null);
try {
} catch (Exception e) {
e.printStackTrace();
} finally {
c.close();
}
}
}
I'm trying to observe when user sends/receives an MMS message. However, my observer never gets called. Is there something I'm missing on this? I have read the below:
Android MMS Monitoring
Android MMS Broadcast receiver
EDIT
here is how i'm running the observer:
mmsContent = new MmsObserver(new Handler());
getContentResolver().registerContentObserver(Constants.Mms, true, mmsContent);
When registering a ContentObserver for MMS, the URI needs to be content://mms-sms/, at least on older Android versions. For some reason, content://mms/ won't work for a ContentObserver, other than possibly firing on changes to draft messages.
Do note that this will cause the Observer to fire for changes to the SMS table, as well.

Android : how to detect language has been changes on phone setting

how could i detect if my phone language has been changed, like facebook application that will give us announce : please wait, we preparing your language
i used myString = Locale.getDefault().getDisplayLanguage();in my onCreate()
on my onCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
String myString = Locale.getDefault().getDisplayLanguage();
if(myString.equals("en"){
ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setMessage("Please wait, we preparing your language");
progressDialog.show();
/*
it will dismiss until the language has been prepared
*/
}else{
//do nothing
}
}
}
please give me suggestion, i still learning, will try harder. thank you.
You can use: ACTION_LOCALE_CHANGED
Here an example:
private BroadcastReceiver mLangReceiver = null;
protected BroadcastReceiver setupLangReceiver(){
if(mLangReceiver == null) {
mLangReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do what you want
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED);
registerReceiver(mLangReceiver, filter);
}
return mLangReceiver;
}
What about to make a broadcast listener to: ACTION_LOCALE_CHANGED
Since "Locale represents a language/country/variant combination. Locales are used to alter the presentation of information such as numbers or dates to suit the conventions in the region they describe."
http://developer.android.com/reference/java/util/Locale.html
Locale.getDefault().getLanguage();
You can use this to get languages in "en"-like format.
Locale.getDefault().getDisplayLanguage(); returns language name e.g. "English" not "en".
This is also useful : https://stackoverflow.com/a/34265899/5515972
Here's a more modern way to get locale changes using Flow. Like others mentioned, we'll need a BroadcastReceiver to receive the Intent.ACTION_LOCALE_CHANGED action. To start, add this function to create the Flow.
private fun getLocaleChangedFlow(context: Context) = callbackFlow {
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
if (intent.action == Intent.ACTION_LOCALE_CHANGED) {
val locale = context?.resources?.configuration?.locales?.get(0)
if (locale != null) {
trySend(locale)
}
}
}
}
context.registerReceiver(receiver, IntentFilter(Intent.ACTION_LOCALE_CHANGED))
awaitClose {
context.unregisterReceiver(receiver)
}
}
Then use the Flow. Replace the TODO() with your own logic:
getLocaleChangedFlow(context)
.onEach {
TODO() // Locale changed, add code here
}
.launchIn(coroutineScope)
To learn more, see these links:
Kotlin docs about callbackFlow
Android docs for Intent.ACTION_LOCALE_CHANGED
StackOverflow answer to Wrap a BroadcastReceiver in a Flow

One of my Application's view inside my second application in android

I got stuck in to the problem where I need to show my first application in to some area of second application's screen. Both codes are under my control. Can any one suggest me where should I proceed as I am not getting any clue about the situation.
if some one help me for the issue, it would be a great help for me.
Or
If I can open both of my applications using the multiscreen option available in S3.
Write a service on either of your application or a individual application. Have AIDL(Android Interface Definition Language) defined as IRemoteService.aidl, the below is my pseudo code or sample implementation. Using this approach you can start activity and handle events of another application through your application.
// IRemoteService.aidl
// Declare any non-default types here with import statements
/** Example service interface */
interface IAccountService {
String getLoggedInUserInfo(String appId);
void userLogin(String appId,ILoginCallback cb);
void signout(String appId);
}
interface ILoginCallback {
void loginSuccess(String userId);
void loginFailed();
}
In your service have some RemoteCallbacks
#Override
public IBinder onBind(Intent intent) {
final RemoteCallbackList<ILoginCallback> mCallbacks = new RemoteCallbackList<ILoginCallback>();
if(mCallbacks!=null){
int i = mCallbacks.beginBroadcast();
while(i>0){
i--;
try {
Log.e(TAG, "Callback ...");
mCallbacks.getBroadcastItem(i).loginSuccess(newUserId);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing
// the dead object for us.
}
}
mCallbacks.finishBroadcast();
}
}
private final IAccountService.Stub mBinder = new IAccountService.Stub() {
#Override
public void userLogin(String appId,ILoginCallback cb) throws RemoteException {
String userId = Settings.getSettings().getUserId();
if(userId ==null||userId.length()==0){
mCallbacks.register(cb);
Intent intent = new Intent(getApplicationContext(), AccountLoginActivity.class);
intent.putExtra("deviceId", Settings.getSettings().getDeviceUniqueId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
You can find detailed AIDL examples in the below links.
http://owenhuangtw.pixnet.net/blog/post/23760257-android-aidl-(android-interface-definition-language)
http://www.app-solut.com/blog/2011/04/using-the-android-interface-definition-language-aidl-to-make-a-remote-procedure-call-rpc-in-android/
https://github.com/afollestad/aidl-example

Categories

Resources