I am using this library CamView from LivotovLabs to scan barcodes. It works as expected however it does not focus for specific phones so I want to implement a focus on touch and my solution is as below. However its not working,the phone does not focus on the barcode.
camera = (ScannerLiveView) findViewById(R.id.camview);
camera.setFocusable(true);
camera.setFocusableInTouchMode(true);
camera.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
camera.requestFocus();
return true;
}
});
camera.setScannerViewEventListener(new ScannerLiveView.ScannerViewEventListener() {
#Override
public void onScannerStarted(ScannerLiveView scanner) {
}
#Override
public void onScannerStopped(ScannerLiveView scanner) {
}
#Override
public void onScannerError(Throwable err) {
Toast.makeText(ACME_Scanner.this, "Scanner Error: " + err.getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeScanned(String data) {
Toast.makeText(ACME_Scanner.this, "Barcode No: "+data, Toast.LENGTH_SHORT).show();
}
});
findViewById(R.id.btnFlash).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toggleFlash();
}
});
findViewById(R.id.btnSkip).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onResume()
{
super.onResume();
ZXDecoder decoder = new ZXDecoder();
decoder.setScanAreaPercent(0.5);
camera.setDecoder(decoder);
camera.startScanner();
}
#Override
protected void onPause()
{
camera.stopScanner();
super.onPause();
}
public void toggleFlash()
{
try {
flashStatus = !flashStatus;
camera.getCamera().getController().switchFlashlight(flashStatus);
}
catch (NullPointerException e){
e.printStackTrace();
}
}
Related
beacon manager.addMonitorNotifier(new MonitorNotifier()
in this method, there are two methods and both are not running .... it is a small app of beacon I want to show the alert .... and that alert in my method in if condition ... but it is not running I did debugger but it is not working
import java.util.Collection;
public class WebViewScreen extends AppCompatActivity implements BeaconConsumer {
public static final String TAG="MainActivity";
private Button startbtn,stopbtn;
private BeaconManager beaconManager=null;
private static final String ALTBEACON_LAYOUT="m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25";
private Region beaconRegion=null;
private void ShowAlert(final String title, final String message){
runOnUiThread (new Thread(new Runnable() {
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(WebViewScreen.this).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}));
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
Log.d(TAG,"on create called");
startbtn=findViewById(R.id.startButton);
stopbtn=findViewById(R.id.stopButton);
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1234);
beaconManager=BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(ALTBEACON_LAYOUT));
beaconManager.bind(this);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startBiconMonitoring();
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopBiconMonitoring();
}
});
}
private boolean entryMessageRaised=false;
private boolean exitMessageRaised=false;
private boolean rangingMessageRaised=false;
private void stopBiconMonitoring() {
Log.d(TAG,"Stop Beacon Monitering");
try {
beaconManager.stopMonitoringBeaconsInRegion(beaconRegion);
beaconManager.stopRangingBeaconsInRegion(beaconRegion);
}catch (RemoteException e){
e.printStackTrace();
}
}
private void startBiconMonitoring() {
Log.d(TAG,"Start Beacon Monitering");
try {
beaconRegion = new Region("My Bicons",Identifier.parse("B9407F30-F5F8-466E-AFF9-25556B57FE6D"),Identifier.parse("4"),Identifier.parse("200"));
beaconManager.startMonitoringBeaconsInRegion(beaconRegion);
beaconManager.startRangingBeaconsInRegion(beaconRegion);
}catch (RemoteException e){
e.printStackTrace();
}
}
private void findID() {
}
#Override
public void onBeaconServiceConnect() {
beaconManager.addMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
if (!entryMessageRaised){
showAlert("didEnterRegion","Entering Region"+region.getUniqueId()+"Beacon Detected UUID/Major/Minor:"+region.getId1()+"/"+region.getId2()+"/"+region.getId3());
entryMessageRaised=true;
}
else {
Log.d(TAG,"somrething go wrong");
}
}
#Override
public void didExitRegion(Region region) {
if (!exitMessageRaised){
showAlert("didExitRegion","Exiting Region"+region.getUniqueId()+"Beacon Detected UUID/Major/Minor:"+region.getId1()+"/"+region.getId2()+"/"+region.getId3());
exitMessageRaised=true;
}
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
});
beaconManager.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
if (rangingMessageRaised && collection != null && !collection.isEmpty()){
for (Beacon beacon:collection){
showAlert("didExitRegion","Ranging Region"+region.getUniqueId()+"Beacon Detected UUID/Major/Minor:"+beacon.getId1()+"/"+beacon.getId2()+"/"+beacon.getId3());
}
rangingMessageRaised=true;
}
}
});
}
}
I want to show the alert if the device will found bacon
I'm trying to implement live stream radio by using fragment and background service, however every time I click to radio button on navigation drawer I couldn't reach the player because it generates one more and I can only control the second one. Here is my fragment class.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_radio, container, false);
init(v);
ApiManager.getInstance().getRadioBroadcast(new ApiResponseLive.GetLiveBroadcastListener() {
#Override
public void onSuccess(StreamModel days) {
turnRadioOn(ApiManager.streamModel);
}
#Override
public void onFailure(String responseString) {
}
});
registerHandler(v);
return v;
}
private void turnRadioOn(StreamModel streamModel) {
HashMap<Integer, ArrayList<GenericStreamItem>> broadcastDays = new HashMap<>();
streamModel.setStreamAllArrays(broadcastDays);
BroadcastPagerAdapter radioPagerAdapter = new BroadcastPagerAdapter(getChildFragmentManager(), getContext(), TAG);
radioPager.setAdapter(radioPagerAdapter);
}
private void init(View v) {
radioPager = (ViewPager) v.findViewById(R.id.broadcastRadioPager);
radioTabLayout = (TabLayout) v.findViewById(R.id.tabsDays);
radioTabLayout.setupWithViewPager(radioPager);
radioPlay = (ToggleButton) v.findViewById(R.id.playButton);
radioScrollView = (ScrollView) v.findViewById(R.id.radioScroll);
}
private void start(String url) {
try {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setDataSource(url);
mp.prepareAsync();
mp.setOnCompletionListener(this);
Log.e("Radio::", "Working");
} catch (Exception e) {
Log.e("StreamAudioDemo", e.getMessage());
e.printStackTrace();
}
}
private void stop() {
try {
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void stopRadio() {
try {
Log.e("stopRadio::", "Pause");
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
}
private void registerHandler(View v) {
radioPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.e("Toggle::", "Enabled");
radioService = new RadioService();
radioService.initMediaPlayer(ApiManager.RADIO_URL);
} else {
Log.e("Toggle::", "Disabled");
stop();
stopRadio();
radioService.onDestroy();
}
}
});
v.findViewById(R.id.radioBroadcast).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
public class RadioService extends Service implements MediaPlayer.OnErrorListener {
public void initMediaPlayer(String url) {
// ...initialize the MediaPlayer here...
ApiManager.getInstance().getRadioURL(new ApiResponseLive.GetTVStreamUrlListener() {
#Override
public void onSuccess(String tvUrl) {
start(ApiManager.RADIO_URL);
mp.setOnErrorListener(RadioService.this);
}
#Override
public void onFailure(String responseString) {
}
});
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// ... react appropriately ...
// The MediaPlayer has moved to the Error state, must be reset!
mp.reset();
return false;
}
#Override
public void onDestroy() {
if (mp != null) mp.release();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
}
Here is how I call fragment:
RadioFragment radioFragment = new RadioFragment();
fragment = fm.findFragmentByTag("radio");
radioDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fragment == null) {
fm.beginTransaction()
.remove(fm.findFragmentById(R.id.activity_content))
.add(R.id.activity_content, radioFragment,
"radio").addToBackStack("main").commit();
} else {
fm.beginTransaction().replace(R.id.activity_content,
radioFragment, "radio");
}
fullView.closeDrawers();
}
});
Here's my code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
SetupButton();
}
private void SetupButton()
{
Button createNewMessage = (Button) findViewById(R.id.button);
createNewMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListenForNewMessage();
}
});
}
private void ListenForNewMessage()
{
final SpeechRecognizer newDeliverySpeech = SpeechRecognizer.createSpeechRecognizer(this);
RecognitionListener newDeliveryRecognitionListener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("SpeechListening","onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.d("SpeechListening","onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsdB) {
//do nothing
}
#Override
public void onBufferReceived(byte[] buffer) {
//do nothing
}
#Override
public void onEndOfSpeech() {
Log.d("SpeechListening","onEndOfSpeech");
}
#Override
public void onError(int error) {
//do nothing
}
#Override
public void onResults(Bundle results) {
ArrayList<String> userMessage;
userMessage = results.getStringArrayList(RESULTS_RECOGNITION);
PushNewDelivery(userMessage);
}
#Override
public void onPartialResults(Bundle partialResults) {
//do nothing
}
#Override
public void onEvent(int eventType, Bundle params) {
//do nothing
}
};
newDeliverySpeech.setRecognitionListener(newDeliveryRecognitionListener);
if (newDeliverySpeech.isRecognitionAvailable(getApplicationContext()))
{
Log.d("SpeechListening","started listening hopefully");
newDeliverySpeech.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
}
}
}
The problem is, only the started listening hopefully is logged, the RecognitionListener never has onReadyForSpeech() or any of its methods called.
Can someone please tell me what I'm doing wrong here?
You can change this below line
newDeliverySpeech.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
To,
Intent mSpeechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "voice.recognition.test");
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
newDeliverySpeech.startListening(mSpeechIntent);
Ask the user for the permission to record audio before calling startListening:
String[] permissions = {Manifest.permission.RECORD_AUDIO};
ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);
https://developer.android.com/guide/topics/media/mediarecorder#audio-record-permission
Here's my code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
SetupButton();
}
private void SetupButton()
{
Button createNewMessage = (Button) findViewById(R.id.button);
createNewMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListenForNewMessage();
}
});
}
private void ListenForNewMessage()
{
final SpeechRecognizer newDeliverySpeech = SpeechRecognizer.createSpeechRecognizer(this);
RecognitionListener newDeliveryRecognitionListener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("SpeechListening","onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.d("SpeechListening","onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsdB) {
//do nothing
}
#Override
public void onBufferReceived(byte[] buffer) {
//do nothing
}
#Override
public void onEndOfSpeech() {
Log.d("SpeechListening","onEndOfSpeech");
}
#Override
public void onError(int error) {
//do nothing
}
#Override
public void onResults(Bundle results) {
ArrayList<String> userMessage;
userMessage = results.getStringArrayList(RESULTS_RECOGNITION);
PushNewDelivery(userMessage);
}
#Override
public void onPartialResults(Bundle partialResults) {
//do nothing
}
#Override
public void onEvent(int eventType, Bundle params) {
//do nothing
}
};
newDeliverySpeech.setRecognitionListener(newDeliveryRecognitionListener);
if (newDeliverySpeech.isRecognitionAvailable(getApplicationContext()))
{
Log.d("SpeechListening","started listening hopefully");
newDeliverySpeech.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
}
}
}
The problem is, only the started listening hopefully is logged, the RecognitionListener never has onReadyForSpeech() or any of its methods called.
details
details
details
details
Can someone please tell me what I'm doing wrong here?
You are basically creating a new SpeechRecognizer object and register a new listener each time you click on the button. On top of that you create the SpeechRecognizer using the current Activity Context but you are actually using the Application context when calling: isRecognitionAvailable();
Try to create the SpeechRecognizer as a member object and register your listener when onCreate() is called. Also try to avoid using the Application context to avoid memory leaks.
Here is an example of how you should do it.
private SpeechRecognizer mDeliverySpeech;
private Intent mSpeechIntent;
private boolean mListening = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
SetupButton();
SetupSpeechRecognizer();
mSpeechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en");
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
}
private void SetupButton()
{
Button createNewMessage = (Button) findViewById(R.id.button);
createNewMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListenForNewMessage();
}
});
}
private void SetupSpeechRecognizer()
{
mDeliverySpeech = SpeechRecognizer.createSpeechRecognizer(this);
RecognitionListener newDeliveryRecognitionListener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("SpeechListening","onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.d("SpeechListening","onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsdB) {
//do nothing
}
#Override
public void onBufferReceived(byte[] buffer) {
//do nothing
}
#Override
public void onEndOfSpeech() {
Log.d("SpeechListening","onEndOfSpeech");
}
#Override
public void onError(int error) {
//do nothing
}
#Override
public void onResults(Bundle results) {
ArrayList<String> userMessage;
userMessage = results.getStringArrayList(RESULTS_RECOGNITION);
PushNewDelivery(userMessage);
}
#Override
public void onPartialResults(Bundle partialResults) {
//do nothing
}
#Override
public void onEvent(int eventType, Bundle params) {
//do nothing
}
};
mDeliverySpeech.setRecognitionListener(newDeliveryRecognitionListener);
}
private void ListenForNewMessage()
{
if (mDeliverySpeech.isRecognitionAvailable(this) && !mListening)
{
Log.d("SpeechListening","started listening hopefully");
mListening = true;
mDeliverySpeech.startListening(mSpeechIntent);
new CountDownTimer(5000, 5000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
mDeliverySpeech.stopListening();
mListening = false;
}
}.start();
}
}
Do not forget to properly handle the activity life cycle when working with listener to avoid memory leak.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View h = getActivity().findViewById(R.id.gohome);
h.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
new Thread(new Runnable() {
public void run() {
Log.w("tt", "tttt");
if(MainActivity.fm.getBackStackEntryCount() > 1) {
try {
MainActivity.fm.popBackStackImmediate("tiles", 0);
}
catch(Exception e) {
Log.w("tt", "tttt" + e);
}
}
//((MainActivity)arg0.getContext()).toggle();
}
}).start();
}
});
}
I have a home button on my app. When clicked, i wanted to return to the fragment names "tiles" which is the bottom most fragment. But this is not working ... plz help