Okay, this question has been asked and I have tried all of the solutions provided but none of them seem to work,
I am using a Pubnub tutorial which displays my location in real time on an Android app, I have encountered a few errors that I cannot resolve one mainly been
"Cannot resolve methods requestLocationUpdates"
I have seen in previous posts to add, import android.location.LocationListener; to the imports but it doesnt change anything.
if anybody has any solution to this it would be great, also my other errors if you know.
Main Activity:
package nixerpubcom.nixerpub;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.pubnub.api.PubnubError;
import android.location.LocationListener;
import org.json.JSONException;
import org.json.JSONObject;
import javax.security.auth.callback.Callback;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks {
//Create Google API Client
private GoogleApiClient mGoogleApiClient;
//Create pubnub variable
private Pubnub mPubnub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Start The Google Client
this.buildGoogleApiClient();
mGoogleApiClient.connect();
//Retrieve pubnub keys
mPubnub = new Pubnub ("pub-c-fe4ed754-2b9d-4563-abb6-63c3f048f9ad","sub-c-82de7130-eacb-11e5-8346-0619f8945a4f");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
//Google Api build Method
private synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this).addApi(LocationServices.API)
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Implement the Connection Callback
#Override
public void onConnected(Bundle connectionHint) {
LocationRequest mLocationRequest = createLocationRequest();
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "Connection to Google API Suspended ");
}
private LocationRequest createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return mLocationRequest;
}
#Override
public void onLocationChanged(Location location) {
broadcastLocation(location);
}
private void broadcastLocation(Location location) {
JSONObject message = new JSONObject();
try {
message.put("lat", location.getLatitude());
message.put("lng", location.getLongitude());
message.put("alt", location.getAltitude());
} catch (JSONException e) {
Log.e(TAG, e.toString());
}
mPubnub.publish("A Channel Name", message, publishCallback);
}
KeyEvent.Callback publishCallback = new Callback() {
#Override
public void successCallback(String channel, Object response) {
Log.d("PUBNUB", response.toString());
}
#Override
public void errorCallback(String channel, PubnubError error) {
Log.e("PUBNUB", error.toString());
}
};
}
This is the error I get for the Cannot resolve methods requestLocationUpdates, my other errors are also in there which is a TAG error and a pubnub error
I am new to this so I apologise if the question is no formatted correctly.
In the requestLocationUpdates method:
LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this);
It is expecting that the class that is calling (MainActivity) implements com.google.android.gms.location.LocationListener, so you need to implement it, or change it with an anonymous class:
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Here you have the updated location
}
});
}
The string TAG is not defined in this class, so create a field like this on your class:
private static final String TAG = "MainActivity";
Tip: type "logt" + enter in Android Studio to generate this line.
The callback you want in
KeyEvent.Callback publishCallback = new Callback() {...}
is not from KeyEvent, but from com.pubnub.api.Callback
com.pubnub.api.Callback publishCallback = new Callback() {...}
Please make sure your imports are right and that you asked for location in the manifest:
android.permission.ACCESS_COARSE_LOCATION
or
android.permission.ACCESS_COARSE_LOCATION
Related
I have an android service and I'd like to do the following:
When clicking a button, I start this service, the toast in the onCreate() method always appears but after that I cannot see the longitude-latitude popping up. My main goal is to use this longitude-latitude couple in more activities.
How can I achieve this?
I implemented GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location .LocationListener because I had to wait 20-30 seconds to get the coordinates. The following code works in an activity, but not as a service.
Thanks!
EDITED:
package com.si.ou;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class FullAutoService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location
.LocationListener {
private static final int PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 100;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
String loki;
#Override
public void onCreate() {
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
Toast.makeText(this, "service started....", Toast.LENGTH_SHORT).show();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void startLocationUpdates() {
//noinspection MissingPermission
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission
.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat
.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
private void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
private boolean checkPermissions() {
return ContextCompat.checkSelfPermission(this, android.Manifest.permission
.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (checkPermissions() && mGoogleApiClient.isConnected()) startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
Double lati = location.getLatitude();
Double longi = location.getLongitude();
loki = String.valueOf(lati) + ":" + String.valueOf(longi);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), loki, Toast.LENGTH_SHORT).show();
}
});
}
}
It is because you are working on Service.
Try this:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
getString(R.string.string_id),
Toast.LENGTH_SHORT).show();
}
});
Any UI component can't be accessed from background thread.
If need be arise use handler and sen msg to UI thread and update UI components.
Level
I am a beginner
Task
To run an android service that sends location updates (latitude, longitude) to a database periodically while a driver is driving (to track location) every 5mins. I want to update the database with location even if the app is not active, hence I decided to use the firebase job dispatcher.
Note
I have already seen several threads on how to do this using ALARM_MANAGER or broadcast receivers etc. I would like to know how to do this with a job dispatcher. My current code works but I am pretty sure its not the right way to go about it.
Questions
1. Where do I make a call to build the Googleapi and call the Connect() method? Right now, my scheduler calls a class 'onStart', which in turns performs the connection.
Instead of using the jobScheduler is there any way in which I can use the 'Location Receiver' to do this as I read it takes a time interval, and returns the updated location by overwriting onLocationChanged().
Currently Working Code
The firebase service:-
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
public class GPSTracking extends JobService {
private AsyncTask mBackgroundTask;
public static final String LOG_TAG = "location-scheduler";
#Override
public boolean onStartJob(final JobParameters jobParameters) {
Log.i(LOG_TAG,"Scheduling");
mBackgroundTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] params) {
Context context = GPSTracking2.this;
LocationTracker.execute(context);
return null;
}
#Override
protected void onPostExecute(Object o) {
jobFinished(jobParameters, false);
}
};
mBackgroundTask.execute();
return true;
}
#Override
public boolean onStopJob(JobParameters jobParameters) {
if (mBackgroundTask != null) {
mBackgroundTask.cancel(true);
}
return true;
}
}
The actual tracking:-
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
public class LocationTracker implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private Context context;
private static final String LOG_TAG="LOCATION TRACKER";
public LocationTracker(Context context){
this.context = context;
buildGoogleApiClient();
}
#Override
protected void finalize() throws Throwable {
super.finalize();
//Disconnect
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public static void execute(Context context){
LocationTracker2 track = new LocationTracker2(context);
//connect
track.startConnection();
}
public void startConnection(){
mGoogleApiClient.connect();
}
private static void trackLocation(Location location) {
// To replace with updating database
if (location!=null) {
Log.i("TRACKING LAT", String.valueOf(location.getLatitude()));
Log.i("TRACKING LON", String.valueOf(location.getLongitude()));
}
else
{
Log.i("TRACKING LAT", "Null location received");
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
// Create new location request
// The permission should be granted previously
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
trackLocation(mLastLocation);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(LOG_TAG,"Connection suspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(LOG_TAG,"Connection failed");
}
}
Inside Main, start the scheduling:
Driver driver = new GooglePlayDriver(context);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
Job locationTrackerJob = dispatcher.newJobBuilder()
.setService(GPSTracking.class)
.setTag(JOB_TAG)
.setLifetime(Lifetime.FOREVER)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(
REMINDER_INTERVAL_SECONDS,
REMINDER_INTERVAL_SECONDS + SYNC_FLEXTIME_SECONDS
))
.setReplaceCurrent(true)
.build();
dispatcher.schedule(locationTrackerJob);
NOTE
- You might have to add code to check for permissions depending on the api
- I am leaving out registering the service in Android manifest and dependency in build gradle.
I am trying to use Google SignIn on an app I'm creating. I have been using Google's developer tutorials, but I'm getting the error "Class 'HomeActivity' must either be declared abstract or implement abstract method 'onConnected(Bundle)' in 'ConnectionCallbacks' highlighted under:
public class HomeActivity extends Activity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnClickListener
Here is my HomeActivity code, much of which I used from Google:
import android.app.Activity;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.plus.Plus;
import static android.view.View.*;
public class HomeActivity extends Activity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnClickListener {
private static final int RC_SIGN_IN = 0;
private GoogleApiClient mGoogleApiClient;
private Button mLoginButton;
private TextView mSignUpLabel;
/* Is there a ConnectionResult resolution in progress? */
private boolean mIsResolving = false;
/* Should we automatically resolve ConnectionResults when possible? */
private boolean mShouldResolve = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mLoginButton = (Button) findViewById(R.id.btnLogin);
mLoginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HomeActivity.this, "Button Pressed", Toast.LENGTH_SHORT).show();
}
});
mSignUpLabel = (TextView) findViewById(R.id.lblAboutUs);
mSignUpLabel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HomeActivity.this, "WAY TO SIGN UP MAN", Toast.LENGTH_SHORT).show();
}
});
findViewById(R.id.sign_in_button).setOnClickListener(this);
// Build GoogleApiClient with access to basic profile
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PROFILE))
.build();
}
#Override
public void onConnectionSuspended(int arg0) {
// what should i do here ? should i call mGoogleApiClient.connect() again ? ?
}
#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_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Could not connect to Google Play Services. The user needs to select an account,
// grant permissions or resolve an error in order to sign in. Refer to the javadoc for
// ConnectionResult to see possible error codes.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
if (!mIsResolving && mShouldResolve) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, RC_SIGN_IN);
mIsResolving = true;
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Could not resolve ConnectionResult.", e);
mIsResolving = false;
mGoogleApiClient.connect();
}
} else {
// Could not resolve the connection result, show the user an
// error dialog.
showErrorDialog(connectionResult);
}
} else {
// Show the signed-out UI
showSignedOutUI();
}
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
}
Any help would be much appreciated!!!
Your class declares that it will implement ConnectionCallbacks which means it's obligatory that you define all the methods included in that interface (and all other interfaces that you wish to implement). Both
Android Studio (Click on the light bulb at the left endge) and Eclipse have to ability to automatically implement uninmplemented methods (you will of course have to fill them up with any custom code)
I am using android 5.0.1 and compile my app with API 21.
I want to connect to google play services with the this code:
package com.example.getlocation2;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener{
public GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String tag="test";
Log.i(tag, "just for test");
//buildGoogleApiClient();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
/**
* 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();
mGoogleApiClient.connect();
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the java doc for ConnectionResult to see what error
//codes might be returned in
// onConnectionFailed.
String TAG="Fword";
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
/**
* 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.
String TAG="GoodWord";
Log.i(TAG, "Connectioned");
}
#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.
/*String TAG="Sword";
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();*/
}
}
but it returns connection result code 8 that means: "internal error occurred. Retrying should resolve the problem."
what does this error means and how can I resolve it?
Add this to your gradle build file in the dependencies section.
compile 'com.google.android.gms:play-services:7.0.0'
I am following Google's documentation to implement Google+ Sign In feature into an app.
https://developers.google.com/+/mobile/android/getting-started
I followed each step according to the guide but got stuck in an error generated by the GoogleApiClient.Builder , I searched thoroughly but got no result.
Please help me sort it out. Thank you.
Error code:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
Error Message :
The method addConnectionCallbacks(GoogleApiClient.ConnectionCallbacks) in the type
GoogleApiClient.Builder is not applicable for the arguments (MainActivity)
Complete MainActivity.java code :
package mad.project.mightysatta;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
/* Client used to interact with Google APIs. */
private GoogleApiClient mGoogleApiClient;
/*
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
// return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (!mIntentInProgress && result.hasResolution()) {
try {
mIntentInProgress = true;
result.startResolutionForResult(this, // your activity
RC_SIGN_IN);
} catch (SendIntentException e) {
// The intent was canceled before it was sent. Return to the
// default
// state and attempt to connect to get an updated
// ConnectionResult.
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle connectionHint) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
}
In this code if I comment out .addConnectionCallbacks and .addOnConnectionFailedListener , then the error goes away. The error seems to be related with their arguments.
mGoogleApiClient = new GoogleApiClient.Builder(this)
// .addConnectionCallbacks(this)
// .addOnConnectionFailedListener(this)
.addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
Updated Main Activity , after replacing implements to
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener
MainActivity.java(Updated)
package mad.project.mightysatta;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
public class MainActivity extends ActionBarActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
/* Client used to interact with Google APIs. */
private GoogleApiClient mGoogleApiClient;
/*
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
// return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (!mIntentInProgress && result.hasResolution()) {
try {
mIntentInProgress = true;
result.startResolutionForResult(this, // your activity
RC_SIGN_IN);
} catch (SendIntentException e) {
// The intent was canceled before it was sent. Return to
// default
// state and attempt to connect to get an updated
// ConnectionResult.
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle connectionHint) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
}
I see in their documentation where they clearly instruct you to include this import:
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
However, the error being thrown is expecting a different class than GooglePlayServicesClient.ConnectionCallbacks, it's asking for GoogleApiClient.ConnectionCallbacks. Try changing your implements to use the more-qualified class name. That looks to be the only possible thing throwing the code for a loop and without the explicit qualified classname, it will default to the directly imported class name.
It's always tougher when you have to question the manual.
Edit: I mean a change like this:
public class MainActivity
extends ActionBarActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
I too faced the same problem, i resolved by doing the following things.
import the right ConnectionCallbacks.
here is my code:
import android.content.Context;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
public class GplusLogin implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient mGoogleApiClient;
GplusLogin(Context context){
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) context)
.addOnConnectionFailedListener(this)
.build();
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onConnectionSuspended(int i) {
}
}
turns out they (google) don't follow much of the guide themselves. Use their Google Drive Android Quickstart as a reference, which they actually do mention at the top of the tutorial, but they give it the misleading name "Android Quickstart" even though it is specific to Google Drive
The note at the top of the guide:
click alt enter and force android studio to implement:
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener
implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,OnMapReadyCallback
to the Activity