How to get sofar downloaded byte? - android

I use this library For downloading files , It is awesome library , but i need sofar downloaded byte (its parameter of progress) in the oncreate for updating the progress bar in onCreate.
This is My code :
public class MainActivity extends AppCompatActivity {
private Button btnDownload;
private ProgressBar prgDownload;
private int downloadId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
////////////////////////////////////////////////////////////
//================== Init Views ===========
////////////////////////////////////////////////////////////
btnDownload = (Button) findViewById(R.id.btnDownload);
prgDownload = (ProgressBar) findViewById(R.id.prgDownload);
final String savePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "angry.apk";
final String url = "http://dl2.soft98.ir/mobile/Angry.Birds.Rio.2.6.1_Soft98.iR.apk";
////////////////////////////////////////////////////////////
//================== Init Download Manager ===========
////////////////////////////////////////////////////////////
btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadId = createDownloadTask(url,savePath).start();
}
});
}
////////////////////////////////////////////////////////////
//================== Start Download Manager ===========
////////////////////////////////////////////////////////////
private BaseDownloadTask createDownloadTask(final String url , final String savePath){
return FileDownloader.getImpl().create(url)
.setPath(savePath)
.setListener(new FileDownloadListener() {
#Override
protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
Toast.makeText(MainActivity.this, "We are in pending ... ", Toast.LENGTH_SHORT).show();
}
#Override
protected void started(BaseDownloadTask task) {
super.started(task);
}
#Override
=====> protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
prgDownload.setMax(totalBytes);
prgDownload.setProgress(soFarBytes);
btnDownload.setText("Stop");
btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FileDownloader.getImpl().pause(downloadId);
}
});
}
#Override
protected void completed(BaseDownloadTask task) {
Toast.makeText(MainActivity.this, "Download is Completed !!!", Toast.LENGTH_SHORT).show();
btnDownload.setText("Open");
}
#Override
protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
btnDownload.setText("Resume");
btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDownloadTask(url, savePath).start();
Toast.makeText(MainActivity.this, "Resume", Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void error(BaseDownloadTask task, Throwable e) {
Toast.makeText(MainActivity.this, "We have Error !!!", Toast.LENGTH_SHORT).show();
}
#Override
protected void warn(BaseDownloadTask task) {
Toast.makeText(MainActivity.this, "We have warn !!!", Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
FileDownloader.getImpl().pause(downloadId);
}
}

Related

I use liulishuo.filedownloader.File downloaded but not write phone storage where am i making a mistake?

i use liulishuo.filedownloader library in the android application. In completed method toast showing on-screen when the activity starts but not writing in phone or emulator storage. My MainActivity code and Manifest permission code is below where am i making a mistake?
//MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FileDownloader.init(getApplicationContext());
FileDownloader.getImpl().create("https://image.shutterstock.com/image-photo/colorful-flower-on-dark-tropical-260nw-721703848.jpg")
.setPath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString())
.setListener(new FileDownloadListener() {
#Override
protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
}
#Override
protected void started(BaseDownloadTask task) {
}
#Override
protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
}
#Override
protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
}
#Override
protected void blockComplete(BaseDownloadTask task) {
}
#Override
protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
}
#Override
protected void completed(BaseDownloadTask task) {
Toast.makeText(MainActivity.this, "Complete", Toast.LENGTH_SHORT).show();
}
#Override
protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
}
#Override
protected void error(BaseDownloadTask task, Throwable e) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
#Override
protected void warn(BaseDownloadTask task) {
}
}).start();
}
}
//Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />

Android beacon addMonitorNotifier

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

Stuck in this Firebase database in main activity

In this project I am displaying scores from database. When I change the value of scores from the database it changes there but when I check in the app, it doesn't show the change there, and whenever the points gets added through rewarded video ad it doesnt show in the scores.
We need to restart the app to see the video ads point added, and when I change the values from database, it never shows on the app, I think its solution is easy and I am just a beginner.
public class Home_page extends AppCompatActivity implements RewardedVideoAdListener {
TextView score_text;
LinearLayout spin_button, logout_button, redeem_button, watch_video_buuton,share_id,rate_button;
;
private RewardedVideoAd mRewardedVideoAd;
int myIntValue;
DatabaseReference user_id_child;
String user_id;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544/5224354917");
databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
FirebaseAuth mAuth = FirebaseAuth.getInstance();
user_id = mAuth.getCurrentUser().getUid();
user_id_child = databaseReference.child(user_id);
getSupportActionBar().setTitle("Earn Money");
// Admob video ads
MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544/5224354917");
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
spin_button = (LinearLayout) findViewById(R.id.spin_linear_id);
redeem_button = (LinearLayout) findViewById(R.id.linear_redeem_id);
logout_button = (LinearLayout) findViewById(R.id.linear_logout_id);
watch_video_buuton = (LinearLayout) findViewById(R.id.linear_watch_video_id);
share_id = (LinearLayout)findViewById(R.id.linear_share_id);
score_text = (TextView) findViewById(R.id.wallet_text_score_id);
rate_button = (LinearLayout)findViewById(R.id.linear_rate_id);
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
myIntValue = sp.getInt("your_int_key", 0);
rate_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("https://www.instagram.com/dhruv__bhati/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
watch_video_buuton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
else {
loadRewardedVideoAd();
Toast.makeText(Home_page.this , "video ad not loaded ", Toast.LENGTH_LONG).show();
}
}
});
redeem_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Home_page.this, Redeem.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
}
});
logout_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
diaglog();
}
});
spin_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Home_page.this, Spinwheel.class);
intent.putExtra("INT",myIntValue);
startActivity(intent);
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
}
});
share_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
share(view);
}
});
}
#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, menu);//Menu Resource, Menu
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout_id: {
logout();
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(Home_page.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
#Override
public void finish() {
super.finish();
finish();
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(Home_page.this,"Congratulations, you will get 1000 points next time you open the app ", Toast.LENGTH_LONG).show();
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
int n = myIntValue+1000;
editor.putInt("your_int_key", n);
editor.commit();
user_id_child.child("scores").setValue(+n);
watch_video_buuton.setEnabled(false);
final long startTime= Calendar.getInstance().getTime().getTime();
final Timer timer=new Timer();
TimerTask task=new TimerTask() {
#Override
public void run() {
long curentTime=Calendar.getInstance().getTime().getTime();
long elapsedTime=curentTime-startTime;
ToastTime(10*60*1000, elapsedTime);
if(curentTime-startTime>=10*60*1000){ //10 minutes in millisecond
timer.cancel();
watch_video_buuton.setEnabled(true);
}
}
};
timer.schedule(task, 500, 2000);
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
private void loadRewardedVideoAd() {
if(!mRewardedVideoAd.isLoaded()){
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
new AdRequest.Builder().build());
}
}
#Override
public void onResume() {
mRewardedVideoAd.resume(this);
super.onResume();
}
#Override
public void onPause() {
mRewardedVideoAd.pause(this);
super.onPause();
}
#Override
public void onDestroy() {
mRewardedVideoAd.destroy(this);
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
myIntValue = sp.getInt("your_int_key", 0);
String s = String.valueOf(myIntValue);
score_text.setText(s);
loadRewardedVideoAd();
}
public void share(View view){
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Earn Money");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Earn unlimited money by simple tasks"+" "+"https://play.google.com/store/apps/details?id=wheel.top.best.online.money.make.techyunk.com.earningwheel");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
public void diaglog(){
final Dialog dialog = new Dialog(Home_page.this);
dialog.setContentView(R.layout.custom_logout);
Button no = (Button) dialog.findViewById(R.id.no_id);
Button yes = (Button)dialog.findViewById(R.id.yes_id);
// if button is clicked, close the custom dialog
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logout();
}
});
dialog.show();
}
private void ToastTime(long totalTime, long elapsedTime) {
final int remainInSec = (int) (totalTime - elapsedTime) / 1000;
if (remainInSec > 0) {
final Activity activity = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, String.valueOf(remainInSec) + " seconds to enable video button", Toast.LENGTH_SHORT).show();
}
});
}
}
}
As I can see you didn't attach any listener to the Firebase, in your case you need to use addChildEventListener : ChildEventListener.
Be careful and only call this listener once in the onCreate method, If you call it more than once it attaches a new listener then you have two listeners and duplicated data.
UPDATE:
This is the user class you get from the firebase :
public class User {
private String email;
private String name;
private String scores;
public User() {
}
public User(String email, String name, String scores) {
this.email = email;
this.name = name;
this.scores = scores;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScores() {
return scores;
}
public void setScores(String scores) {
this.scores = scores;
}
}
Now let's fetch the data :
firebaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// Here you can handle the new added items.
// if you added a new user you will see it here
User user = dataSnapshot.getValue(User.class);
// Now For example let's log the result
Log.d(TAG, "the user score is : " + user.getScore());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// If you change the score this will appear here :
User user = dataSnapshot.getValue(User.class);
// Here is the new score you can use to update the score in the view
String score = user.getScore();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now go and try this and you will get it.

AdMob rewarded videos always onRewardedVideoAdFailedToLoad

My code is here
I have test it on my device I also integrate this app on firebase.
but it never go to onRewarded it always call onRewardedFaild why sir?
can anyone help me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this,APP_ID);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
// Create the "retry" button, which tries to show an interstitial between game plays.
mRetryButton = ((Button) findViewById(R.id.retry_button));
mRetryButton.setVisibility(View.INVISIBLE);
mRetryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGame();
}
});
// Create the "show" button, which shows a rewarded video if one is loaded.
mShowVideoButton = ((Button) findViewById(R.id.watch_video));
mShowVideoButton.setVisibility(View.INVISIBLE);
mShowVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showRewardedVideo();
}
});
// Display current coin count to user.
mCoinCountText = ((TextView) findViewById(R.id.coin_count_text));
mCoinCount = 0;
mCoinCountText.setText("Coins: " + mCoinCount);
startGame();
}
#Override
public void onPause() {
super.onPause();
pauseGame();
mRewardedVideoAd.pause(this);
}
#Override
public void onResume() {
super.onResume();
if (!mGameOver && mGamePaused) {
resumeGame();
}
mRewardedVideoAd.resume(this);
}
private void pauseGame() {
mCountDownTimer.cancel();
mGamePaused = true;
}
private void resumeGame() {
createTimer(mTimeRemaining);
mGamePaused = false;
}
private void loadRewardedVideoAd() {
if (!mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());
/* AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("40C4DDA8F53FFA9BA5B61261E0CA28AB") // Test devices don't work work with rewarded video ads.
.build();
mRewardedVideoAd.loadAd(AD_UNIT_ID, adRequest);*/
}
}
private void addCoins(int coins) {
mCoinCount = mCoinCount + coins;
mCoinCountText.setText("Coins: " + mCoinCount);
}
private void startGame() {
// Hide the retry button, load the ad, and start the timer.
mRetryButton.setVisibility(View.INVISIBLE);
mShowVideoButton.setVisibility(View.VISIBLE);
loadRewardedVideoAd();
createTimer(COUNTER_TIME);
mGamePaused = false;
mGameOver = false;
}
// Create the game timer, which counts down to the end of the level
// and shows the "retry" button.
private void createTimer(long time) {
final TextView textView = ((TextView) findViewById(R.id.timer));
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
mCountDownTimer = new CountDownTimer(time * 1000, 50) {
#Override
public void onTick(long millisUnitFinished) {
mTimeRemaining = ((millisUnitFinished / 1000) + 1);
textView.setText("seconds remaining: " + mTimeRemaining);
}
#Override
public void onFinish() {
if (mRewardedVideoAd.isLoaded()) {
mShowVideoButton.setVisibility(View.VISIBLE);
}
textView.setText("You Lose!");
addCoins(GAME_OVER_REWARD);
mRetryButton.setVisibility(View.VISIBLE);
mGameOver = true;
}
};
mCountDownTimer.start();
}
private void showRewardedVideo() {
mShowVideoButton.setVisibility(View.INVISIBLE);
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
Toast.makeText(this, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
Toast.makeText(this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();
// Preload the next video ad.
loadRewardedVideoAd();
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
Toast.makeText(this, "onRewardedVideoAdFailedToLoad", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewarded(RewardItem reward) {
Toast.makeText(this,
String.format(" onRewarded! currency: %s amount: %d", reward.getType(),
reward.getAmount()),
Toast.LENGTH_SHORT).show();
addCoins(reward.getAmount());
}
#Override
public void onRewardedVideoStarted() {
Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
I am using my Ad_Unit_ID Live not tested Device ID

onReadyForSpeech() in Android speech recognition (SpeechRecognizer) never gets called

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.

Categories

Resources