Agora.io in Native Android (Java) - java

I know that this questions was asked before but it doesn't solved by queries mentioned below after the code .
package io.agora.tutorials1v1vcall;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import io.agora.uikit.logger.LoggerRecyclerView;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;
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
private LoggerRecyclerView mLogView;
/**
* 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() {
mLogView.logI("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() {
mLogView.logI("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() {
mLogView.logI("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);
mLogView = findViewById(R.id.log_recycler_view);
// Sample logs are optional.
showSampleLogs();
}
private void showSampleLogs() {
mLogView.logI("Welcome to Agora 1v1 video call");
mLogView.logW("You will see custom logs here");
mLogView.logE("You can also use this to show errors");
}
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.
String token = getString(R.string.agora_access_token);
if (TextUtils.isEmpty(token) || TextUtils.equals(token, "#YOUR ACCESS TOKEN#")) {
token = null; // default, no token
}
mRtcEngine.joinChannel(token, "demoChannel1", "Extra Optional Data", 0);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (!mCallEnd) {
leaveChannel();
}
RtcEngine.destroy();
}
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_unmute;
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_endcall);
} else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
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);
}
}
I am integrating the agora.io for one-to-one video calling functionality. I got the above code from the agora.io documentation but i am getting the black remote screen . Also i would ask that how would i connect two users dynamically. What modifications i have to do in the above code for one-to-one video call functionality. Please help.Thanks in advance.

It showing black screen because of token issue. kindly check token generation code in backend. Most probably the reason for black screen is the token expiration time.

Related

“How to fix ‘Registration failed. Please check settings’ error in android with sample demo SIP

I'm using sample demo of
https://github.com/aosp-mirror/platform_development/tree/master/samples/SipDemo
the programing is ok, it doesn´t show issues, but when I configure this, it shows message Registration failed.
I´m programing with android studio, and the server is asterisk.
I tried with soiper and and it works.
public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
public String sipAddress = null;
public SipManager manager = null;
public SipProfile me = null;
public SipAudioCall call = null;
public IncomingCallReceiver callReceiver;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walkie_talkie);
ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(this);
// Set up the intent filter. This will be used to fire an
// IncomingCallReceiver when someone calls the SIP address used by this
// application.
IntentFilter filter = new IntentFilter();
filter.addAction("android.SipDemo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
// "Push to talk" can be a serious pain when the screen keeps turning off.
// Let's prevent that.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
initializeManager();
}
#Override
public void onStart() {
super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
initializeManager();
}
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
public void initializeManager() {
if(manager == null) {
manager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
/**
* Logs you into your SIP provider, registering this device as the location to
* send SIP calls to for your SIP address.
*/
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
/* String username = prefs.getString("namePref", "");
String domain = prefs.getString("domainPref", "");
String password = prefs.getString("passPref", ""); */
String username = "12";
String domain = "192.168.1.37";
String password = "1234";
if (username.length() == 0 || domain.length() == 0 || password.length() == 0) {
showDialog(UPDATE_SETTINGS_DIALOG);
return;
}
try {
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setAuthUserName("12");
builder.setDisplayName("12");
builder.setProfileName("12");
builder.setPassword(password);
me = builder.build();
Intent i = new Intent();
i.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus("Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus("Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus("Registration failed. Please check settings.");
}
});
} catch (ParseException pe) {
updateStatus("Connection Error.");
} catch (SipException se) {
updateStatus("Connection error.");
}
}
/**
* Closes out your local profile, freeing associated objects into memory
* and unregistering your device from the server.
*/
public void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
// Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
}
}
/**
* Make an outgoing call.
*/
public void initiateCall() {
updateStatus(sipAddress);
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
// Much of the client's interaction with the SIP Stack will
// happen via listeners. Even making an outgoing call, don't
// forget to set up a listener to set things up once the call is established.
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
updateStatus(call);
}
#Override
public void onCallEnded(SipAudioCall call) {
updateStatus("Ready.");
}
};
call = manager.makeAudioCall(me.getUriString(), sipAddress, listener, 30);
}
catch (Exception e) {
// Log.i("WalkieTalkieActivity/InitiateCall", "Error when trying to close manager.", e);
if (me != null) {
try {
manager.close(me.getUriString());
} catch (Exception ee) {
// Log.i("WalkieTalkieActivity/InitiateCall",
// "Error when trying to close manager.", ee);
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
/**
* Updates the status box at the top of the UI with a messege of your choice.
* #param status The String to display in the status box.
*/
public void updateStatus(final String status) {
// Be a good citizen. Make sure UI changes fire on the UI thread.
this.runOnUiThread(new Runnable() {
public void run() {
TextView labelView = (TextView) findViewById(R.id.sipLabel);
labelView.setText(status);
}
});
}
/**
* Updates the status box with the SIP address of the current call.
* #param call The current, active call.
*/
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if(useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
/**
* Updates whether or not the user's voice is muted, depending on whether the button is pressed.
* #param v The View where the touch event is being fired.
* #param event The motion to act on.
* #return boolean Returns false to indicate that the parent view should handle the touch event
* as it normally would.
*/
public boolean onTouch(View v, MotionEvent event) {
if (call == null) {
return false;
} else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
call.toggleMute();
} else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
call.toggleMute();
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, CALL_ADDRESS, 0, "Call someone");
menu.add(0, SET_AUTH_INFO, 0, "Edit your SIP Info.");
menu.add(0, HANG_UP, 0, "End Current Call.");
return true;
}
}
Think that should be user#domain ...and an IP address is not a domain.

Samsung Health : solving java.lang.IllegalArgumentException: heart_rate (READ) is invalid

what I want to do is developing an app that reads health data that collected by Samsung watch so I tried to use Samsung android health SDK . Moreover reading steps was very easy as there was a sample app doing the same thing . the issue appear when I was trying to read the heart rate value :
here is my code please help me address the issue :
Mainfest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smaunghealth">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data android:name="com.samsung.android.health.permission.read"
android:value="com.samsung.health.step_count;com.samsung.health.heart_rate"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
MainActivity
package com.example.smaunghealth;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.samsung.android.sdk.healthdata.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
public static final String APP_TAG = "SimpleHealth";
private static MainActivity mInstance = null;
private HealthDataStore mStore;
private HealthConnectionErrorResult mConnError;
private Set<HealthPermissionManager.PermissionKey> mKeySet;
private StepCountReporter mReporter;
private HeartRateReporter mHeartReporter;
TextView stepCount ;
TextView heartRate ;
private final HealthResultHolder.ResultListener<HealthPermissionManager.PermissionResult> mPermissionListener =
new HealthResultHolder.ResultListener<HealthPermissionManager.PermissionResult>() {
#Override
public void onResult(HealthPermissionManager.PermissionResult result) {
Log.d(APP_TAG, "Permission callback is received.");
Map<HealthPermissionManager.PermissionKey, Boolean> resultMap = result.getResultMap();
if (resultMap.containsValue(Boolean.FALSE)) {
// Requesting permission fails
} else {
// Get the current step count and display it
}
}
};
private final HealthDataStore.ConnectionListener mConnectionListener = new HealthDataStore.ConnectionListener() {
#Override
public void onConnected() {
Log.d(APP_TAG, "Health data service is connected.");
HealthPermissionManager pmsManager = new HealthPermissionManager(mStore);
try {
// Check whether the permissions that this application needs are acquired
Map<HealthPermissionManager.PermissionKey, Boolean> resultMap = pmsManager.isPermissionAcquired(mKeySet);
if (resultMap.containsValue(Boolean.FALSE)) {
// Request the permission for reading step counts if it is not acquired
pmsManager.requestPermissions(mKeySet, MainActivity.this).setResultListener(mPermissionListener);
} else {
// Get the current step count and display it
// ...
mReporter = new StepCountReporter(mStore);
mReporter.start(mStepCountObserver);
mHeartReporter = new HeartRateReporter(mStore);
mHeartReporter.start(heartRateObserver);
}
} catch (Exception e) {
Log.e(APP_TAG, e.getClass().getName() + " - " + e.getMessage());
Log.e(APP_TAG, "Permission setting fails.");
}
}
#Override
public void onConnectionFailed(HealthConnectionErrorResult error) {
Log.d(APP_TAG, "Health data service is not available.");
showConnectionFailureDialog(error);
}
#Override
public void onDisconnected() {
Log.d(APP_TAG, "Health data service is disconnected.");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInstance = this;
stepCount= (TextView) findViewById(R.id.step_count);
heartRate= (TextView) findViewById(R.id.heart_rate);
mKeySet = new HashSet<HealthPermissionManager.PermissionKey>();
// mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, HealthPermissionManager.PermissionType.READ));
mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.HeartRate.HEART_RATE, HealthPermissionManager.PermissionType.READ));
HealthDataService healthDataService = new HealthDataService();
try {
healthDataService.initialize(this);
} catch (Exception e) {
e.printStackTrace();}
mStore = new HealthDataStore(this, mConnectionListener);
// Request the connection to the health data store
mStore.connectService();
}
#Override
public void onDestroy() {
mStore.disconnectService();
super.onDestroy();
}
private StepCountReporter.StepCountObserver mStepCountObserver = count -> {
Log.d(APP_TAG, "Step reported : " + count);
updateStepCountView(String.valueOf(count));
};
private HeartRateReporter.HeartRateObserver heartRateObserver = count -> {
Log.d(APP_TAG, "Step reported : " + count);
updateHeartRateView(String.valueOf(count));
};
private void updateHeartRateView(String valueOf) {
Log.d(APP_TAG, "heart rate reported : " + valueOf);
updateHeartRateView(String.valueOf(valueOf));
}
private void updateStepCountView(String count) {
stepCount.setText(count);
}
private void showConnectionFailureDialog(HealthConnectionErrorResult error) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
mConnError = error;
String message = "Connection with Samsung Health is not available";
if (mConnError.hasResolution()) {
switch(error.getErrorCode()) {
case HealthConnectionErrorResult.PLATFORM_NOT_INSTALLED:
message = "Please install Samsung Health";
break;
case HealthConnectionErrorResult.OLD_VERSION_PLATFORM:
message = "Please upgrade Samsung Health";
break;
case HealthConnectionErrorResult.PLATFORM_DISABLED:
message = "Please enable Samsung Health";
break;
case HealthConnectionErrorResult.USER_AGREEMENT_NEEDED:
message = "Please agree with Samsung Health policy";
break;
default:
message = "Please make Samsung Health available";
break;
}
}
alert.setMessage(message);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
if (mConnError.hasResolution()) {
mConnError.resolve(mInstance);
}
}
});
if (error.hasResolution()) {
alert.setNegativeButton("Cancel", null);
}
alert.show();
}
}
HeartRateReporter
package com.example.smaunghealth;
import android.util.Log;
import com.samsung.android.sdk.healthdata.*;
import java.util.Calendar;
import java.util.TimeZone;
public class HeartRateReporter {
private final HealthDataStore mStore;
private HeartRateObserver mHeartRateObserver;
private static final long ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000L;
public HeartRateReporter(HealthDataStore store) {
mStore = store;
}
public void start(HeartRateObserver listener) {
mHeartRateObserver = listener;
HealthDataObserver.addObserver(mStore, HealthConstants.HeartRate.HEART_RATE, mObserver);
readHeartRate();
}
private void readHeartRate() {
HealthDataResolver resolver = new HealthDataResolver(mStore, null);
// Set time range from start time of today to the current time
long startTime = getStartTimeOfToday();
long endTime = startTime + ONE_DAY_IN_MILLIS;
HealthDataResolver.ReadRequest request = new HealthDataResolver.ReadRequest.Builder()
.setDataType(HealthConstants.HeartRate.HEART_RATE)
.setProperties(new String[] {HealthConstants.HeartRate.HEART_RATE})
.setLocalTimeRange(HealthConstants.HeartRate.START_TIME, HealthConstants.HeartRate.TIME_OFFSET,
startTime, endTime)
.build();
try {
resolver.read(request).setResultListener(mListener);
} catch (Exception e) {
Log.e("*&*&*&", "Getting Heart fails.", e);
}
}
private long getStartTimeOfToday() {
Calendar today = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
return today.getTimeInMillis();
}
private final HealthResultHolder.ResultListener<HealthDataResolver.ReadResult> mListener = result -> {
int count = 0;
try {
for (HealthData data : result) {
count += data.getInt(HealthConstants.HeartRate.HEART_RATE);
}
} finally {
result.close();
}
if (mHeartRateObserver != null) {
mHeartRateObserver.onChanged(count);
}
};
private final HealthDataObserver mObserver = new HealthDataObserver(null) {
#Override
public void onChange(String dataTypeName) {
Log.d("*&*&*&", "Observer receives a data changed event");
readHeartRate();
}
};
public interface HeartRateObserver {
void onChanged(int count);
}
}
StepCountReporter
/**
* Copyright (C) 2014 Samsung Electronics Co., Ltd. All rights reserved.
*
* Mobile Communication Division,
* Digital Media & Communications Business, Samsung Electronics Co., Ltd.
*
* This software and its documentation are confidential and proprietary
* information of Samsung Electronics Co., Ltd. No part of the software and
* documents may be copied, reproduced, transmitted, translated, or reduced to
* any electronic medium or machine-readable form without the prior written
* consent of Samsung Electronics.
*
* Samsung Electronics makes no representations with respect to the contents,
* and assumes no responsibility for any errors that might appear in the
* software and documents. This publication and the contents hereof are subject
* to change without notice.
*/
package com.example.smaunghealth;
import android.util.Log;
import com.samsung.android.sdk.healthdata.*;
import com.samsung.android.sdk.healthdata.HealthDataResolver.ReadRequest;
import com.samsung.android.sdk.healthdata.HealthDataResolver.ReadResult;
import java.util.Calendar;
import java.util.TimeZone;
public class StepCountReporter {
private final HealthDataStore mStore;
private StepCountObserver mStepCountObserver;
private static final long ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000L;
public StepCountReporter(HealthDataStore store) {
mStore = store;
}
public void start(StepCountObserver listener) {
mStepCountObserver = listener;
// Register an observer to listen changes of step count and get today step count
HealthDataObserver.addObserver(mStore, HealthConstants.StepCount.HEALTH_DATA_TYPE, mObserver);
readTodayStepCount();
}
// Read the today's step count on demand
private void readTodayStepCount() {
HealthDataResolver resolver = new HealthDataResolver(mStore, null);
// Set time range from start time of today to the current time
long startTime = getStartTimeOfToday();
long endTime = startTime + ONE_DAY_IN_MILLIS;
HealthDataResolver.ReadRequest request = new ReadRequest.Builder()
.setDataType(HealthConstants.StepCount.HEALTH_DATA_TYPE)
.setProperties(new String[] {HealthConstants.StepCount.COUNT})
.setLocalTimeRange(HealthConstants.StepCount.START_TIME, HealthConstants.StepCount.TIME_OFFSET,
startTime, endTime)
.build();
try {
resolver.read(request).setResultListener(mListener);
} catch (Exception e) {
Log.e(MainActivity.APP_TAG, "Getting step count fails.", e);
}
}
private long getStartTimeOfToday() {
Calendar today = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
return today.getTimeInMillis();
}
private final HealthResultHolder.ResultListener<ReadResult> mListener = result -> {
int count = 0;
try {
for (HealthData data : result) {
count += data.getInt(HealthConstants.StepCount.COUNT);
}
} finally {
result.close();
}
if (mStepCountObserver != null) {
mStepCountObserver.onChanged(count);
}
};
private final HealthDataObserver mObserver = new HealthDataObserver(null) {
// Update the step count when a change event is received
#Override
public void onChange(String dataTypeName) {
Log.d(MainActivity.APP_TAG, "Observer receives a data changed event");
readTodayStepCount();
}
};
public interface StepCountObserver {
void onChanged(int count);
}
}
Here is the exception log :
<meta-data android:name="com.samsung.android.health.permission.read"
android:value="com.samsung.health.step_count;com.samsung.health.heart_rate"/>
I think you should separate this permission into two, not only one。
like:
<meta-data android:name="com.samsung.android.health.permission.read"
android:value="com.samsung.health.step_count"/>
<meta-data android:name="com.samsung.android.health.permission.read"
android:value="com.samsung.health.heart_rate"/>
After long time finally I was able to address the issue :
mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, HealthPermissionManager.PermissionType.READ));
mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.HeartRate.HEART_RATE, HealthPermissionManager.PermissionType.READ));
this is the write permissionKey :
mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, HealthPermissionManager.PermissionType.READ));
mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.HeartRate.HEALTH_DATA_TYPE, HealthPermissionManager.PermissionType.READ));

"No SKUs listed, can't load them" - solovyev.android:checkout

I have an app with in-app purchase, but when I try get list of items I recieving error:
Caused by: org.solovyev.android.checkout.Check$AssertionException: No
SKUs listed, can't load them
InAppPurchase.java:
import android.app.Application;
import org.solovyev.android.checkout.Billing;
public class InAppPurchase extends Application {
private static InAppPurchase sInstance;
String key = "xxx";
public void onCreate() {
super.onCreate();
}
private final Billing mBilling = new Billing(this, new Billing.DefaultConfiguration() {
#Override public String getPublicKey() {
return key;
}
});
public InAppPurchase() {
sInstance = this;
}
public static InAppPurchase get() {
return sInstance;
}
public Billing getBilling() {
return mBilling;
}
}
Settings.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
...
mCheckout = Checkout.forActivity(this, InAppPurchase.get().getBilling());
mCheckout.start();
mCheckout.createPurchaseFlow(new PurchaseListener());
Inventory mInventory = mCheckout.makeInventory();
mInventory.load(
Inventory.Request.create().loadAllPurchases().loadSkus(ProductTypes.IN_APP),
new InventoryCallback());
...
}
private class InventoryCallback implements Inventory.Callback {
#Override public void onLoaded(#Nonnull Inventory.Products products) {
final Inventory.Product product = products.get(ProductTypes.IN_APP);
if (!product.supported) {
Toast.makeText(Settings.this, "error supported", Toast.LENGTH_LONG).show();
return;
}
List<Purchase> list = product.getPurchases();
if (product.getSku("dark_theme") != null) {
String price = product.getSku("dark_theme").price;
Toast.makeText(Settings.this, price, Toast.LENGTH_LONG).show();
}
}
}
And error for
No SKUs listed, can't load them
Is showing in line
Inventory.Request.create().loadAllPurchases().loadSkus(ProductTypes.IN_APP)
App publihed in Alpha-section n Google Dev Console.
Please help me to fix it.
Try to provide a Sku id, you want to retrieve
mInventory.load(Inventory.Request.create().loadAllPurchases().loadSkus(ProductTypes.IN_APP),"<your Google Play product Id>",
new InventoryCallback());

Mopub: integrating inmobi native ads with the adapter InMobiNative

It appears that the whole inmobi sdk has changed significantly from 4.4.1 to 5.2.3 which means that I cannot integrate the inmobi sdk successfully into mopub. This is adapter bundled within the mopub sdk:
https://github.com/motain/android-ads-MoPub/blob/master/extras/src/com/mopub/nativeads/InMobiNative.java
I have copied and pasted the code here for your convenience - you can see that the author has said that the adapter was tested on 4.4.1:
package com.mopub.nativeads;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.inmobi.commons.InMobi;
import com.inmobi.monetization.IMErrorCode;
import com.inmobi.monetization.IMNative;
import com.inmobi.monetization.IMNativeListener;
import com.mopub.common.util.MoPubLog;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.mopub.common.util.Json.getJsonValue;
import static com.mopub.common.util.Numbers.parseDouble;
/*
* Tested with InMobi SDK 4.4.1
*/
class InMobiNative extends CustomEventNative implements IMNativeListener {
private static final String APP_ID_KEY = "app_id";
private Context mContext;
private CustomEventNativeListener mCustomEventNativeListener;
// CustomEventNative implementation
#Override
protected void loadNativeAd(final Context context,
final CustomEventNativeListener customEventNativeListener,
final Map<String, Object> localExtras,
final Map<String, String> serverExtras) {
mContext = context;
if (!(context instanceof Activity)) {
customEventNativeListener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
return;
}
final Activity activity = (Activity) context;
final String appId;
if (extrasAreValid(serverExtras)) {
appId = serverExtras.get(APP_ID_KEY);
} else {
customEventNativeListener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
return;
}
mCustomEventNativeListener = customEventNativeListener;
InMobi.initialize(activity, appId);
final IMNative imNative = new IMNative(this);
imNative.loadAd();
}
// IMNativeListener implementation
#Override
public void onNativeRequestSucceeded(final IMNative imNative) {
if (imNative == null) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_INVALID_STATE);
return;
}
final InMobiForwardingNativeAd inMobiForwardingNativeAd;
try {
inMobiForwardingNativeAd = new InMobiForwardingNativeAd(imNative);
} catch (IllegalArgumentException e) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.UNSPECIFIED);
return;
} catch (JSONException e) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.INVALID_JSON);
return;
}
final List<String> imageUrls = new ArrayList<String>();
final String mainImageUrl = inMobiForwardingNativeAd.getMainImageUrl();
if (mainImageUrl != null) {
imageUrls.add(mainImageUrl);
}
final String iconUrl = inMobiForwardingNativeAd.getIconImageUrl();
if (iconUrl != null) {
imageUrls.add(iconUrl);
}
preCacheImages(mContext, imageUrls, new ImageListener() {
#Override
public void onImagesCached() {
mCustomEventNativeListener.onNativeAdLoaded(inMobiForwardingNativeAd);
}
#Override
public void onImagesFailedToCache(NativeErrorCode errorCode) {
mCustomEventNativeListener.onNativeAdFailed(errorCode);
}
});
}
#Override
public void onNativeRequestFailed(final IMErrorCode errorCode) {
if (errorCode == IMErrorCode.INVALID_REQUEST) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_INVALID_REQUEST);
} else if (errorCode == IMErrorCode.INTERNAL_ERROR || errorCode == IMErrorCode.NETWORK_ERROR) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_INVALID_STATE);
} else if (errorCode == IMErrorCode.NO_FILL) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_NO_FILL);
} else {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.UNSPECIFIED);
}
}
private boolean extrasAreValid(final Map<String, String> serverExtras) {
final String placementId = serverExtras.get(APP_ID_KEY);
return (placementId != null && placementId.length() > 0);
}
static class InMobiForwardingNativeAd extends BaseForwardingNativeAd {
static final int IMPRESSION_MIN_TIME_VIEWED = 0;
// Modifiable keys
static final String TITLE = "title";
static final String DESCRIPTION = "description";
static final String SCREENSHOTS = "screenshots";
static final String ICON = "icon";
static final String LANDING_URL = "landing_url";
static final String CTA = "cta";
static final String RATING = "rating";
// Constant keys
static final String URL = "url";
private final IMNative mImNative;
InMobiForwardingNativeAd(final IMNative imNative) throws IllegalArgumentException, JSONException {
if (imNative == null) {
throw new IllegalArgumentException("InMobi Native Ad cannot be null");
}
mImNative = imNative;
final JSONTokener jsonTokener = new JSONTokener(mImNative.getContent());
final JSONObject jsonObject = new JSONObject(jsonTokener);
setTitle(getJsonValue(jsonObject, TITLE, String.class));
setText(getJsonValue(jsonObject, DESCRIPTION, String.class));
final JSONObject screenShotJsonObject = getJsonValue(jsonObject, SCREENSHOTS, JSONObject.class);
if (screenShotJsonObject != null) {
setMainImageUrl(getJsonValue(screenShotJsonObject, URL, String.class));
}
final JSONObject iconJsonObject = getJsonValue(jsonObject, ICON, JSONObject.class);
if (iconJsonObject != null) {
setIconImageUrl(getJsonValue(iconJsonObject, URL, String.class));
}
setClickDestinationUrl(getJsonValue(jsonObject, LANDING_URL, String.class));
setCallToAction(getJsonValue(jsonObject, CTA, String.class));
try {
setStarRating(parseDouble(jsonObject.opt(RATING)));
} catch (ClassCastException e) {
MoPubLog.d("Unable to set invalid star rating for InMobi Native.");
}
setImpressionMinTimeViewed(IMPRESSION_MIN_TIME_VIEWED);
}
#Override
public void prepareImpression(final View view) {
if (view != null && view instanceof ViewGroup) {
mImNative.attachToView((ViewGroup) view);
} else if (view != null && view.getParent() instanceof ViewGroup) {
mImNative.attachToView((ViewGroup) view.getParent());
} else {
MoPubLog.e("InMobi did not receive ViewGroup to attachToView, unable to record impressions");
}
}
#Override
public void handleClick(final View view) {
mImNative.handleClick(null);
}
#Override
public void destroy() {
mImNative.detachFromView();
}
}
}
Has anyone been successful in converting this adapter to work with the latest 5.2.3 inmobi sdk?
The 4.4.1 sdk is not even available to download anymore and if there is no adapter for 5.2.3, then I'm afraid inmobi integration with in mopub is not possible?
I waited a few days and did not get any response back from Inmobi so I decided to do some investigation myself on how to solve this issue. Eventually I can across this website which had a sample app with SDK 5.0.0 but the class seems to work with SDK 5.2.3 without any problems.
https://support.inmobi.com/monetize/integration/mediation-adapters/mopub-adaptor-android-sdk-integration-guide/#getting-started
I had to read the class and make my own adjustments to the adapter so that it will work - their adapter had issues as they were using deprecated classes. So here is the updated adapter:
package com.mopub.nativeads;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.inmobi.ads.InMobiAdRequestStatus;
import com.inmobi.sdk.InMobiSdk;
import com.mopub.common.MoPub;
import com.mopub.common.logging.MoPubLog;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.mopub.common.util.Json.getJsonValue;
import static com.mopub.common.util.Numbers.parseDouble;
import static com.mopub.nativeads.NativeImageHelper.preCacheImages;
/*
* Tested with InMobi SDK 5.2.3
*/
public class InMobiNative extends CustomEventNative {
private static boolean isAppIntialize = false;
private JSONObject serverParams;
private String accountId="XXX";
private long placementId=123L;
#Override
protected void loadNativeAd(#NonNull Activity arg0,
#NonNull CustomEventNativeListener arg1,
#NonNull Map<String, Object> arg2,
#NonNull Map<String, String> arg3) {
// TODO Auto-generated method stub
Log.d("InMobiNativeCustomEvent", "Reached native adapter");
try {
serverParams = new JSONObject(arg3);
} catch (Exception e) {
Log.e("InMobi", "Could not parse server parameters");
e.printStackTrace();
}
Activity activity = null;
if (arg0 instanceof Activity) {
activity = arg0;
} else {
// You may also pass in an Activity Context in the localExtras map
// and retrieve it here.
}
if (activity == null) {
arg1.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
return;
}
try {
accountId = serverParams.getString("accountid");
placementId = serverParams.getLong("placementId");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (!isAppIntialize) {
try {
InMobiSdk.init(activity,"accountid");
} catch (Exception e) {
e.printStackTrace();
}
isAppIntialize = true;
}
InMobiSdk.setAreaCode("areacode");
InMobiSdk.setEducation(InMobiSdk.Education.HIGH_SCHOOL_OR_LESS);
InMobiSdk.setGender(InMobiSdk.Gender.MALE);
InMobiSdk.setIncome(1000);
InMobiSdk.setAge(23);
InMobiSdk.setPostalCode("postalcode");
InMobiSdk.setLogLevel(InMobiSdk.LogLevel.DEBUG);
InMobiSdk.setLocationWithCityStateCountry("blore", "kar", "india");
InMobiSdk.setLanguage("ENG");
InMobiSdk.setInterests("dance");
InMobiSdk.setEthnicity(InMobiSdk.Ethnicity.ASIAN);
InMobiSdk.setYearOfBirth(1980);
Map<String, String> map = new HashMap<String, String>();
map.put("tp", "c_mopub");
map.put("tp-ver", MoPub.SDK_VERSION);
final InMobiStaticNativeAd inMobiStaticNativeAd =
new InMobiStaticNativeAd(arg0,
new ImpressionTracker(arg0),
new NativeClickHandler(arg0),
arg1);
inMobiStaticNativeAd.setIMNative(new com.inmobi.ads.InMobiNative(placementId, inMobiStaticNativeAd));
inMobiStaticNativeAd.setExtras(map);
inMobiStaticNativeAd.loadAd();
}
static class InMobiStaticNativeAd extends StaticNativeAd implements com.inmobi.ads.InMobiNative.NativeAdListener {
static final int IMPRESSION_MIN_TIME_VIEWED = 1000;
// Modifiable keys
static final String TITLE = "title";
static final String DESCRIPTION = "description";
static final String SCREENSHOTS = "screenshots";
static final String ICON = "icon";
static final String LANDING_URL = "landingURL";
static final String CTA = "cta";
static final String RATING = "rating";
// Constant keys
static final String URL = "url";
private final Context mContext;
private final CustomEventNativeListener mCustomEventNativeListener;
private final ImpressionTracker mImpressionTracker;
private final NativeClickHandler mNativeClickHandler;
private com.inmobi.ads.InMobiNative mImNative;
InMobiStaticNativeAd(final Context context,
final ImpressionTracker impressionTracker,
final NativeClickHandler nativeClickHandler,
final CustomEventNativeListener customEventNativeListener) {
InMobiSdk.init(context,"9107a61fcda34c969d3f74934a352dcb");
mContext = context.getApplicationContext();
mImpressionTracker = impressionTracker;
mNativeClickHandler = nativeClickHandler;
mCustomEventNativeListener = customEventNativeListener;
}
void setIMNative(final com.inmobi.ads.InMobiNative imNative) {
mImNative = imNative;
}
void setExtras(Map<String,String> map){
mImNative.setExtras(map);
}
void loadAd() {
mImNative.load();
}
// Lifecycle Handlers
#Override
public void prepare(final View view) {
if (view != null && view instanceof ViewGroup) {
com.inmobi.ads.InMobiNative.bind((ViewGroup)view, mImNative);
} else if (view != null && view.getParent() instanceof ViewGroup) {
com.inmobi.ads.InMobiNative.bind((ViewGroup)(view.getParent()), mImNative);
} else {
Log.e("MoPub", "InMobi did not receive ViewGroup to attachToView, unable to record impressions");
}
mImpressionTracker.addView(view, this);
mNativeClickHandler.setOnClickListener(view, this);
}
#Override
public void clear(final View view) {
mImpressionTracker.removeView(view);
mNativeClickHandler.clearOnClickListener(view);
}
#Override
public void destroy() {
//InMobiNative.unbind(arg0);
mImpressionTracker.destroy();
}
// Event Handlers
#Override
public void recordImpression(final View view) {
notifyAdImpressed();
}
#Override
public void handleClick(final View view) {
notifyAdClicked();
mNativeClickHandler.openClickDestinationUrl(getClickDestinationUrl(), view);
mImNative.reportAdClick(null);
}
void parseJson(final com.inmobi.ads.InMobiNative inMobiNative) throws JSONException {
final JSONTokener jsonTokener = new JSONTokener((String) inMobiNative.getAdContent());
final JSONObject jsonObject = new JSONObject(jsonTokener);
setTitle(getJsonValue(jsonObject, TITLE, String.class));
String text = getJsonValue(jsonObject, DESCRIPTION, String.class);
if(text!=null)
setText(text);
final JSONObject screenShotJsonObject = getJsonValue(jsonObject, SCREENSHOTS, JSONObject.class);
if (screenShotJsonObject != null) {
setMainImageUrl(getJsonValue(screenShotJsonObject, URL, String.class));
}
final JSONObject iconJsonObject = getJsonValue(jsonObject, ICON, JSONObject.class);
if (iconJsonObject != null) {
setIconImageUrl(getJsonValue(iconJsonObject, URL, String.class));
}
final String clickDestinationUrl = getJsonValue(jsonObject, LANDING_URL, String.class);
if (clickDestinationUrl == null) {
final String errorMessage = "InMobi JSON response missing required key: "
+ LANDING_URL + ". Failing over.";
MoPubLog.d(errorMessage);
throw new JSONException(errorMessage);
}
setClickDestinationUrl(clickDestinationUrl);
String cta = getJsonValue(jsonObject, CTA, String.class);
if(cta!=null)
setCallToAction(cta);
try {
if(jsonObject.opt(RATING)!=null){
setStarRating(parseDouble(jsonObject.opt(RATING)));
}
} catch (ClassCastException e) {
Log.d("MoPub", "Unable to set invalid star rating for InMobi Native.");
} setImpressionMinTimeViewed(IMPRESSION_MIN_TIME_VIEWED);
}
#Override
public void onAdDismissed(com.inmobi.ads.InMobiNative inMobiNative) {
// TODO Auto-generated method stub
Log.d("InMobiNativeCustomEvent","Native Ad is dismissed");
}
#Override
public void onAdDisplayed(com.inmobi.ads.InMobiNative inMobiNative) {
// TODO Auto-generated method stub
Log.d("InMobiNativeCustomEvent","Native Ad is displayed");
}
#Override
public void onAdLoadFailed(com.inmobi.ads.InMobiNative arg0, InMobiAdRequestStatus arg1) {
// TODO Auto-generated method stub
Log.d("InMobiNativeCustomEvent","Native ad failed to load");
String errorMsg="";
switch (arg1.getStatusCode()) {
case INTERNAL_ERROR:
errorMsg="INTERNAL_ERROR";
break;
case REQUEST_INVALID:
errorMsg="INVALID_REQUEST";
break;
case NETWORK_UNREACHABLE:
errorMsg="NETWORK_UNREACHABLE";
break;
case NO_FILL:
errorMsg="NO_FILL";
break;
case REQUEST_PENDING:
errorMsg="REQUEST_PENDING";
break;
case REQUEST_TIMED_OUT:
errorMsg="REQUEST_TIMED_OUT";
break;
case SERVER_ERROR:
errorMsg="SERVER_ERROR";
break;
case AD_ACTIVE:
errorMsg="AD_ACTIVE";
break;
case EARLY_REFRESH_REQUEST:
errorMsg="EARLY_REFRESH_REQUEST";
break;
default:
errorMsg="NETWORK_ERROR";
break;
}
if (errorMsg == "INVALID_REQUEST") {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_INVALID_REQUEST);
} else if (errorMsg == "INTERNAL_ERROR" || errorMsg == "NETWORK_ERROR") {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_INVALID_STATE);
} else if (errorMsg == "NO_FILL") {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_NO_FILL);
} else if (errorMsg == "REQUEST_TIMED_OUT"){
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_TIMEOUT);
}else if(errorMsg == "NETWORK_UNREACHABLE"){
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.CONNECTION_ERROR);
}
else {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.UNSPECIFIED);
}
}
#Override
public void onUserLeftApplication(com.inmobi.ads.InMobiNative arg0) {
// TODO Auto-generated method stub
Log.d("InMobiNativeCustomEvent","User left application");
}
#Override
public void onAdLoadSucceeded(com.inmobi.ads.InMobiNative inMobiNative) {
// TODO Auto-generated method stub
Log.v("InMobiNativeCustomEvent", "Ad loaded:"+inMobiNative.getAdContent().toString());
try {
parseJson(inMobiNative);
} catch (JSONException e) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.INVALID_RESPONSE);
return;
}
final List<String> imageUrls = new ArrayList<String>();
/*final String mainImageUrl = getMainImageUrl();
if (mainImageUrl != null) {
imageUrls.add(mainImageUrl);
}*/
final String iconUrl = getIconImageUrl();
if (iconUrl != null) {
imageUrls.add(iconUrl);
}
preCacheImages(mContext, imageUrls, new NativeImageHelper.ImageListener() {
#Override
public void onImagesCached() {
Log.v("InMobiNativeCustomEvent", "image cached");
mCustomEventNativeListener.onNativeAdLoaded(InMobiStaticNativeAd.this);
}
#Override
public void onImagesFailedToCache(NativeErrorCode errorCode) {
Log.v("InMobiNativeCustomEvent", "image failed to cache");
mCustomEventNativeListener.onNativeAdFailed(errorCode);
}
});
}
}
}
Then you need to read this website telling you more about how to integrate their SDK into your app. You need to copy and paste this into your manifest:
https://support.inmobi.com/android-sdk-integration-guide/#getting-started
<activity android:name="com.inmobi.rendering.InMobiAdActivity"
android:configChanges="keyboardHidden|orientation|keyboard|smallestScreenSize|screenSize"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:hardwareAccelerated="true" />
<receiver
android:name="com.inmobi.commons.core.utilities.uid.ImIdShareBroadCastReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.inmobi.share.id" />
</intent-filter>
</receiver>
Without these classes, the SDK will not initialize and you will get an error in the logs.
Please do read through both websites, I'm just dealing on a high level on how you can solve the integration but there are other stuff you should put into your app to make mopub work successfully with inmobi for Android.

Getting current value with Android Bluetooth LE Sample App

This is probably really straightforward, but I am new to Android and Bluetooth, and this has me lost.
I'm using the sample BluetoothLEGatt app as a starting point
http://developer.android.com/samples/BluetoothLeGatt/index.html
This allows you to select various characteristics from the connected Bluetooth LE device from an expandable list. Upon selecting the characteristic, the value is displayed in mDataField. I would like to just automatically display the heart rate measurement in the mDataField, without first having to select anything in the menu, but I can't figure out how the servicesListClickListner piece works.
Below is the DeviceControlActivity.java, which is the main screen
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.bluetooth.le;
import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* For a given BLE device, this Activity provides the user interface to connect, display data,
* and display GATT services and characteristics supported by the device. The Activity
* communicates with {#code BluetoothLeService}, which in turn interacts with the
* Bluetooth LE API.
*/
public class DeviceControlActivity extends Activity {
private final static String TAG = DeviceControlActivity.class.getSimpleName();
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
private TextView mConnectionState;
private TextView mDataField;
private String mDeviceName;
private String mDeviceAddress;
private ExpandableListView mGattServicesList;
private BluetoothLeService mBluetoothLeService;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
private boolean mConnected = false;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
// or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
// Show all the supported services and characteristics on the user interface.
displayGattServices(mBluetoothLeService.getSupportedGattServices());
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
// If a given GATT characteristic is selected, check for supported features. This sample
// demonstrates 'Read' and 'Notify' features. See
// http://d.android.com/reference/android/bluetooth/BluetoothGatt.html for the complete
// list of supported characteristic features.
private final ExpandableListView.OnChildClickListener servicesListClickListner =
new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
if (mGattCharacteristics != null) {
final BluetoothGattCharacteristic characteristic =
mGattCharacteristics.get(groupPosition).get(childPosition);
final int charaProp = characteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
// If there is an active notification on a characteristic, clear
// it first so it doesn't update the data field on the user interface.
if (mNotifyCharacteristic != null) {
mBluetoothLeService.setCharacteristicNotification(
mNotifyCharacteristic, false);
mNotifyCharacteristic = null;
}
mBluetoothLeService.readCharacteristic(characteristic);
}
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
mNotifyCharacteristic = characteristic;
mBluetoothLeService.setCharacteristicNotification(
characteristic, true);
}
return true;
}
return false;
}
};
private void clearUI() {
mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
mDataField.setText(R.string.no_data);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gatt_services_characteristics);
final Intent intent = getIntent();
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
// Sets up UI references.
((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
mGattServicesList = (ExpandableListView) findViewById(R.id.gatt_services_list);
mGattServicesList.setOnChildClickListener(servicesListClickListner);
mConnectionState = (TextView) findViewById(R.id.connection_state);
mDataField = (TextView) findViewById(R.id.data_value);
getActionBar().setTitle(mDeviceName);
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gatt_services, menu);
if (mConnected) {
menu.findItem(R.id.menu_connect).setVisible(false);
menu.findItem(R.id.menu_disconnect).setVisible(true);
} else {
menu.findItem(R.id.menu_connect).setVisible(true);
menu.findItem(R.id.menu_disconnect).setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_connect:
mBluetoothLeService.connect(mDeviceAddress);
return true;
case R.id.menu_disconnect:
mBluetoothLeService.disconnect();
return true;
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mConnectionState.setText(resourceId);
}
});
}
private void displayData(String data) {
if (data != null) {
mDataField.setText(data);
}
}
// Demonstrates how to iterate through the supported GATT Services/Characteristics.
// In this sample, we populate the data structure that is bound to the ExpandableListView
// on the UI.
private void displayGattServices(List<BluetoothGattService> gattServices) {
if (gattServices == null) return;
String uuid = null;
String unknownServiceString = getResources().getString(R.string.unknown_service);
String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
= new ArrayList<ArrayList<HashMap<String, String>>>();
mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
HashMap<String, String> currentServiceData = new HashMap<String, String>();
uuid = gattService.getUuid().toString();
currentServiceData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
currentServiceData.put(LIST_UUID, uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
new ArrayList<HashMap<String, String>>();
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas =
new ArrayList<BluetoothGattCharacteristic>();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap<String, String>();
uuid = gattCharacteristic.getUuid().toString();
currentCharaData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
currentCharaData.put(LIST_UUID, uuid);
gattCharacteristicGroupData.add(currentCharaData);
}
mGattCharacteristics.add(charas);
gattCharacteristicData.add(gattCharacteristicGroupData);
}
SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter(
this,
gattServiceData,
android.R.layout.simple_expandable_list_item_2,
new String[] {LIST_NAME, LIST_UUID},
new int[] { android.R.id.text1, android.R.id.text2 },
gattCharacteristicData,
android.R.layout.simple_expandable_list_item_2,
new String[] {LIST_NAME, LIST_UUID},
new int[] { android.R.id.text1, android.R.id.text2 }
);
mGattServicesList.setAdapter(gattServiceAdapter);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
return intentFilter;
}
}
And below is BluetoothLeService
package com.example.bluetooth.le;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.util.List;
import java.util.UUID;
/**
* Service for managing connection and data communication with a GATT server hosted on a
* given Bluetooth LE device.
*/
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private int mConnectionState = STATE_DISCONNECTED;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
public final static UUID UUID_HEART_RATE_MEASUREMENT =
UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
// Implements callback methods for GATT events that the app cares about. For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
};
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
// This is special handling for the Heart Rate Measurement profile. Data parsing is
// carried out as per profile specifications:
// http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
int flag = characteristic.getProperties();
int format = -1;
if ((flag & 0x01) != 0) {
format = BluetoothGattCharacteristic.FORMAT_UINT16;
Log.d(TAG, "Heart rate format UINT16.");
} else {
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Log.d(TAG, "Heart rate format UINT8.");
}
final int heartRate = characteristic.getIntValue(format, 1);
Log.d(TAG, String.format("Received heart rate: %d", heartRate));
intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
} else {
// For all other profiles, writes the data formatted in HEX.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for(byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
}
}
sendBroadcast(intent);
}
public class LocalBinder extends Binder {
BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
// After using a given device, you should make sure that BluetoothGatt.close() is called
// such that resources are cleaned up properly. In this particular example, close() is
// invoked when the UI is disconnected from the Service.
close();
return super.onUnbind(intent);
}
private final IBinder mBinder = new LocalBinder();
/**
* Initializes a reference to the local Bluetooth adapter.
*
* #return Return true if the initialization is successful.
*/
public boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* #param address The device address of the destination device.
*
* #return Return true if the connection is initiated successfully. The connection result
* is reported asynchronously through the
* {#code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The disconnection result
* is reported asynchronously through the
* {#code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
/**
* Request a read on a given {#code BluetoothGattCharacteristic}. The read result is reported
* asynchronously through the {#code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* callback.
*
* #param characteristic The characteristic to read from.
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
/**
* Enables or disables notification on a give characteristic.
*
* #param characteristic Characteristic to act on.
* #param enabled If true, enable notification. False otherwise.
*/
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
// This is specific to Heart Rate Measurement.
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
/**
* Retrieves a list of supported GATT services on the connected device. This should be
* invoked only after {#code BluetoothGatt#discoverServices()} completes successfully.
*
* #return A {#code List} of supported services.
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (mBluetoothGatt == null) return null;
return mBluetoothGatt.getServices();
}
}
The displayGattServices method populates your ExpandableListView with possible services. So you could just select the service that you want in this for loop:
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
if (uuid.equals("THE NAME OF THE SERVICE THAT I WANT") {
// and then call
mBluetoothLeService.setCharacteristicNotification(characteristic, true);
}
}
And then modify the displayData method if you need to.
The line:
int flag = characteristic.getProperties();
in the sample code is expected to return the bit mask for the supported characteristic fields. It doesn't. It returns the characteristic properties, like PROPERTY_NOTIFY.
To get the bit mask for the supported characteristic fields, in the case of the example's Heart Rate Measurement characteristic, the first value of the characteristic needs to be read and used.
Thus replacing the line
int flag = characteristic.getProperties();
with something like
byte[] charValue = characteristic.getValue();
byte flag = charValue[0];
will work correctly.

Categories

Resources