Google-Fit Sensors API Not Finding Watch - android

I have implemented the Google Fit Sensors API in my project and it does not seem to be finding my watch when scanning for data sources
Here is my code for scanning for data sources
private void findFitnessDataSources() {
Log.i(TAG, "findFitnessDataSources called");
// [START find_data_sources]
// Note: Fitness.SensorsApi.findDataSources() requires the ACCESS_FINE_LOCATION permission.
Fitness.getSensorsClient(this, GoogleSignIn.getLastSignedInAccount(this))
.findDataSources(
new DataSourcesRequest.Builder()
.setDataTypes(DataType.TYPE_HEART_RATE_BPM)
.setDataSourceTypes(DataSource.TYPE_RAW)
.build())
.addOnSuccessListener(
new OnSuccessListener<List<DataSource>>() {
#Override
public void onSuccess(List<DataSource> dataSources) {
Log.i(TAG, "Listener Success");
Log.i(TAG, "DataSources: " + dataSources.size());
for (DataSource dataSource : dataSources) {
Log.i(TAG, "Data source found: " + dataSource.toString());
Log.i(TAG, "Data Source type: " + dataSource.getDataType().getName());
// Let's register a listener to receive Activity data!
if (dataSource.getDataType().equals(DataType.TYPE_HEART_RATE_BPM)
&& mListener == null) {
Log.i(TAG, "Data source for HEART RATE found! Registering.");
registerFitnessDataListener(dataSource);
}
}
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "failed", e);
}
});
// [END find_data_sources]
}
The result is no data sources found. My watch had google fit updated and signed in on the same account as I select in the application. As far as I can tell it is successfully connecting to the API it is simply not reading any sensors to pull information out of. I am, of course, possibly wrong about that. If anyone can shed any light on this it would be much appreciated.
Below is all my code for this activity if it is relevant
public class Test_Page extends AppCompatActivity {
TextView hR;
public static final String TAG = "BasicSensorsApi";
private static final int REQUEST_OAUTH_REQUEST_CODE = 1;
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
// [START mListener_variable_reference]
// Need to hold a reference to this listener, as it's passed into the "unregister"
// method in order to stop all sensors from sending data to this listener.
private OnDataPointListener mListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_page);
hR = findViewById(R.id.heartRate);
// When permissions are revoked the app is restarted so onCreate is sufficient to check for
// permissions core to the Activity's functionality.
if (hasRuntimePermissions()) {
findFitnessDataSourcesWrapper();
} else {
requestRuntimePermissions();
}
}
/**
* A wrapper for {#link #findFitnessDataSources}. If the user account has OAuth permission,
* continue to {#link #findFitnessDataSources}, else request OAuth permission for the account.
*/
private void findFitnessDataSourcesWrapper() {
Log.i(TAG, "findFitnessDataSourcesWrapper called");
if (hasOAuthPermission()) {
findFitnessDataSources();
} else {
requestOAuthPermission();
}
}
/** Gets the {#link FitnessOptions} in order to check or request OAuth permission for the user. */
private FitnessOptions getFitnessSignInOptions() {
Log.i(TAG, "getFitnessSignInOptions calles");
return FitnessOptions.builder().addDataType(DataType.TYPE_HEART_RATE_BPM, FitnessOptions.ACCESS_READ).build();
}
/** Checks if user's account has OAuth permission to Fitness API. */
private boolean hasOAuthPermission() {
Log.i(TAG, "hasOAuthPermission called");
FitnessOptions fitnessOptions = getFitnessSignInOptions();
return GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount(this), fitnessOptions);
}
/** Launches the Google SignIn activity to request OAuth permission for the user. */
private void requestOAuthPermission() {
Log.i(TAG, "requestOAuthPermission called");
FitnessOptions fitnessOptions = getFitnessSignInOptions();
GoogleSignIn.requestPermissions(
this,
REQUEST_OAUTH_REQUEST_CODE,
GoogleSignIn.getLastSignedInAccount(this),
fitnessOptions);
}
#Override
protected void onResume() {
super.onResume();
// This ensures that if the user denies the permissions then uses Settings to re-enable
// them, the app will start working.
findFitnessDataSourcesWrapper();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "onActivityResult called");
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_OAUTH_REQUEST_CODE) {
findFitnessDataSources();
}
}
}
// [END auth_oncreate_setup]
/** Finds available data sources and attempts to register on a specific {#link DataType}. */
private void findFitnessDataSources() {
Log.i(TAG, "findFitnessDataSources called");
// [START find_data_sources]
// Note: Fitness.SensorsApi.findDataSources() requires the ACCESS_FINE_LOCATION permission.
Fitness.getSensorsClient(this, GoogleSignIn.getLastSignedInAccount(this))
.findDataSources(
new DataSourcesRequest.Builder()
.setDataTypes(DataType.TYPE_HEART_RATE_BPM)
.setDataSourceTypes(DataSource.TYPE_RAW)
.build())
.addOnSuccessListener(
new OnSuccessListener<List<DataSource>>() {
#Override
public void onSuccess(List<DataSource> dataSources) {
Log.i(TAG, "Listener Success");
Log.i(TAG, "DataSources: " + dataSources.size());
for (DataSource dataSource : dataSources) {
Log.i(TAG, "Data source found: " + dataSource.toString());
Log.i(TAG, "Data Source type: " + dataSource.getDataType().getName());
// Let's register a listener to receive Activity data!
if (dataSource.getDataType().equals(DataType.TYPE_HEART_RATE_BPM)
&& mListener == null) {
Log.i(TAG, "Data source for HEART RATE found! Registering.");
registerFitnessDataListener(dataSource);
}
}
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "failed", e);
}
});
// [END find_data_sources]
}
/**
* Registers a listener with the Sensors API for the provided {#link DataSource} and {#link
* DataType} combo.
*/
private void registerFitnessDataListener(DataSource dataSource) {
Log.i(TAG, "registerFitnessDataListener called");
// [START register_data_listener]
mListener =
new OnDataPointListener() {
#Override
public void onDataPoint(DataPoint dataPoint) {
for (final Field field : dataPoint.getDataType().getFields()) {
final Value val = dataPoint.getValue(field);
runOnUiThread(new Runnable() {
#Override
public void run() {
hR.setText(val.toString());
}
});
}
}
};
Fitness.getSensorsClient(this, GoogleSignIn.getLastSignedInAccount(this))
.add(
new SensorRequest.Builder()
.setDataSource(dataSource) // Optional but recommended for custom data sets.
.setDataType(DataType.TYPE_HEART_RATE_BPM) // Can't be omitted.
.setSamplingRate(1, TimeUnit.SECONDS)
.build(),
mListener)
.addOnCompleteListener(
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.i(TAG, "Listener registered!");
} else {
Log.e(TAG, "Listener not registered.", task.getException());
}
}
});
// [END register_data_listener]
}
/** Unregisters the listener with the Sensors API. */
private void unregisterFitnessDataListener() {
Log.i(TAG, "unRegisterFitnessDataListener called");
if (mListener == null) {
// This code only activates one listener at a time. If there's no listener, there's
// nothing to unregister.
return;
}
// [START unregister_data_listener]
// Waiting isn't actually necessary as the unregister call will complete regardless,
// even if called from within onStop, but a callback can still be added in order to
// inspect the results.
Fitness.getSensorsClient(this, GoogleSignIn.getLastSignedInAccount(this))
.remove(mListener)
.addOnCompleteListener(
new OnCompleteListener<Boolean>() {
#Override
public void onComplete(#NonNull Task<Boolean> task) {
if (task.isSuccessful() && task.getResult()) {
Log.i(TAG, "Listener was removed!");
} else {
Log.i(TAG, "Listener was not removed.");
}
}
});
// [END unregister_data_listener]
}
/** Initializes a custom log class that outputs both to in-app targets and logcat. */
/** Returns the current state of the permissions needed. */
private boolean hasRuntimePermissions() {
Log.i(TAG, "hasRuntimePermissions called");
int permissionState =
ActivityCompat.checkSelfPermission(this, Manifest.permission.BODY_SENSORS);
return permissionState == PackageManager.PERMISSION_GRANTED;
}
private void requestRuntimePermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(
this, Manifest.permission.BODY_SENSORS);
if (shouldProvideRationale) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
} else {
Log.i(TAG, "Requesting permission");
// Request permission. It's possible this can be auto answered if device policy
// sets the permission in a given state or the user denied the permission
// previously and checked "Never ask again".
ActivityCompat.requestPermissions(
Test_Page.this,
new String[] {Manifest.permission.BODY_SENSORS},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}
/** Callback received when a permissions request has been completed. */
#Override
public void onRequestPermissionsResult(
int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.i(TAG, "onRequestPermissionResult called");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
// If user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i(TAG, "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted.
findFitnessDataSourcesWrapper();
} else {
// Permission denied.
Log.i(TAG, "Permission denied");
}
}
}
}

Related

onDestroy() is called when press home button in video call using agora.io

onDestroy() is called when press home button in video call using agora.io .
I have 2 project one is for user and other for astrologer. In User app everything in working fine but in astrologer app onDestroy is calling whenever I press the home button.
This is refernce for agora
https://github.com/AgoraIO/Basic-Video-Call/tree/master/One-to-One-Video/Agora-Android-Tutorial-1to1
public class VideoChatViewActivity extends AppCompatActivity {
private static final String TAG = VideoChatViewActivity.class.getSimpleName();
private static final int PERMISSION_REQ_ID = 22;
// Permission WRITE_EXTERNAL_STORAGE is not mandatory
// for Agora RTC SDK, just in case if you wanna save
// logs to external sdcard.
private static final String[] REQUESTED_PERMISSIONS = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private RtcEngine mRtcEngine;
private boolean mCallEnd;
private boolean mMuted;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private SurfaceView mLocalView;
private SurfaceView mRemoteView;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
// Customized logger view
/**
* Event handler registered into RTC engine for RTC callbacks.
* Note that UI operations needs to be in UI thread because RTC
* engine deals with the events in a separate thread.
*/
private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("TAG", "Join channel success, uid: " + (uid & 0xFFFFFFFFL));
}
});
}
#Override
public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("TAG", "First remote video decoded, uid: " + (uid & 0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("TAG", "User offline, uid: " + (uid & 0xFFFFFFFFL));
onRemoteUserLeft();
}
});
}
};
private void setupRemoteVideo(int uid) {
// Only one remote video view is available for this
// tutorial. Here we check if there exists a surface
// view tagged as this uid.
int count = mRemoteContainer.getChildCount();
View view = null;
for (int i = 0; i < count; i++) {
View v = mRemoteContainer.getChildAt(i);
if (v.getTag() instanceof Integer && ((int) v.getTag()) == uid) {
view = v;
}
}
if (view != null) {
return;
}
mRemoteView = RtcEngine.CreateRendererView(getBaseContext());
mRemoteContainer.addView(mRemoteView);
mRtcEngine.setupRemoteVideo(new VideoCanvas(mRemoteView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
mRemoteView.setTag(uid);
}
private void onRemoteUserLeft() {
removeRemoteVideo();
}
private void removeRemoteVideo() {
if (mRemoteView != null) {
mRemoteContainer.removeView(mRemoteView);
}
mRemoteView = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
initUI();
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
}
private void initUI() {
mLocalContainer = findViewById(R.id.local_video_view_container);
mRemoteContainer = findViewById(R.id.remote_video_view_container);
mCallBtn = findViewById(R.id.btn_call);
mMuteBtn = findViewById(R.id.btn_mute);
mSwitchCameraBtn = findViewById(R.id.btn_switch_camera);
// Sample logs are optional.
showSampleLogs();
}
private void showSampleLogs() {
Log.e("TAG", "Welcome to Agora 1v1 video call");
}
private boolean checkSelfPermission(String permission, int requestCode) {
if (ContextCompat.checkSelfPermission(this, permission) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQ_ID) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
grantResults[1] != PackageManager.PERMISSION_GRANTED ||
grantResults[2] != PackageManager.PERMISSION_GRANTED) {
showLongToast("Need permissions " + Manifest.permission.RECORD_AUDIO +
"/" + Manifest.permission.CAMERA + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE);
finish();
return;
}
// Here we continue only if all permissions are granted.
// The permissions can also be granted in the system settings manually.
initEngineAndJoinChannel();
}
}
private void showLongToast(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void initEngineAndJoinChannel() {
// This is our usual steps for joining
// a channel and starting a call.
initializeEngine();
setupVideoConfig();
setupLocalVideo();
joinChannel();
}
private void initializeEngine() {
try {
mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
}
private void setupVideoConfig() {
// In simple use cases, we only need to enable video capturing
// and rendering once at the initialization step.
// Note: audio recording and playing is enabled by default.
mRtcEngine.enableVideo();
// Please go to this page for detailed explanation
// https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_rtc_engine.html#af5f4de754e2c1f493096641c5c5c1d8f
mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT));
}
private void setupLocalVideo() {
// This is used to set a local preview.
// The steps setting local and remote view are very similar.
// But note that if the local user do not have a uid or do
// not care what the uid is, he can set his uid as ZERO.
// Our server will assign one and return the uid via the event
// handler callback function (onJoinChannelSuccess) after
// joining the channel successfully.
mLocalView = RtcEngine.CreateRendererView(getBaseContext());
mLocalView.setZOrderMediaOverlay(true);
mLocalContainer.addView(mLocalView);
mRtcEngine.setupLocalVideo(new VideoCanvas(mLocalView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
}
private void joinChannel() {
// 1. Users can only see each other after they join the
// same channel successfully using the same app id.
// 2. One token is only valid for the channel name that
// you use to generate this token.
mRtcEngine.joinChannel(null, getIntent().getExtras().getString("channel_name"), "Extra Optional Data", 0);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy: ");
if (!mCallEnd) {
leaveChannel();
}
RtcEngine.destroy();
}
#Override
protected void onPause() {
super.onPause();
Log.e(TAG, "onPause: ");
}
#Override
protected void onStop() {
super.onStop();
Log.e(TAG, "onStop: ");
}
private void leaveChannel() {
mRtcEngine.leaveChannel();
}
public void onLocalAudioMuteClicked(View view) {
mMuted = !mMuted;
mRtcEngine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_mute;
mMuteBtn.setImageResource(res);
}
public void onSwitchCameraClicked(View view) {
mRtcEngine.switchCamera();
}
public void onCallClicked(View view) {
if (mCallEnd) {
startCall();
mCallEnd = false;
mCallBtn.setImageResource(R.drawable.btn_end_call);
} else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_end_call);
}
showButtons(!mCallEnd);
}
private void startCall() {
setupLocalVideo();
joinChannel();
}
private void endCall() {
removeLocalVideo();
removeRemoteVideo();
leaveChannel();
}
private void removeLocalVideo() {
if (mLocalView != null) {
mLocalContainer.removeView(mLocalView);
}
mLocalView = null;
}
private void showButtons(boolean show) {
int visibility = show ? View.VISIBLE : View.GONE;
mMuteBtn.setVisibility(visibility);
mSwitchCameraBtn.setVisibility(visibility);
}
}
Welcome to codding party.
you should implement
onSaveInstanceState
and
onRestoreInstanceState
properly. The framework may kill your Activity at any time it isn't foreground.
other way u can Use Foreground service for keeping alive your call.

Google Play Services chrash when using Android Nearby Connections

I try to implement a small test application for Googles Nearby Connections API. Unfortunately on 2 of 3 tested devices Google Play Services chrash when discovering or advertising. (OnePlus One, Android 6.1; Acer Iconia, Android 4.4)
I see other devices, but when i connect to one of them play service crash (only my Honor 8 keeps on working). It says the connection is suspendend with error code 1. According to Google this means "A suspension cause informing that the service has been killed."
Maybe some of you could help. I made this code based on this tutorial.
Code without imports:
MainActivity.java
package com.example.steffen.nearbyconnectionsdemo;
public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener,
Connections.ConnectionRequestListener,
Connections.MessageListener,
Connections.EndpointDiscoveryListener {
// Identify if the device is the host
private boolean mIsHost = false;
GoogleApiClient mGoogleApiClient = null;
Button bt_ad, bt_search, bt_send;
TextView tv_status;
CheckBox checkBox;
Context c;
String globalRemoteEndpointId = "";
EditText editText;
final int MY_PERMISSIONS_REQUEST = 666;
private static int[] NETWORK_TYPES = {ConnectivityManager.TYPE_WIFI,
ConnectivityManager.TYPE_ETHERNET};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c = this;
checkPermisson();
editText = (EditText) findViewById(R.id.editText);
bt_ad = (Button) findViewById(R.id.bt_ad);
bt_ad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bt_search.setEnabled(false);
startAdvertising();
}
});
bt_search = (Button) findViewById(R.id.bt_search);
bt_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startDiscovery();
}
});
bt_send = (Button) findViewById(R.id.bt_send);
bt_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "message: " + editText.getText().toString();
Toast.makeText(c, "Sending: " + message, Toast.LENGTH_SHORT).show();
byte[] payload = message.getBytes();
Nearby.Connections.sendReliableMessage(mGoogleApiClient, globalRemoteEndpointId, payload);
}
});
tv_status = (TextView) findViewById(R.id.tv_status);
checkBox = (CheckBox) findViewById(R.id.checkBox);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Nearby.CONNECTIONS_API)
.build();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private boolean isConnectedToNetwork() {
ConnectivityManager connManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
for (int networkType : NETWORK_TYPES) {
NetworkInfo info = connManager.getNetworkInfo(networkType);
if (info != null && info.isConnectedOrConnecting()) {
return true;
}
}
return false;
}
private void startAdvertising() {
if (!isConnectedToNetwork()) {
// Implement logic when device is not connected to a network
tv_status.setText("No Network");
return;
}
// Identify that this device is the host
mIsHost = true;
checkBox.setChecked(mIsHost);
// Advertising with an AppIdentifer lets other devices on the
// network discover this application and prompt the user to
// install the application.
List<AppIdentifier> appIdentifierList = new ArrayList<>();
appIdentifierList.add(new AppIdentifier(getPackageName()));
AppMetadata appMetadata = new AppMetadata(appIdentifierList);
// The advertising timeout is set to run indefinitely
// Positive values represent timeout in milliseconds
long NO_TIMEOUT = 0L;
String name = null;
Nearby.Connections.startAdvertising(mGoogleApiClient, name, appMetadata, NO_TIMEOUT,
this).setResultCallback(new ResultCallback<Connections.StartAdvertisingResult>() {
#Override
public void onResult(Connections.StartAdvertisingResult result) {
if (result.getStatus().isSuccess()) {
// Device is advertising
tv_status.setText("Advertising");
} else {
int statusCode = result.getStatus().getStatusCode();
// Advertising failed - see statusCode for more details
tv_status.setText("Error: " + statusCode);
}
}
});
}
private void startDiscovery() {
if (!isConnectedToNetwork()) {
// Implement logic when device is not connected to a network
tv_status.setText("No Network");
return;
}
String serviceId = getString(R.string.service_id);
// Set an appropriate timeout length in milliseconds
long DISCOVER_TIMEOUT = 1000L;
// Discover nearby apps that are advertising with the required service ID.
Nearby.Connections.startDiscovery(mGoogleApiClient, serviceId, DISCOVER_TIMEOUT, this)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
// Device is discovering
tv_status.setText("Discovering");
} else {
int statusCode = status.getStatusCode();
// Advertising failed - see statusCode for more details
tv_status.setText("Error: " + statusCode);
}
}
});
}
#Override
public void onEndpointFound(final String endpointId, String deviceId,
String serviceId, final String endpointName) {
// This device is discovering endpoints and has located an advertiser.
// Write your logic to initiate a connection with the device at
// the endpoint ID
Toast.makeText(this, "Found Device: " + serviceId + ", " + endpointName + ". Start Connection Try", Toast.LENGTH_SHORT).show();
connectTo(endpointId, endpointName);
}
private void connectTo(String remoteEndpointId, final String endpointName) {
// Send a connection request to a remote endpoint. By passing 'null' for
// the name, the Nearby Connections API will construct a default name
// based on device model such as 'LGE Nexus 5'.
tv_status.setText("Connecting");
String myName = null;
byte[] myPayload = null;
Nearby.Connections.sendConnectionRequest(mGoogleApiClient, myName,
remoteEndpointId, myPayload, new Connections.ConnectionResponseCallback() {
#Override
public void onConnectionResponse(String remoteEndpointId, Status status,
byte[] bytes) {
if (status.isSuccess()) {
// Successful connection
tv_status.setText("Connected to " + endpointName);
globalRemoteEndpointId = remoteEndpointId;
} else {
// Failed connection
tv_status.setText("Connecting failed");
}
}
}, this);
}
#Override
public void onConnectionRequest(final String remoteEndpointId, String remoteDeviceId,
final String remoteEndpointName, byte[] payload) {
if (mIsHost) {
byte[] myPayload = null;
// Automatically accept all requests
Nearby.Connections.acceptConnectionRequest(mGoogleApiClient, remoteEndpointId,
myPayload, this).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
String statusS = "Connected to " + remoteEndpointName;
Toast.makeText(c, statusS,
Toast.LENGTH_SHORT).show();
tv_status.setText(statusS);
globalRemoteEndpointId = remoteEndpointId;
} else {
String statusS = "Failed to connect to: " + remoteEndpointName;
Toast.makeText(c, statusS,
Toast.LENGTH_SHORT).show();
tv_status.setText(statusS);
}
}
});
} else {
// Clients should not be advertising and will reject all connection requests.
Nearby.Connections.rejectConnectionRequest(mGoogleApiClient, remoteEndpointId);
}
}
#Override
public void onMessageReceived(String endpointId, byte[] payload, boolean b) {
String message = payload.toString();
Toast.makeText(this, "Received from " + endpointId + ": " + message, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View view) {
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
tv_status.setText("Connection suspended because of " + i);
mGoogleApiClient.reconnect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
tv_status.setText("Connection Failed");
}
#Override
public void onEndpointLost(String s) {
tv_status.setText("Endpoint lost: " + s);
}
#Override
public void onDisconnected(String s) {
tv_status.setText("Disconnected: " + s);
}
public void checkPermisson(){
Toast.makeText(c, "Check permission", Toast.LENGTH_SHORT).show();
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_NETWORK_STATE}, MY_PERMISSIONS_REQUEST);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
Toast.makeText(c, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(c, "Permission not granted, app may fail", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}

Nearby API not getting any message

I have tried connecting to the Nearby Messages API, and have successfully been able to subscribe.
Now, my mMessageListener field is never getting callbacks for some reason.
I have already configured my beacons using the proximity beacon api using the Android beacon service demo app.
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
// Declaration of member variables
private GoogleApiClient mGoogleApiClient;
private final String TAG = "Bridge.MainActivity";
private boolean mResolvingError = false;
private static final int REQUEST_RESOLVE_ERROR = 100;
private static final int REQUEST_PERMISSION = 42;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing the Google API client
}
private MessageListener mMessageListener = new MessageListener() {
#Override
public void onFound(Message message) {
// Do something with the message
Log.i(TAG, " Found Message : " + message.toString());
}
#Override
public void onLost(Message message) {
super.onLost(message);
Log.i(TAG, " Found Message : " + message.toString());
}
};
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(TAG, "GoogleAPi Client Connected");
foregorundSubscribeBeacons();
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "Google Api Connection Suspended : " + i);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "GoogleApi Connection failed : " + connectionResult.getErrorMessage());
}
public void foregorundSubscribeBeacons() {
// Subscribe to receive messages
Log.i(TAG, "Trying to subscribe");
if (!mGoogleApiClient.isConnected()) {
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
} else {
SubscribeOptions options = new SubscribeOptions.Builder()
.setStrategy(Strategy.BLE_ONLY)
.setCallback(new SubscribeCallback() {
#Override
public void onExpired() {
Log.i(TAG, "No longer subscribing.");
}
}).build();
Nearby.Messages.subscribe(mGoogleApiClient, mMessageListener, options)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Subscribed successfully.");
} else {
Log.i(TAG, "Could not subscribe.");
// Check whether consent was given;
// if not, prompt the user for consent.
handleUnsuccessfulNearbyResult(status);
}
}
});
}
}
private void handleUnsuccessfulNearbyResult(Status status) {
Log.i(TAG, "Processing error, status = " + status);
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (status.hasResolution()) {
try {
mResolvingError = true;
status.startResolutionForResult(this,
REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
mResolvingError = false;
Log.i(TAG, "Failed to resolve error status.", e);
}
} else {
if (status.getStatusCode() == CommonStatusCodes.NETWORK_ERROR) {
Toast.makeText(this.getApplicationContext(),
"No connectivity, cannot proceed. Fix in 'Settings' and try again.",
Toast.LENGTH_LONG).show();
} else {
// To keep things simple, pop a toast for all other error messages.
Toast.makeText(this.getApplicationContext(), "Unsuccessful: " +
status.getStatusMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_RESOLVE_ERROR) {
// User was presented with the Nearby opt-in dialog and pressed "Allow".
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Execute the pending subscription and publication tasks here.
foregorundSubscribeBeacons();
} else if (resultCode == RESULT_CANCELED) {
// User declined to opt-in. Reset application state here.
} else {
Toast.makeText(this, "Failed to resolve error with code " + resultCode,
Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onStart() {
super.onStart();
//Initiate connection to Play Services
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Nearby.MESSAGES_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
//The location permission is required on API 23+ to obtain BLE scan results
int result = ActivityCompat
.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (result != PackageManager.PERMISSION_GRANTED) {
//Ask for the location permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSION);
}
}
#Override
protected void onStop() {
super.onStop();
//Tear down Play Services connection
if (mGoogleApiClient.isConnected()) {
Log.d(TAG, "Un-subscribing…");
mGoogleApiClient.disconnect();
}
}
Make sure both the Beacon Service Demo App and the app using Nearby Messages are part of the same Google Developers Console project. You will only see messages attached by your own project.
If you have successfully done the beacon registration, adding the attachment to beacon on the Google Beacon Registry Server; then on subscribed successfully on device.
PRE-PREPARATION IS NECESSARY, ELSE YOU WON'T GET THE THINGS ON DEVICE.
So when beacon gets detected, the onFound(Message msg) gets called for each attachment of respective beacon.
THEY CLEARLY SAID, "DO SOMETHING WITH MESSAGE" in onFound(), so process your attachment only there, not the outside of onFound().
Here, if you print variable msg into Log, it should look like this :
Message{namespace='yourprojectname-1234', type='abcd', content=[614 bytes], devices=[NearbyDevice{id=NearbyDeviceId{UNKNOWN}}]}
Get the attachment content with msg.getContent() into String variable. This is normal text, and not in the base64 format.
Once you get the string content, DO WHATEVER you wanted to do.
Now it's up to you what content goes into attachment.
I have used JSON in the attachment and successfully processed for my purpose.

Why is my Fitness.SensorApi OnDataPointListener only called once?

My GoogleApiClient connects successfully and my #Override public void onDataPoint(DataPoint dataPoint) {…} is called exactly once and then never again. This is within a Service that's started only after Google Fit is authorized from within the UI (that's another can of worms). The Service has another GoogleApiClient that successfully runs and is called at my specified interval.
Here's what I see from logcat:
mGoogleFitApiClient connected.
mGoogleFitApiClient listener registered.
mGoogleFitApiClient detected DataPoint: still (100.0% confidence)
It's then never called again and #Override public void onConnectionSuspended(int i) {…} is never called either.
Here's the relevant code from my Service:
private void buildFitnessClient() {
mGoogleFitApiClient = new GoogleApiClient.Builder(this)
.useDefaultAccount()
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "mGoogleFitApiClient connected.");
setupPhysicalActivityListener();
}
#Override
public void onConnectionSuspended(int i) {
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "mGoogleFitApiClient connection lost. Cause: network lost.");
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG, "mGoogleFitApiClient connection lost. Reason: service disconnected");
}
}
}
)
.addOnConnectionFailedListener(
new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "mGoogleFitApiClient connection failed. Cause: " + result.toString());
}
}
)
.build();
}
#Override
public void onDataPoint(DataPoint dataPoint) {
String activityName = "";
float confidence = 0;
for (Field field : dataPoint.getDataType().getFields()) {
if (field.getName().equals("activity")) {
activityName = dataPoint.getValue(field).asActivity();
} else if (field.getName().equals("confidence")) {
confidence = dataPoint.getValue(field).asFloat();
}
}
lastActivityName = activityName;
lastActivityConfidence = confidence;
Log.i(TAG, "mGoogleFitApiClient detected DataPoint: " + activityName + " (" + confidence + "% confidence)");
}
private void setupPhysicalActivityListener() {
SensorRequest sensorRequest = new SensorRequest.Builder()
.setDataType(DataType.TYPE_ACTIVITY_SAMPLE)
.setSamplingRate(15, TimeUnit.SECONDS)
.setFastestRate(5, TimeUnit.SECONDS)
.setAccuracyMode(SensorRequest.ACCURACY_MODE_LOW)
.build();
Fitness.SensorsApi.add(mGoogleFitApiClient, sensorRequest, this)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.i(TAG, "mGoogleFitApiClient listener registered.");
} else {
Log.i(TAG, "mGoogleFitApiClient listener not registered.");
}
}
});
}
The request data type is
setDataType(DataType.TYPE_ACTIVITY_SAMPLE)
Try
DataType.TYPE_STEP_COUNT_DELTA or DataType.TYPE_HEART_RATE_BPM
to see if you get the same result.(only called once)
Could it be because the screen becomes locked?

Step Counter Google FIT API

I am currently trying to work with Google Fit API.This is my first App using the API, and I have been mainly by following Google's documentation.
Below is the code that I have which seems to have a problem
The problem I have is that it doesn't seem to be updating the step counter.
public class MainActivity extends Activity
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "FitActivity";
//[START Auth_Variable_References]
private static final int REQUEST_OAUTH = 1;
// [END auth_variable_references]
private GoogleApiClient mClient = null;
int mInitialNumberOfSteps = 0;
private TextView mStepsTextView;
private boolean mFirstCount = true;
// Create Builder View
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStepsTextView = (TextView) findViewById(R.id.textview_number_of_steps);
}
private void connectFitness() {
Log.i(TAG, "Connecting...");
// Create the Google API Client
mClient = new GoogleApiClient.Builder(this)
// select the Fitness API
.addApi(Fitness.API)
// specify the scopes of access
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.addScope(new Scope(Scopes.FITNESS_LOCATION_READ))
.addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE))
// provide callbacks
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
// Connect the Google API client
mClient.connect();
}
// Manage OAuth authentication
#Override
public void onConnectionFailed(ConnectionResult result) {
// Error while connecting. Try to resolve using the pending intent returned.
if (result.getErrorCode() == ConnectionResult.SIGN_IN_REQUIRED ||
result.getErrorCode() == FitnessStatusCodes.NEEDS_OAUTH_PERMISSIONS) {
try {
// Request authentication
result.startResolutionForResult(this, REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception connecting to the fitness service", e);
}
} else {
Log.e(TAG, "Unknown connection issue. Code = " + result.getErrorCode());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OAUTH) {
if (resultCode == RESULT_OK) {
// If the user authenticated, try to connect again
mClient.connect();
}
}
}
#Override
public void onConnectionSuspended(int i) {
// If your connection gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "Connection lost. Cause: Network Lost.");
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG, "Connection lost. Reason: Service Disconnected");
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected!");
// Now you can make calls to the Fitness APIs.
invokeFitnessAPIs();
}
private void invokeFitnessAPIs() {
// Create a listener object to be called when new data is available
OnDataPointListener listener = new OnDataPointListener() {
#Override
public void onDataPoint(DataPoint dataPoint) {
for (Field field : dataPoint.getDataType().getFields()) {
Value val = dataPoint.getValue(field);
updateTextViewWithStepCounter(val.asInt());
}
}
};
//Specify what data sources to return
DataSourcesRequest req = new DataSourcesRequest.Builder()
.setDataSourceTypes(DataSource.TYPE_DERIVED)
.setDataTypes(DataType.TYPE_STEP_COUNT_DELTA)
.build();
// Invoke the Sensors API with:
// - The Google API client object
// - The data sources request object
PendingResult<DataSourcesResult> pendingResult =
Fitness.SensorsApi.findDataSources(mClient, req);
// Build a sensor registration request object
SensorRequest sensorRequest = new SensorRequest.Builder()
.setDataType(DataType.TYPE_STEP_COUNT_CUMULATIVE)
.setSamplingRate(1, TimeUnit.SECONDS)
.build();
// Invoke the Sensors API with:
// - The Google API client object
// - The sensor registration request object
// - The listener object
PendingResult<Status> regResult =
Fitness.SensorsApi.add(mClient,
new SensorRequest.Builder()
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.build(),
listener);
// 4. Check the result asynchronously
regResult.setResultCallback(new ResultCallback<Status>()
{
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.d(TAG, "listener registered");
// listener registered
} else {
Log.d(TAG, "listener not registered");
// listener not registered
}
}
});
}
// Update the Text Viewer with Counter of Steps..
private void updateTextViewWithStepCounter(final int numberOfSteps) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "On Datapoint!", Toast.LENGTH_SHORT);
if(mFirstCount && (numberOfSteps != 0)) {
mInitialNumberOfSteps = numberOfSteps;
mFirstCount = false;
}
if(mStepsTextView != null){
mStepsTextView.setText(String.valueOf(numberOfSteps - mInitialNumberOfSteps));
}
}
});
}
//Start
#Override
protected void onStart() {
super.onStart();
mFirstCount = true;
mInitialNumberOfSteps = 0;
if (mClient == null || !mClient.isConnected()) {
connectFitness();
}
}
//Stop
#Override
protected void onStop() {
super.onStop();
if(mClient.isConnected() || mClient.isConnecting()) mClient.disconnect();
mInitialNumberOfSteps = 0;
mFirstCount = true;
}
}
First of all,
Follow these steps to enable the Fitness API in the Google API Console and get an OAuth 2.0 client ID.
1. Go to the Google API Console.
2. Select a project, or create a new one. Use the same project for the Android and REST versions of your app.
3. Click Continue to enable the Fitness API.
4. Click Go to credentials.
5. Click New credentials, then select OAuth Client ID.
6. Under Application type select Android.
7. In the resulting dialog, enter your app's SHA-1 fingerprint and package name. For example:
BB:0D:AC:74:D3:21:E1:43:67:71:9B:62:91:AF:A1:66:6E:44:5D:75
com.example.android.fit-example
8. Click Create. Your new Android OAuth 2.0 Client ID and secret appear in the list of IDs for your project. An OAuth 2.0 Client ID is a string of characters, something like this:
780816631155-gbvyo1o7r2pn95qc4ei9d61io4uh48hl.apps.googleusercontent.com
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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.ResultCallback;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSource;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.data.Value;
import com.google.android.gms.fitness.request.DataSourcesRequest;
import com.google.android.gms.fitness.request.OnDataPointListener;
import com.google.android.gms.fitness.request.SensorRequest;
import com.google.android.gms.fitness.result.DataSourcesResult;
import java.util.concurrent.TimeUnit;
/**
* Created by Admin on Dec/8/2016.
* <p/>
* <p/>
* http://stackoverflow.com/questions/28476809/step-counter-google-fit-api?rq=1
*/
public class StackOverflowActivity extends AppCompatActivity
{
private static final String TAG = "FitActivity";
private GoogleApiClient mClient = null;
private OnDataPointListener mListener;
// Create Builder View
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
connectFitness();
}
private void connectFitness() {
if (mClient == null){
mClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_LOCATION_READ)) // GET STEP VALUES
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.e(TAG, "Connected!!!");
// Now you can make calls to the Fitness APIs.
findFitnessDataSources();
}
#Override
public void onConnectionSuspended(int i) {
// If your connection to the sensor gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "Connection lost. Cause: Network Lost.");
} else if (i
== GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG,
"Connection lost. Reason: Service Disconnected");
}
}
}
)
.enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.e(TAG, "!_##ERROR :: Google Play services connection failed. Cause: " + result.toString());
}
})
.build();
}
}
private void findFitnessDataSources() {
Fitness.SensorsApi.findDataSources(
mClient,
new DataSourcesRequest.Builder()
.setDataTypes(DataType.TYPE_STEP_COUNT_DELTA)
.setDataSourceTypes(DataSource.TYPE_DERIVED)
.build())
.setResultCallback(new ResultCallback<DataSourcesResult>() {
#Override
public void onResult(DataSourcesResult dataSourcesResult) {
Log.e(TAG, "Result: " + dataSourcesResult.getStatus().toString());
for (DataSource dataSource : dataSourcesResult.getDataSources()) {
Log.e(TAG, "Data source found: " + dataSource.toString());
Log.e(TAG, "Data Source type: " + dataSource.getDataType().getName());
//Let's register a listener to receive Activity data!
if (dataSource.getDataType().equals(DataType.TYPE_STEP_COUNT_DELTA) && mListener == null) {
Log.i(TAG, "Data source for TYPE_STEP_COUNT_DELTA found! Registering.");
registerFitnessDataListener(dataSource, DataType.TYPE_STEP_COUNT_DELTA);
}
}
}
});
}
private void registerFitnessDataListener(final DataSource dataSource, DataType dataType) {
// [START register_data_listener]
mListener = new OnDataPointListener() {
#Override
public void onDataPoint(DataPoint dataPoint) {
for (Field field : dataPoint.getDataType().getFields()) {
Value val = dataPoint.getValue(field);
Log.e(TAG, "Detected DataPoint field: " + field.getName());
Log.e(TAG, "Detected DataPoint value: " + val);
}
}
};
Fitness.SensorsApi.add(
mClient,
new SensorRequest.Builder()
.setDataSource(dataSource) // Optional but recommended for custom data sets.
.setDataType(dataType) // Can't be omitted.
.setSamplingRate(1, TimeUnit.SECONDS)
.build(),
mListener).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Listener registered!");
} else {
Log.i(TAG, "Listener not registered.");
}
}
});
}
}
NOTE : :: Sometimes in some device it doestn't detect Step values so whenever you are developing and workling with this code Always Uninstall app and then re-install app. then this works fine.
**Don't forget to add this permission**
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You can try the StepSensor library from OrangeGangster's.
It contains a custom Service allowing to collect data from the Sensor.TYPE_STEP_COUNTER introduced with Android 4.4 (available only for devices that supports this hardware feature).
This code works for me !
Building the client :
mClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE))
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
Invoking Sensors API :
private void invokeSensorsAPI() {
Fitness.SensorsApi.add(
mClient,
new SensorRequest.Builder()
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setSamplingRate(1, TimeUnit.SECONDS)
.build(),
this)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Sensor Listener registered!");
} else {
Log.i(TAG, "Sensor Listener not registered.");
}
}
});
}
Recieving data :
#Override
public void onDataPoint(DataPoint dataPoint) {
for (Field field : dataPoint.getDataType().getFields()) {
Value val = dataPoint.getValue(field);
Log.i(TAG, "Detected DataPoint field: " + field.getName());
Log.i(TAG, "Detected DataPoint value: " + val);
final int value = val.asInt();
if (field.getName().compareToIgnoreCase("steps") == 0) {
runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText("Value" + value)
}
});
}
}
}
I hope it helps
I think you are making a mistake here
if (resultCode == RESULT_OK) {
// If the user authenticated, try to connect again
mClient.connect()
}
instead it should be
if (resultCode != RESULT_OK) {
// If the user is not authenticated, try to connect again/ resultcode = RESULT_CANCEL
mClient.connect()
} else {
onConnected(null);
}
By your code invokeFitnessApis would never be called because you are reconnecting with googleapiclient after successfull connection.

Categories

Resources