In my activity i am implementing the below given classes
com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks,
com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener,
com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks,
com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener
These two interfaces is for authenticating user through google plus.
com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks,
com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener
and these are for getting user current location
com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks,
com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener
the methods have in these classes are same.
#Override
public void onConnected(Bundle connectionHint) {}
and
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
Since these methods have the same parameters and same return type i cant have two in the same class. So i think i need to identify which interface have invoked from the Bundle or ConnectionResult . How i can do this ? I mean which key value i need to check ? If need any clarification please comment.
Thank you
What about implementing the interfaces as a anonymous member declaration ?
public class Ac {
private GooglePlayServicesClient.OnConnectionFailedListener psConnectionFailedListener =
new GooglePlayServicesClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// implementation
}
};
private GooglePlayServicesClient.ConnectionCallbacks psConnectionCallbacks =
new GooglePlayServicesClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
// implementation
}
#Override
public void onDisconnected() {
// implementation
}
};
private GoogleApiClient.ConnectionCallbacks googleConnectionCallbacks =
new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
// implementation
}
#Override
public void onConnectionSuspended(int i) {
// implementation
}
};
private GoogleApiClient.OnConnectionFailedListener googleConnectionFailedListener =
new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// implementation
}
};
}
Related
I use SpeechRecognizer for implement a "speech-to-text" functional and result of her work is a text data:
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.US.toString());
intent.putExtra("android.speech.extra.EXTRA_ADDITIONAL_LANGUAGES", new String[]{});
SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(getApplicationContext());
recognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {}
#Override
public void onBeginningOfSpeech() {}
#Override
public void onRmsChanged(float rmsdB) {}
#Override
public void onBufferReceived(byte[] buffer) {}
#Override
public void onEndOfSpeech() {}
#Override
public void onError(int error) {}
#Override
public void onPartialResults(Bundle partialResults) {}
#Override
public void onEvent(int eventType, Bundle params) {}
#Override
public void onResults(Bundle results) {
String result = null;
ArrayList<String> arrOfResults = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String command = arrOfResults.get(0);
}
});
recognizer.startListening(intent);
Is it possible to get a transcription of recognized speech instead of text using this method?
For example, as it was implemented in Google Translate:
Or, if necessary, use a different approach.
How can i do this? Thanks in advance. Regards...
The SpeechReocgnizer API only offers the "text" (normal orthographic text, I guess), and optionally the confidence scores, see: https://developer.android.com/reference/android/speech/RecognitionListener.html#onResults(android.os.Bundle)
I have been trying to find a way to implement the SpeechRecognizer API in a Service (runs in background) so that when a condition is met, it will open the speech recognizer without having to be within the application. My question is whether this is even possible natively? And if so, how would it be done?
Here is my code snippet. You can use the recognition listener like this in a service.
I'm not sure how you are scheduling your services, I have left that to you. But you can do something like this. (I have not added code for restarting service / starting it in a timer etc.)
public class MyService extends Service {
protected static SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
Context c;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//if condition is met then do this
SpeechRecognitionListener h = new SpeechRecognitionListener();
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(h);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
Log.d("avail", " " + mSpeechRecognizer.isRecognitionAvailable(this));
if (mSpeechRecognizer.isRecognitionAvailable(this))
Log.d("created", "onBeginingOfSpeech");
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
c= getApplicationContext();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
class SpeechRecognitionListener implements RecognitionListener {
#Override
public void onReadyForSpeech(Bundle bundle) {
Log.d("onReady", "service");
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
Log.d("ERROR","ERROR");
}
#Override
public void onResults(Bundle resultsBundle) {
Log.d("Results", "onResults");
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
}
}
I am currently trying to follow along this tutorial to get last location of android device - https://developer.android.com/training/location/retrieve-current.html#play-services - but I cannot get past the last part.
My code:
package com.example.prouser.driveapp;
public class MainActivity extends AppCompatActivity implements ConnectionCallbacks {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
super.onStart();
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
public void onConnected(Bundle connectionHint) {
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
// Create an instance of GoogleAPIClient.
GoogleApiClient mGoogleApiClient = new GoogleApiClient() {
#Override
public boolean hasConnectedApi(#NonNull Api<?> api) {
return false;
}
#NonNull
#Override
public ConnectionResult getConnectionResult(#NonNull Api<?> api) {
return null;
}
#Override
public void connect() {
}
#Override
public ConnectionResult blockingConnect() {
return null;
}
#Override
public ConnectionResult blockingConnect(long l, #NonNull TimeUnit timeUnit) {
return null;
}
#Override
public void disconnect() {
}
#Override
public void reconnect() {
}
#Override
public PendingResult<Status> clearDefaultAccountAndReconnect() {
return null;
}
#Override
public void stopAutoManage(#NonNull FragmentActivity fragmentActivity) {
}
#Override
public boolean isConnected() {
return false;
}
#Override
public boolean isConnecting() {
return false;
}
#Override
public void registerConnectionCallbacks(#NonNull ConnectionCallbacks connectionCallbacks) {
}
#Override
public boolean isConnectionCallbacksRegistered(#NonNull ConnectionCallbacks connectionCallbacks) {
return false;
}
#Override
public void unregisterConnectionCallbacks(#NonNull ConnectionCallbacks connectionCallbacks) {
}
#Override
public void registerConnectionFailedListener(#NonNull OnConnectionFailedListener onConnectionFailedListener) {
}
#Override
public boolean isConnectionFailedListenerRegistered(#NonNull OnConnectionFailedListener onConnectionFailedListener) {
return false;
}
#Override
public void unregisterConnectionFailedListener(#NonNull OnConnectionFailedListener onConnectionFailedListener) {
}
#Override
public void dump(String s, FileDescriptor fileDescriptor, PrintWriter printWriter, String[] strings) {
}
};
if(mGoogleApiClient==null)
{
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener((OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
Try this:
public class MainActivity extends AppCompatActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
protected static final String TAG = "MainActivity";
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
protected String mLatitudeLabel;
protected String mLongitudeLabel;
protected TextView mLatitudeText;
protected TextView mLongitudeText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mLatitudeLabel = getResources().getString(R.string.latitude_label);
mLongitudeLabel = getResources().getString(R.string.longitude_label);
mLatitudeText = (TextView) findViewById((R.id.latitude_text));
mLongitudeText = (TextView) findViewById((R.id.longitude_text));
buildGoogleApiClient();
}
/**
* Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.format("%s: %f", mLatitudeLabel,
mLastLocation.getLatitude()));
mLongitudeText.setText(String.format("%s: %f", mLongitudeLabel,
mLastLocation.getLongitude()));
} else {
Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
}
You have a complete example here:
https://github.com/googlesamples/android-play-location
For demonstration purposes, the app has one activity that simply offers this:
You click a button, view a rewarded video, and you are rewarded with whatever.
The Problem
How can I load the videos? From what I have seen you can only call mAd.loadAd() once. There are 3 videos, each with their own AD UNIT ID. Each ad unit can have its own listener, but only one video loads so it doesn't matter...
When trying to load multiple videos
For example:
mAd1.loadAd("AD_UNIT_1", new AdRequest.Builder().build());
mAd2.loadAd("AD_UNIT_2", new AdRequest.Builder().build());
mAd3.loadAd("AD_UNIT_3", new AdRequest.Builder().build());
results in only the last video being loaded and this in log:
W/Ads: Loading already in progress, saving this object for future refreshes.
onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAd1 = MobileAds.getRewardedVideoAdInstance(this);
mAd2 = MobileAds.getRewardedVideoAdInstance(this);
mAd3 = MobileAds.getRewardedVideoAdInstance(this);
listeners...
mAd1.loadAd() etc
}
Thank you for your help
Edit: It's clear I am thinking about this problem wrong. I have 5+ ad zones that each will play a rewarded video and give a different reward (for example, one gives coins, one gives a level up, and so on..). There is no reason to load 5 videos. I should load one in onCreate(), so it's ready when needed, then load it again after the item is rewarded so it's ready for next time.
So the question remains, if there is just the one video, and thus one ad zone, being loaded onCreate() then how can I track what reward to give?
Here's a simple solution...
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
#Override
public void onRewarded(RewardItem rewardItem) {
switch(Constants.currentAd) {
case("REWARD1"):
//do something
Constants.currentAd = "";
break;
case("REWARD2"):
//do something
Constants.currentAd = "";
break;
case("REWARD3"):
//do something
Constants.currentAd = "";
break;
}
}
});
mAd.loadAd("REWARDED_VIDEO_UNIT_ID", new AdRequest.Builder().build());
}
public void showRewardedVideo() {
if (mAd.isLoaded()) {
mAd.show();
}
}
Constants.java
public class Constants {
public static String currentAd = "";
}
Showing the ad after button click
rewardButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Constants.currentAd = "REWARD1";
dismiss();
((MainActivity) getActivity()).showRewardedVideo();
}
});
REWARDED_VIDEO_UNIT_ID is one ad unit for rewarded video in AdMob...remove the rest. No need for other units, you can track whatever you like in the listener.
Other simple soluction...
AbstractRewardVideo.java
public abstract class AbstractRewardVideo {
private RewardedVideoAd mAd;
private String adId = "ca-app-pub...";
private Activity activity;
abstract protected RewardedVideoAdListener getListener();
public void init(Activity activity) {
this.activity = activity;
mAd = MobileAds.getRewardedVideoAdInstance(activity);
setAdId(adId);
loadRewardedVideoAd();
}
public Activity getActivity(){
return this.activity;
}
public void loadRewardedVideoAd() {
mAd.loadAd(adId, new AdRequest.Builder().build());
}
public void showVideo(){
setListener(getListener());
if (mAd.isLoaded()) {
mAd.show();
} else {
Utils.exibirToast("Don't loaded!");
}
}
public void setAdId(#NonNull String id){
this.adId = id;
}
public void setListener(RewardedVideoAdListener listener){
mAd.setRewardedVideoAdListener(listener);
}
}
Reward1.java
public class Reward1 extends AbstractRewardVideo {
public Reward1(Activity activity) {
init(activity);
}
#Override
protected RewardedVideoAdListener getListener() {
return new Listener();
}
private class Listener implements RewardedVideoAdListener {
#Override
public void onRewarded(RewardItem rewardItem) {
//Do something...
}
public void onRewardedVideoAdLoaded() {}
public void onRewardedVideoAdOpened() {}
public void onRewardedVideoStarted() {}
public void onRewardedVideoAdClosed() { loadRewardedVideoAd(); }
public void onRewardedVideoAdLeftApplication() {}
public void onRewardedVideoAdFailedToLoad(int i) {}
}
}
Reward2.java
public class Reward2 extends AbstractRewardVideo {
public Reward2(Activity activity) {
init(activity);
}
#Override
protected RewardedVideoAdListener getListener() {
return new Listener();
}
private class Listener implements RewardedVideoAdListener {
#Override
public void onRewarded(RewardItem rewardItem) {
//Do something...
}
public void onRewardedVideoAdLoaded() {}
public void onRewardedVideoAdOpened() {}
public void onRewardedVideoStarted() {}
public void onRewardedVideoAdClosed() { loadRewardedVideoAd(); }
public void onRewardedVideoAdLeftApplication() {}
public void onRewardedVideoAdFailedToLoad(int i) {}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity{
Reward1 reward1;
Reward2 reward2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
reward1 = new Reward1(this);
reward2 = new Reward1(this);
...
reward1.showVideo();
...
reward2.showVideo();
}
}
MobileAds.initialize ( this, "ca-app-pub-4761500786576152~8215465788" );
RewardedVideoAd mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(Video_Ad.this);
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
I try a Toast Message interface. If app not connection internet, I want show a Toast Message and I'm wanting java interfaces.
This is MotherActivity.java. This file implement ToastMessagges.ToastMessaggeCallback
public class MotherActivity extends ActionBarActivity implements ToastMessagges.ToastMessaggeCallback {
ToastMessagges toastMessagges;
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mother);
toastMessagges = new ToastMessagges();
AppStarter();
}
private void AppStarter(){
boolean checkinternet = InternetControl.checkInternetConnection( getApplicationContext() );
if( checkinternet ) {
toastMessagges.show_toast_messagge();
}
else {
}
}
#Override
public void LongToastMessagge() {
Toast.makeText(getApplicationContext(), "Hello World", Toast.LENGTH_LONG).show();
}
}
This is my ToastMessagges.java file.
public class ToastMessagges {
ToastMessaggeCallback toastMessaggeCallback;
public void show_toast_messagge(){
toastMessaggeCallback.LongToastMessagge();
}
public static interface ToastMessaggeCallback {
public void LongToastMessagge();
}
}
When the start this app. I get NullPointerException error.
Caused by: java.lang.NullPointerException
at com.medyasef.bulenttirasnewapp.bulenttiras.functions.ToastMessagges.show_toast_messagge(ToastMessagges.java:22)
at com.medyasef.bulenttirasnewapp.bulenttiras.MotherActivity.AppStarter(MotherActivity.java:36)
at com.medyasef.bulenttirasnewapp.bulenttiras.MotherActivity.onCreate(MotherActivity.java:29)
ToastMessagges.java:22
toastMessaggeCallback.LongToastMessagge();
Sorry bad english.
Please help.
Thank you.
You haven't initialized you ToastMessaggeCallback toastMessaggeCallback.
To do this, write
ToastMessaggeCallback toastMessaggeCallback = new ToastMessaggeCallback(){
public void LongToastMessagge(){
// add some toasting code here
}
};
This will make an object implementing your interface (called "anonymous class"). Of course, your ToastMessaggeCallback should do something in the method LongToastMessagge, so add the desired code there.
I will recommend you to create a Util class instead of Interface. I'm here giving you an example of Util class.
public class Util {
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
}
Then call the showToast() method from your activity as follows...
Util.showToast(YourActivity.this, "text");
Update:
Declare your Interface as a individual, not inside a class as below...
public interface ToastMessaggeCallback {
public void showLongToastMessagge(String text);
}
Then implement the Interface as follows...
public class MotherActivity extends ActionBarActivity implements ToastMessaggeCallback {
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mother);
AppStarter();
}
private void AppStarter(){
boolean checkinternet = InternetControl.checkInternetConnection( getApplicationContext() );
if( checkinternet ) {
showLongToastMessagge("Hello World");
}
else {
}
}
#Override
public void showLongToastMessagge(String text) {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
}
Your ToastMessagges class needs to provide a method to register the callback. Then, your Activity needs to call this method to register itself as the callback, right after you construct the ToastMessages object.