I am trying to create an Android App that can listen to various commands and respond to it accordingly. for e.g, if i press mic and say "open whatsapp", it does it.
Question is How do i open Various apps with limited coding?
following code is to open whatsapp, but if i had to open other various app, Do i need to write same IF Statement for various apps?? wont it be too lenghty?
please provide a better solution.
package example.bot;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends Activity {
private TextView txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
* */
private void promptSpeechInput() {
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,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (result.size() == 0) {
} else {
String mostLikelyThingHeard = result.get(0);
// toUpperCase() used to make string comparison equal
if (mostLikelyThingHeard.toUpperCase().equals("OPEN WHATSAPP")) {
//informationMenu();
txtSpeechInput.setText(result.get(0));
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.whatsapp");
//if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
} //else if()
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
//private void informationMenu() {
// Intent intent = new Intent(this, open_app.class);
// startActivity(intent);
//}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Related
I have been trying to do lock task mode or lock into my app without being able to access other apps with still being able to disable the feature. I have looked at tutorials and documentation but some methods were deprecated since they were made around 5 years ago (onActivityResult). I have tried to change to the new methods (registerForActivityResult) that I found, however when I launch my app and try to enable admin permission by tapping on the enable button, the admin permissions don't pop up, so I cannot check it. So, when I try to lock my phone from other apps nothing happens because I don't have admin permissions.My Code for MainActivity.class below:
package com.example.myapplication;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.myapplication.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.myapplication.helper.MqttHelper;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button lock, disable, enable;
private static final int RESULT_ENABLE = 11;
private DevicePolicyManager devicePolicyManager;
private ActivityManager activityManager;
private ComponentName componentName;
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
MqttHelper mqttHelper;
//ChartHelper mChart;
//LineChart chart;
TextView dataReceived;
private Button btnPublish;
// Allowlist two apps.
private static final String KIOSK_PACKAGE = "com.example.myapplication";
private static final String[] APP_PACKAGES = {KIOSK_PACKAGE};
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//setContentView(R.layout.activity_main);
devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
componentName = new ComponentName(this, Controller.class);
lock = (Button) findViewById(R.id.lock);
enable = (Button) findViewById(R.id.enable);
disable = (Button) findViewById(R.id.disable);
lock.setOnClickListener(this);
enable.setOnClickListener(this);
disable.setOnClickListener(this);
dataReceived = (TextView) findViewById(R.id.textview_first);
startMqtt();
}
#Override
protected void onResume() {
super.onResume();
boolean isActive = devicePolicyManager.isAdminActive(componentName);
}
#Override
public void onClick(View view) {
if (view == lock) {
boolean active = devicePolicyManager.isAdminActive(componentName);
if(active) {
devicePolicyManager.lockNow();
} else {
Toast.makeText(this, "You need to enable the Admin Device Features", Toast.LENGTH_SHORT).show();
}
} else if (view == enable) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"You Should Enable the app!");
//someActivityResultLauncher.launch(intent);
// Caller
mGetContent.launch(intent);
// Receiver
//startActivityForResult(intent, RESULT_ENABLE);
} else if (view == disable) {
devicePolicyManager.removeActiveAdmin(componentName);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
}
ActivityResultLauncher<Intent> mGetContent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// Here, no request code
Intent data = result.getData();
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode== Activity.RESULT_OK && requestCode == RESULT_ENABLE){
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
/*#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case RESULT_ENABLE:
if(resultCode== Activity.RESULT_OK ){
//btn_unblock.setText("Dissable");
//btn_block.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}*/
#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
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
// MQTT Code
private void startMqtt(){
mqttHelper = new MqttHelper(getApplicationContext());
mqttHelper.mqttAndroidClient.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean b, String s) {
Log.w("Debug","Connected");
}
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Debug",mqttMessage.toString());
dataReceived.setText(mqttMessage.toString());
//mChart.addEntry(Float.valueOf(mqttMessage.toString()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}
}
after logging into an account in my webview application, it automatically exits the account 5 minutes after closing the application. Can anyone help with this? I need to solve this problem.
Hello, after logging into an account in my webview application, it automatically exits the account 5 minutes after closing the application. Can anyone help with this? I need to solve this problem
package com.igtr.webview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.KeyEvent;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public void onBackPressed(){
if(websitem.canGoBack()){
websitem.goBack();
}else {
final Dialog exitDialog=new Dialog(MainActivity.this);
exitDialog.getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
exitDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
exitDialog.setCancelable(false);
exitDialog.setContentView(R.layout.cikis_diyalog);
Button evetBtn=exitDialog.findViewById(R.id.evetBtn);
Button hayirBtn=exitDialog.findViewById(R.id.hayirBtn);
evetBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
System.exit(0);
}
});
hayirBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
exitDialog.dismiss();
}
});
exitDialog.show();
}
}
private SwipeRefreshLayout swipeRefreshLayout;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
private Object ValueCallback;
#SuppressLint("SetJavaScriptEnabled")
WebView websitem;
Context context;
ImageView noconnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.sitem);
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new com.panelimws.webview.FullScreenClient(MainActivity.this){
#Override
public void onHideCustomView() {
hideFullScreen(webView);
}
#Override
public Bitmap getDefaultVideoPoster() {
return videoBitmap();
}
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
showFullScreen(view,callback);
}
});
goster();
yukle();
noconnection = (ImageView) findViewById(R.id.noconnection);
if (!isConnected()){
noconnection.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "İnternet Bağlantısı Bulunamadı",Toast.LENGTH_SHORT).show();
}
else{Toast.makeText(MainActivity.this, "Dünya'nın 1 Numaralı SMM Paneline Hoşgeldiniz!",Toast.LENGTH_SHORT).show();
}
}
public void goster(){
websitem=findViewById(R.id.sitem);
}
public void yukle(){
swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
websitem.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
});
websitem.getSettings().setJavaScriptEnabled(true);
websitem.getSettings().setBuiltInZoomControls(true);
websitem.getSettings().setSupportZoom(true);
websitem.loadUrl("url");
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
websitem.reload();
}
});
websitem.setWebChromeClient(new WebChromeClient()
{
// For 3.0+ Devices (Start)
// onActivityResult attached before constructor
protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
intent = fileChooserParams.createIntent();
}
try
{
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e)
{
uploadMessage = null;
return false;
}
return true;
}
//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
} else if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
private static class xWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && websitem.canGoBack()) {
websitem.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private boolean isConnected(){
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo()!=null && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
Here is my mainactivity code i waiting your help.
I tried but didn't work.
I have a problem. I got a simple clicker here, but the "upgraded clicks per tap" are not transferred to the other activity. I don't know why it is not working.
Code as below :
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CODE_CURRENTCLICKS = 10;
public int amountClicks = 0;
public int incrementAmount = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnClick = (Button) findViewById(R.id.btnClick);
final TextView tvAmountClicks = (TextView) findViewById(R.id.tvAmoutClicks);
Button btnShop = (Button) findViewById(R.id.btnShop);
amountClicks = getIntent().getIntExtra("currentClicks", 0);
incrementAmount = getIntent().getIntExtra("upgradedClicks", 1);
tvAmountClicks.setText(""+amountClicks);
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
amountClicks += incrementAmount;
tvAmountClicks.setText(""+amountClicks);
}
});
btnShop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ShopActivity.class);
intent.putExtra("currentClicks",amountClicks);
startActivityForResult(intent, REQUEST_CODE_CURRENTCLICKS);
}
});
}
}
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class ShopActivity extends AppCompatActivity {
public int currentClicks;
public int incrementAmount;
public int upgradedClicks;
public int upgradeCost = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);
currentClicks = getIntent().getIntExtra("currentClicks",0);
final TextView tvCurrentClicks = (TextView) findViewById(R.id.tvCurrentClicks);
tvCurrentClicks.setText(""+currentClicks);
Button btnUpgrade = (Button) findViewById(R.id.btnUpgrade);
btnUpgrade.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(upgradeCost > currentClicks)
{
Context context = getApplicationContext();
CharSequence text = "You don't have enough Clicks";
int duration = Toast.LENGTH_SHORT;
Toast cantUpgrade = Toast.makeText(context, text,duration);
cantUpgrade.show();
}
else
{
currentClicks -= upgradeCost;
upgradedClicks++;
tvCurrentClicks.setText(""+ currentClicks);
}
Intent intent = new Intent();
intent.putExtra("currentClicks",currentClicks);
intent.putExtra("upgradedClicks",upgradedClicks);
setResult(RESULT_OK, intent);
}
});
}
}
If I return back to the main activity, it doesnt return the "upgraded clicks" nor the "current clicks".
You have startActivityForResult therefore you need to implement onActivityResult
So, you have this code
Intent intent = new Intent();
intent.putExtra("currentClicks",currentClicks);
intent.putExtra("upgradedClicks",upgradedClicks);
setResult(RESULT_OK, intent);
finish(); // Add finish() to end this Activity
And that would go back to the calling Activity where you check the request code.
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CODE_CURRENTCLICKS = 10;
public int amountClicks = 0;
private TextView tvAmountClicks;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST_CODE_CURRENTCLICKS) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
amountClicks = data.getIntExtra("currentClicks", 0);
int upgradedClicks = data.getIntExtra("upgradedClicks", 1);
tvAmountClicks.setText(""+amountClicks);
}
}
}
Android | Getting the result of an Activity
You should override the MainActivity's onResume() method to refresh your data.
EDIT try this one
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
amountClicks = getIntent().getIntExtra("currentClicks", 0);
incrementAmount = getIntent().getIntExtra("upgradedClicks", 1);
tvAmountClicks.setText(""+amountClicks);
}
}
}
I am working on app that take the audio of the user and save them in an arrayList, then searching this array list to see if the desired word generated by the google audio API exists, so we can do actions. The action that I wanted is removed and replace it with a textview just to see if it is work properly, the audio recog is working properly, but I always got the textview text as stop. So what is the problem ?
package myfirstapp.myapps.me.voicerecognition;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
ListView lv;
Button recBtn;
static final int check = 1111;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
recBtn = (Button) findViewById(R.id.recBtn);
tv = (TextView) findViewById(R.id.textView);
recBtn.setOnClickListener(MainActivity.this);
}
public void onClick(View v) {
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak");
startActivityForResult(i, check);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == check && resultCode == RESULT_OK) {
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
lv.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, results));
String s = "start";
for (String string : results) {
// if(string.matches("start"))
// tv.setText("Ok");
// else
// tv.setText("No start");
// }
if (string.startsWith(s))
tv.setText("Start");
else
tv.setText("Stop");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
You don't break from the loop when you find a match, so unless the match is in the last String of the list, the text view will contain Stop at the end.
You might want to change it to :
boolean match = false;
for (String string : results) {
if (string.startsWith(s)) {
tv.setText("Start");
match = true;
break;
}
}
if (!match)
tv.setText("Stop");
So I'm following tutorials and below is my code. I'm stuck trying to figure out what I need to with the data path. Does anyone have an example or suggestion on how to take the bitmap photo I took and get it loaded into tesseract to analyze? All help appreciated.
package com.example.cameraocr;
import java.io.File;
import com.googlecode.tesseract.android.TessBaseAPI;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private static ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
protected static void identifyunicode() {
// DATA_PATH = Path to the storage
// lang for which the language data exists, usually "eng"
File myDir = getExternalFilesDir(Environment.MEDIA_MOUNTED);
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(myDir, "eng");
}
}
take a look at my example:
https://github.com/akiwarheit/plug-notes-android/blob/master/src/com/plug/note/NoteEditorActivity.java
What I did was call the camera, take a photo, get the photo and pass it to my OCRTask class (an AsyncTask) which calls the TessBaseAPI
public void callCamera() {
Log.d(TAG, "Starting camera...");
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, REQUEST_OCR);
}
https://github.com/akiwarheit/plug-notes-android/blob/master/src/com/plug/note/OCRTask.java
(A bit long if I post the entire OCRTask class code here, so just read it in Github, maybe?)
And handled the result afterwards
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
/* bunch of other codes */
if (requestCode == REQUEST_OCR) {
if (resultCode == RESULT_OK) {
Bitmap x = (Bitmap) data.getExtras().get("data");
new OCRTask(this, x, this).execute();
}
}
}
I just added the text it recognized to my EditText
#Override
public void onFinishRecognition(String recognizedText) {
noteView.setText(noteView.getText() + " " + recognizedText);
}
Here are the classes
NoteEditor (calls the Camera intent)
OCRTask (calls the TessBaseApi, this is your main concern)
OCRCallback (Adds the text to my EditText after OCRTask finishes)
FileManager (util method)
Hope it helps.