Beacon only detected upon app restart - android

I'm developing an application where users will check-in to the location only when the mobile app is opened. I followed the sample code at https://altbeacon.github.io/android-beacon-library/samples.html, the beacon managed to be scanned.. only when the user clicks the back button on the MainActivity and opens the app again. The app is not able to detect the beacon despite being very close to the device without restarting.
This is my MainActivity code:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, BeaconConsumer {
BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// some code //
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.bind(this);
}
public void onBeaconServiceConnect() {
final String module_code = "FI 3011_ITO P02"; // TODO: replace with latest lecture
final UUID uuid = UUID.nameUUIDFromBytes(module_code.getBytes());
beaconManager.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
for (Beacon beacon : collection) {
// Do something
}
}
});
try {
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
Region region = new Region(uuid.toString(), Identifier.fromUuid(uuid), Identifier.fromInt(1), Identifier.fromInt(2));
beaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (beaconManager.isBound(this)) beaconManager.unbind(this);
}
}
Can somebody please advice me on how should I go about resolving this problem?
Best regards

Related

sometimes both enter and exit method called when user in range

i am new to android developing. i am using Altbeacon lib to detect beacons and i have kontakt.io beacons. i am trying to create an app which is notify user when they enter in Region but when user first time enter the didEnterRegion() method perfectly but after some times didExitRegion() region called even when user in same Region. i am facing some problem when user lost the region and come again it takes too much time to detect user again.
public class MainActivity extends AppCompatActivity implements BeaconConsumer {
protected static final String TAG = "MonitoringActivity";
private BeaconManager beaconManager;
Region region;
String Eddystone_Namespace_ID="f7826da6bc5b71e0893e";
Button next;
Handler ha=new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
beaconManager = BeaconManager.getInstanceForApplication(this);
next=findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,TestingBeacon.class);
startActivity(intent);
}
});
beaconManager.setEnableScheduledScanJobs(false);
beaconManager.setForegroundScanPeriod(2000);
beaconManager.setForegroundBetweenScanPeriod(0);
beaconManager.setBackgroundScanPeriod(200);
beaconManager.setBackgroundBetweenScanPeriod(0);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT));
beaconManager.bind(this);
}
#Override
protected void onResume() {
super.onResume();
region=new Region("myRangingUniqueId", Identifier.parse(Eddystone_Namespace_ID), null, null);
try {
beaconManager.startMonitoringBeaconsInRegion(region);
beaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
}
}
#Override
public void onBeaconServiceConnect() {
beaconManager.addMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
Log.e(TAG, "I just saw an beacon for the first time!");
Toast.makeText(MainActivity.this,"Near By To Beacon",Toast.LENGTH_SHORT).show();
}
#Override
public void didExitRegion(Region region) {
Log.e(TAG, "I no longer see an beacon");
Toast.makeText(MainActivity.this,"Beacon Range Lost",Toast.LENGTH_SHORT).show();
try {
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void didDetermineStateForRegion(int state, Region region) {
Log.e(TAG, "I have just switched from seeing/not seeing beacons: "+state);
}
});
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
for (Beacon beacon : beacons) {
Log.e("MainActivity", "I see a beacon that is about "+beacon.getDistance()+" meters away.");
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.unbind(this);
}
i want user notify when they in region and same with when exit in region.

Is any issue scan long period of Android AltBeacon Library?

I use altbeacon library to scan BLE Kit.
When I use method like this,
#Override
public void onBeaconServiceConnect() {
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
Log.d("BeaconInfo","" + collection.size);
}
});
try {
beaconManager.startRangingBeaconsInRegion(defaultRegion);
} catch (RemoteException e) {
e.printStackTrace();
}
}
It worked normally at first time, but after five minutes or long, It occurs error like, like when I select button to load video file or image file from server, or I reload that activity which is scan BLE Kit, It returns collection size is 0.
I did when do another thing, I should use this method.
private void stopBeacon(){
beaconManager.unbind(this);
}
When I start the App first time, it returns collection size normally but I stay about 3minutues, occurs error.
I don't understand of it
If you know about of it, please help me
BeaconManager beaconManager;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainr);
beaconManager = BeaconManager.getInstanceForApplication(this);
button.setOnClickLister(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveList();
}
});
startBeacon();
}
#Override
public void onBeaconServiceConnect() {
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
Log.d("BeaconInfo","" + collection.size());
}
});
try {
beaconManager.startRangingBeaconsInRegion(defaultRegion);
} catch (RemoteException e) {
e.printStackTrace();
}
}
private void startBeacon(){
beaconManager.bind(this);
}
private void stopBeacon(){
beaconManager.unbind(this);
}
public void moveList(){
stopBeacon();
Intent intent = new Intent(this,ListActivity.class);
startActivity(intent);
finish();
}

onBeaconServiceConnect not called

As before, I work with Android Beacon Library,
It already worked and I can found out beacon via BLE - Bluetooth low energy,
But now, after updated to latest version of library, now method onBeaconServiceConnect() not run anymore.
Please tell me what I need to do to make it works,
Thank you,
p/s : Code :
Manifest.xml
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<service
android:name="org.altbeacon.beacon.service.BeaconService"
android:enabled="true"
android:isolatedProcess="false"
android:label="beacon" />
<service
android:name="org.altbeacon.beacon.BeaconIntentProcessor"
android:enabled="true" />
Java
public class FoundBeaconFragment extends Fragment
implements BeaconConsumer {
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return false;
}
#Override
public Context getApplicationContext() {
return getActivity();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_found_beacon, null);
// Set adapter
foundBeaconAdapter = new FoundBeaconAdapter(
getActivity(),
R.layout.simple_list_item_found_beacon,
mAlFoundBeacon);
mLvFoundBeacon.setAdapter(foundBeaconAdapter);
// Register Scan beacons feature
register();
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
try {
// Unbind scan beacon progress
if (beaconManager != null)
beaconManager.unbind(this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
}
// CUSTOM METHODS
private void register() {
beaconManager = BeaconManager.getInstanceForApplication(getActivity());
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
try {
// todo
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
} catch (Exception e) {
e.printStackTrace();
}
// CAN SEE THIS LOG CAT, NO EXCEPTION
Log.i("", "Register Service");
beaconManager.bind(this);
}
#Override
public void onBeaconServiceConnect() {
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(
Collection<org.altbeacon.beacon.Beacon> beacons, Region region) {
Log.i("", "IS_SCAN_BEACON " + FoundBeaconFragment.IS_SCAN_BEACON);
if (FoundBeaconFragment.IS_SCAN_BEACON) {
Log.i("", "Found " + beacons.size() + " beacon!");
if (beacons.size() > 0) {
/**
* Begin transfer data
*/
for (final org.altbeacon.beacon.Beacon beacon : beacons) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getDataViaBLE(getActivity(), beacon.getId1() + "",
beacon.getId2() + "", beacon.getId3() + "");
}
});
}
}
}
}
});
try {
beaconManager.startRangingBeaconsInRegion(
new Region(Constant.UUID, null, null, null));
} catch (RemoteException e) {
e.printStackTrace();
}
}
public static String UUID = "01122334-4556-6778-899a-abbccddeeff0";
ANSWER
Since I used Fragment not Activity as sample codes from the library.
So I need do these changes :
#Override
public Context getApplicationContext() {
return getActivity().getApplicationContext();
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
getActivity().unbindService(serviceConnection);
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return getActivity().bindService(intent, serviceConnection, i);
}
If you are implementing the BeaconConsumer interface in a Fragment (and not an Activity, Service or Application instance), you need to chain all of the methods. Like this:
#Override
public Context getApplicationContext() {
return getActivity().getApplicationContext();
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
getActivity().unbindService(serviceConnection);
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return getActivity().bindService(intent, serviceConnection, i);
}
I am not sure.before few days ,this beacon code is working for me.please check.if any issue ,i will send whole my code.
try this one:
beaconManager.startRangingBeaconsInRegion(new Region("myBeaons", Identifier.parse(UUID), null, null));
instead of this line in your code.
beaconManager.startRangingBeaconsInRegion(
new Region(Constant.UUID, null, null, null));
this Code is working for me.please try this code:
Create Application Class:
public class BeaconReferenceApplication extends Application implements BootstrapNotifier {
private BackgroundPowerSaver backgroundPowerSaver;
private boolean haveDetectedBeaconsSinceBoot = false;
private MonitoringActivity monitoringActivity = null;
private String UUID = "23542266-18D1-4FE4-B4A1-23F8195B9D39";
private static final String TAG = ".MyApplicationName";
private RegionBootstrap regionBootstrap;
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "App started up");
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
// beaconManager.getBeaconParsers().add(new BeaconParser().
// setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
// wake up the app when any beacon is seen (you can specify specific id filers in the parameters below)
Region region = new Region("com.example.myapp.boostrapRegion", null, null, null);
regionBootstrap = new RegionBootstrap(this, region);
}
#Override
public void didDetermineStateForRegion(int arg0, Region arg1) {
// Don't care
}
#Override
public void didEnterRegion(Region arg0) {
Log.d(TAG, "Got a didEnterRegion call");
// This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched)
// if you want the Activity to launch every single time beacons come into view, remove this call.
regionBootstrap.disable();
Intent intent = new Intent(this, MainActivity.class);
// IMPORTANT: in the AndroidManifest.xml definition of this activity, you must set android:launchMode="singleInstance" or you will get two instances
// created when a user launches the activity manually and it gets launched from here.
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
#Override
public void didExitRegion(Region arg0) {
// Don't care
}
}
Activity Class
public class MainActivity extends Activity implements BeaconConsumer {
public static final String TAG = "BeaconsEverywhere";
private BeaconManager beaconManager;
private String UUID = "23542266-18D1-4FE4-B4A1-23F8195B9D39";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser()
.setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.bind(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.unbind(this);
}
#Override
public void onBeaconServiceConnect() {
final Region region = new Region("myBeaons", Identifier.parse(UUID), null, null);
beaconManager.setMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
try {
Log.d(TAG, "didEnterRegion");
beaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void didExitRegion(Region region) {
try {
Log.d(TAG, "didExitRegion");
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
});
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
for (Beacon oneBeacon : beacons) {
Log.d(TAG, "distance: " + oneBeacon.getDistance() + " id:" + oneBeacon.getId1() + "/" + oneBeacon.getId2() + "/" + oneBeacon.getId3());
}
}
});
try {
beaconManager.startMonitoringBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}

Android WearableListenerService has to be called twice to receive Message

I'm sending a Message from my Wear to the Service from my Handheld.
The first time I'm clicking a button on my handheld is just calling the onCreate method of the Service, the second time the service receives also the message. I can't figure out the problem.
Here is my Wear part:
#Override
public void onClick(View v)
{
final PendingResult<NodeApi.GetConnectedNodesResult> nodes1 = Wearable.NodeApi.getConnectedNodes(mApiClient);
nodes1.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>()
{
#Override
public void onResult(NodeApi.GetConnectedNodesResult result)
{
for (int i = 0; i < result.getNodes().size(); i++)
{
Node node = result.getNodes().get(i);
PendingResult<MessageApi.SendMessageResult> messageResult = Wearable.MessageApi.sendMessage(mApiClient, node.getId(), "/OPEN;"
+ cnt, null);
messageResult.setResultCallback(new ResultCallback<MessageApi.SendMessageResult>()
{
#Override
public void onResult(MessageApi.SendMessageResult sendMessageResult)
{
Status status = sendMessageResult.getStatus();
Log.d("", "##Status: " + status.toString());
if (status.getStatusCode() != WearableStatusCodes.SUCCESS)
{
//not getting there, always success
}
}
});
}
}
});
}
I have following WearableListenerService:
public class DataLayerListenerService extends WearableListenerService implements ConnectionCallbacks, OnConnectionFailedListener
{
private GoogleApiClient mApiClient;
private SharedPreferences prefs;
#Override
public void onCreate()
{
Log.d("", "##DataService created");
super.onCreate();
if (null == mApiClient)
{
mApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this)
.build();
}
if (!mApiClient.isConnected())
{
mApiClient.connect();
Log.d("", "##Api connecting");
}
}
#Override
public void onDestroy()
{
Log.d("", "##DataService destroyed");
if (null != mApiClient)
{
if (mApiClient.isConnected())
{
mApiClient.disconnect();
}
}
super.onDestroy();
}
#Override
public void onMessageReceived(MessageEvent messageEvent)
{
Log.d("", "##DataService received " + messageEvent.getPath());
super.onMessageReceived(messageEvent);
if (messageEvent.getPath().contains("/OPEN;"))
{
// only if called twice :(
}
}
#Override
public void onDataChanged(DataEventBuffer dataEvents)
{
Log.d("", "##DataService Data changed");
}
#Override
public void onConnectionFailed(ConnectionResult arg0)
{
}
#Override
public void onConnected(Bundle arg0)
{
}
#Override
public void onConnectionSuspended(int arg0)
{
}
}
Maybe I also should mention that I ony have to click the button twice when the Service gets destroyed before, which happens some seconds after the click event.
So..in fact this is what happens:
wear click
service oncreate
wear click
service onMessageReceived
wear click
service onMessageReceived
//wait some seconds
service ondestroy
wear click
service oncreate
wear click
service onMessageReceived
Hope this is clear :-)
Thanks in advance!!
I think I may have solved it Phillip Adam - try commenting-out the line in your service in the onMessageReceived() method that makes the call to the superclass. That holds for me. :)
I've been messing with this some more, and if you're still running into the bug of the listener service not firing on the first try, I've found that increasing the timeout interval helps. I had mine set to 10 milliseconds, but making it a larger value seems to have helped.
Check out the code in WearableMainActivity.java in this gist I created for a project. Good luck! :)

Text to Speech not playing sound for first time, but playing for the next time

I am using this kind of text to speech in one of my class in my app(Code edited to show outlook & exact requirement.). I will show some content on my view & if we click the button , I want to play the sound that is by using this texttospeech engine... But for First time it is not playing the sound. From the next click onwards the TEXTTOSPEECH engine is working nicely
Iwant to know how to overcome this issue....
public class LearnActivity extends Activity implements OnClickListener, OnInitListener {
AudioManager audioManager;
float volume;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_learn);
textToSpeech = new TextToSpeech(this, this);
textToSpeech.setLanguage(Locale.US);
textToSpeech.setSpeechRate(0.95f);
method();
}
public void method(){
bt.setonClickListener(new onClickListener(){
public void onClick(View v){
playSound(datasource.getItemSound);
}
});
}
public void playSound(String sound){
textToSpeech.speak(sound,TextToSpeech.QUEUE_FLUSH,null);
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
}
NOTE:- This also meet my Requirement, How to play sound from TEXTTOSPEECH engine directly without using any onClicks etc.,... because I also wants to play a startup sound that too with Android's Text-To-Speech engine only...
That's because you are clicking the button before the engine is ready.
You have to check if the TTS engine has successfully initialized on your onInit() method and enable/disable the play button accordingly.
Assuming that bt in your code is some sort of View that has setEnabled(boolean) method:
#Override
public void onInit(int status) {
bt.setEnabled(status == TextToSpeech.SUCCESS);
}
You always have to assume that the engine has not been initialized and hence keep your play button disabled by default.
I used RXJava to make a class that solves this problem. If your TTS engine is not ready when you want to use the speak method it will wait for the engine to get ready and then speaks the given string.
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Pair;
import android.widget.Toast;
import java.util.Locale;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
public class Pronunciation {
private TextToSpeech textToSpeech;
private int languageResult;
private boolean noError;
private final String errorMessage="Something went wrong with your text to speech engine";
private PublishSubject<Boolean> engineIsReady=PublishSubject.create();
private PublishSubject<Pair<String,Integer>> speakObservable=PublishSubject.create();
private CompositeDisposable compositeDisposable=new CompositeDisposable();
public Pronunciation(Context context) {
textToSpeech=new TextToSpeech(context, status -> {
if (status!=TextToSpeech.ERROR){
languageResult= textToSpeech.setLanguage(Locale.ENGLISH);
engineIsReady.onNext(true);
} else {
Toast.makeText(context,errorMessage
,Toast.LENGTH_LONG).show();
}
});
if (languageResult==TextToSpeech.LANG_MISSING_DATA||languageResult== TextToSpeech.LANG_NOT_SUPPORTED){
noError =false;
Toast.makeText(context,errorMessage
,Toast.LENGTH_LONG).show();
}else { noError =true;}
compositeDisposable.add( Observable.combineLatest(speakObservable, engineIsReady,
(stringIntegerPair, aBoolean) -> stringIntegerPair)
.subscribeOn(Schedulers.io())
.subscribe(pair->{
if (noError)
textToSpeech.speak( (pair).first
,(pair).second,null,null);
}));
}
public void speak(String text,int queueMode){
speakObservable.onNext(new Pair<>(text,queueMode));
}
public void stop(){
if (textToSpeech!=null){
textToSpeech.stop();
textToSpeech.shutdown();
}
compositeDisposable.clear();
}
}
first add RxJava dependency in your Gradle file
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
Then create an instance of this class in the onCreate method of your activity or fragment.Now you can pass the string and queue mode to the speak method.
pronunciation.speak("Hi", TextToSpeech.QUEUE_FLUSH));
Don't forget to call the stop method in onDestroy or onDetach to avoid memory leak
#Override
public void onDetach() {
super.onDetach();
pronunciation.stop();
}
you should write your program ...
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnUtteranceCompletedListener {
TextToSpeech t1;
protected void onCreate(Bundle savedInstanceState) {
t1=new TextToSpeech(MainActivity.this, MainActivity.this);
}/////on creat
protected void onDestroy() {
if(t1!=null) {
t1.stop();
t1.shutdown();
t1=null;
}
super.onDestroy();
}
public void onInit(int arg0) {
t1.setOnUtteranceCompletedListener(this);
}
}//mainactivity
Add this command when button is clicked or everywhere you want to speak text.
t1.speak(text, TextToSpeech.QUEUE_FLUSH, null);
Just Put Delay For 5 Second And It's Working without any button Click
public class Final_Text_To_Speech_Activity extends AppCompatActivity implements TextToSpeech.OnInitListener {
private TextToSpeech tts; // For Text to Speech
CardView ScanProduct, SearchProduct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
init();
// Just Put Delay For 5 Second And It's Working without any button Click
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
SpeakOutOnce("Welcome to Text To Speech Application");
}
}, 5000);
}
#Override
protected void onResume() {
super.onResume();
}
public void init() {
ScanProduct = (CardView) findViewById(R.id.scan_product);
SearchProduct = (CardView) findViewById(R.id.search_product);
// Search On Button Click
ScanProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut("You have Just pressed Scan Option");
}
});
SearchProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut("You have Just pressed Search Option ");
}
});
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
int result = tts.setLanguage(Locale.US);
if (status == TextToSpeech.SUCCESS) {
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
} else {
speakOut("");
}
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
private void speakOut(String text) {
tts.setPitch(1.0f); //Normal Pitch
tts.setSpeechRate(0.7f); // 1.0 is Normal speech Rate
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
private void SpeakOutOnce(String text) {
if (tts != null) {
tts.setPitch(1.0f); //Normal Pitch
tts.setSpeechRate(0.7f); // 1.0 is Normal speech Rate
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}

Categories

Resources