Util Class in Java - java

I want to know about the util Class used in Java. I am currently working on one Application in Android where I need to used a class from one file to another different file. I was told to import it like import com.android.utli.(ClassName) here the "com.android.util" is a package name.
Can I use that class in my another file simply by importing the package along with the class name?

Yes. After you import the class at the top of your java file like:
import android.util.Log;
You can then use it in your code.
Log.debug("MyActivity", "Thing I want to log");

The package is really a part of the "fully qualified class name". You can actually use that fully qualified name everywhere you use the class name, e.g.
com.android.util.UtilClass myUtil = new com.android.util.UtilClass();
But that's rather inconvenient. Therefore, classes in the same package (and in the package java.lang) can be used shorthand (i.e. only the class name) without imports. Classes from other packages have to be imported before they can be used that way.
It's just a way to organize the code and prevent problems when different programmers write classes with the same name - as long as they are in different packages, the collision can always be resolved by using the fully qualified class name.

public class SelectionListAdapter extends BaseAdapter {
private static final String TAG = SelectionListAdapter.class.getSimpleName();
private static LayoutInflater inflater = null;
// ArrayList<Selection> selections;
ArrayList<MultiSelection> multiselections;
ArrayList<MultiSelection> multiselectionsTemp;
Context mContext;
ArrayList<String> arrSelectedIDs;
ArrayList<String> arrSelectedNames;
String type;
public SelectionListAdapter(Activity ctx, ArrayList<MultiSelection> multiselections, String type) {
mContext = ctx;
inflater = (LayoutInflater) mContext.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// this.selections = selections;
this.multiselections = multiselections;
this.multiselectionsTemp = new ArrayList<>();
multiselectionsTemp.addAll(multiselections);
arrSelectedIDs = new ArrayList<>();
arrSelectedNames = new ArrayList<>();
this.type = type;
}
public int getCount() {
return multiselections.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final ViewHolder holder;
if (view == null) {
view = inflater.inflate(R.layout.selection_list_row, null);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.txt_item.setText(multiselections.get(i).name);
final MultiSelection multiSelection = multiselections.get(i);
if (multiSelection.isChecked) {
holder.check.setBackgroundResource(R.drawable.chacked);
if (!arrSelectedIDs.contains(multiSelection.id.trim()))
arrSelectedIDs.add(multiSelection.id.trim());
if (!arrSelectedNames.contains(multiSelection.name.trim()))
arrSelectedNames.add(multiSelection.name);
} else {
holder.check.setBackgroundResource(R.drawable.unchacked);
}
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (multiSelection.isChecked) {
holder.check.setBackgroundResource(R.drawable.unchacked);
arrSelectedIDs.remove(multiSelection.id.trim());
arrSelectedNames.remove(multiSelection.name);
if (type != null && type.equals("search")) {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS_SEARCH, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES_SEARCH, arrSelectedNames.toString());
} else {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES, arrSelectedNames.toString());
}
multiSelection.isChecked = false;
} else {
holder.check.setBackgroundResource(R.drawable.chacked);
arrSelectedIDs.add(multiSelection.id.trim());
arrSelectedNames.add(multiSelection.name);
if (type != null && type.equals("search")) {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS_SEARCH, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES_SEARCH, arrSelectedNames.toString());
} else {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES, arrSelectedNames.toString());
}
multiSelection.isChecked = true;
}
}
});
return view;
}
public class ViewHolder {
#InjectView(R.id.txt_item)
TextView txt_item;
#InjectView(R.id.check)
ImageView check;
public ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
// Filter method
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
multiselections.clear();
if (charText.length() == 0) {
multiselections.addAll(multiselectionsTemp);
} else {
for (MultiSelection wp : multiselectionsTemp) {
if (wp.name.toLowerCase(Locale.getDefault())
.contains(charText)) {
multiselections.add(wp);
}
}
}
notifyDataSetChanged();
}
}
public boolean isChecked;
private SwipeRefreshLayout swipeRefreshLayout;
implements SwipeRefreshLayout.OnRefreshListener
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setProgressBackgroundColor(R.color.colorPrimary);
swipeRefreshLayout.setColorSchemeColors(getActivity().getResources().getColor(R.color.color_white));
// swipeRefreshLayout.post(new Runnable()
// {
// #Override
// public void run()
// {
// swipeRefreshLayout.setRefreshing(true);
// }
// });
swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setRefreshing(false); // not call
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
if (Utils.isInternetConnected(getActivity())) {
getNearbyUserList();
} else {
MDToast mdToast = MDToast.makeText(getActivity(), "Please check the internet connection.",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
**Connection Detector Class**
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context context) {
this.context = context;
}
public static boolean isConnectingToInternet(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivityManager.getAllNetworks();
NetworkInfo networkInfo;
for (Network mNetwork : networks) {
networkInfo = connectivityManager.getNetworkInfo(mNetwork);
if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
return true;
}
}
} else {
if (connectivityManager != null) {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo anInfo : info) {
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
}
return false;
}
public boolean connectionDetected()
{
if (isConnectingToInternet(context)) {
return true;
} else {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.connection_checker);
dialog.setCancelable(false);
dialog.show();
Button ok = (Button) dialog.findViewById(R.id.dialog_ok);
Button cancel = (Button) dialog.findViewById(R.id.dialog_cancel);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
dialog.dismiss();
connectionDetected();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
return false;
}
}
}
**Datetime**
//Click
fromDatePickerDialog.show();
// Defin Oncreat()
private SimpleDateFormat dateFormatter;
dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
setDateTimeField();
private void setDateTimeField()
{
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
startDateTv.setText(dateFormatter.format(newDate.getTime()));
getDateTimeDifference();
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
toDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
endDateTv.setText(dateFormatter.format(newDate.getTime()));
getDateTimeDifference();
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
GLIDE_WITH BLUER
Glide.with(mContext)
.load(user.card_image.toString())
.bitmapTransform(new BlurTransformation(mContext))
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(((ItemTypeViewHolder) viewHolder).iv_card_pic);
if (!user.profile_image.toString().equals(""))
Glide.with(mContext)
.load(user.profile_image.toString()) // Uri of the picture
.into(holder.img_pp);
else
Glide.with(mContext)
.load(R.drawable.ico_profile_default) // Uri of the picture
.into(holder.img_pp);
Push Notification
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static int count = 0;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
Log.d(TAG, "Notification Message TITLE: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "Notification Message BODY: " + remoteMessage.getNotification().getBody());
Log.d(TAG, "Notification Message DATA: " + remoteMessage.getData().toString());
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(), remoteMessage.getData());
}
//This method is only generating push notification
private void sendNotification(String messageTitle, String messageBody, Map<String, String> row) {
PendingIntent contentIntent = null;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap))
.setSmallIcon(R.mipmap.)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(contentIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(count, notificationBuilder.build());
count++;
}
}
Snackbar
<string name="no_internet">It seems like there is problem with your internet connection</string>
Main View
android:id="#+id/ll_main"
llMain = findViewById(R.id.ll_main);
Snackbar snackbar = Snackbar.make(llMain, R.string.no_internet, Snackbar.LENGTH_LONG);
snackbar.show();
Custom Spinner
public void CustomSpinner() {
pd = new ProgressDialog(Over75Lakh.this);
pd.setIndeterminate(false);
pd.setMessage("Please Wait...");
pd.setCancelable(false);
pd.show();
ApiInterface apiServiceData =
ApiClient.getClient().create(ApiInterface.class);
Call<GetServicesMainResponse> callServices = apiServiceData.getServices();
callServices.enqueue(new Callback<GetServicesMainResponse>() {
#Override
public void onResponse(Call<GetServicesMainResponse> call, Response<GetServicesMainResponse> response) {
if ((pd != null) && pd.isShowing()) {
pd.dismiss();
}
getServices = new ArrayList<String>();
getServicesDataResponses = response.body().getData();
for (GetServicesDataResponse getServicesDataResponse : getServicesDataResponses) {
getServices.add(getServicesDataResponse.getServices());
}
ArrayAdapter<String> adapterServices = new ArrayAdapter<String>(Activit.this, android.R.layout.simple_spinner_item, getServices);
adapterServices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spMainService.setAdapter(adapterServices);
}
#Override
public void onFailure(Call<GetServicesMainResponse> call, Throwable t) {
pd.dismiss();
}
});
}
Get CallLogs.
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.CallLog;
public class CallLogHelper {
public static Cursor getAllCallLogs(ContentResolver cr) {
String strOrder = CallLog.Calls.DATE + " DESC"; // ASC --> then latest calls will get the latest txn no
Cursor curCallLogs = cr.query(CallLog.Calls.CONTENT_URI, null, null, null, strOrder);
return curCallLogs;
}
}
public class timer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
= new ArrayList<>();
}
#SuppressLint("DefaultLocale")
#Override
protected String doInBackground(String... params) {
if (ActivityCompat.checkSelfPermission(CallHistoryRevenueActivity.this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
return null;
}
Cursor managedCursor = CallLogHelper.getAllCallLogs(getContentResolver());
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
int callType11 = managedCursor.getColumnIndex(android.provider.CallLog.Calls.TYPE);
if (managedCursor.moveToFirst()) {
do {
String contactNumber = managedCursor.getString(number);
String callType = managedCursor.getString(callType11);
String callDate = managedCursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString(duration);
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = CallType.OUTGOING_CALL_END;
break;
case CallLog.Calls.INCOMING_TYPE:
dir = CallType.INCOMING_CALL_END;
break;
case CallLog.Calls.MISSED_TYPE:
dir = CallType.MISS_CALL;
break;
case CallLog.Calls.VOICEMAIL_TYPE:
dir = CallType.VoiceMail;
break;
case 5:
dir = CallType.Rejected;
break;
case 6:
dir = CallType.Refused;
break;
}
if (str_unit.equals("sec")) {
if (callDuration != null) {
if (callDuration.length() > 0) {
total_rate = ((str_def_Rate / str_per) * Integer.parseInt(callDuration));
sum_count_running = sum_count_running + total_rate;
publishProgress(String.valueOf(roundDouble(sum_count_running, 2)));
}
}
} else if (str_unit.equals("min")) {
if (callDuration != null) {
if (callDuration.length() > 0) {
total_rate = (((str_def_Rate / str_per) / 60) * Integer.parseInt(callDuration));
sum_count_running = sum_count_running + total_rate;
publishProgress(String.valueOf(roundDouble(sum_count_running, 2)));
}
}
} else if (str_unit.equals("hr")) {
if (callDuration != null) {
if (callDuration.length() > 0) {
total_rate = (((str_def_Rate / str_per) / 3600) * Integer.parseInt(callDuration));
sum_count_running = sum_count_running + total_rate;
publishProgress(String.valueOf(roundDouble(sum_count_running, 2)));
}
}
}
}
#Override
public void onFailure() {
}
});
}
while (managedCursor.moveToNext());
}
managedCursor.close();
// If the AsyncTask cancelled
if (isCancelled()) {
}
return "run";
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
setText(str_currency + " " + values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
finish();
}
}

JAVA utitlity / Helper Class is here
imports
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class is here
public class Utils {
/**
* Convertim to time format
*
* #param unix is time with long value
* #return string time
*/
public static String convertUnix2Date(long unix) {
if (unix == 0) return "";
String result;
Date date = new Date(TimeUnit.SECONDS.toMillis(unix));
#SuppressLint("SimpleDateFormat") SimpleDateFormat f = new SimpleDateFormat("HH:mm");
f.setTimeZone(TimeZone.getDefault());
result = f.format(date);
return result;
}
/**
* Handling the keyboard on device
*
* #param activity
*/
private static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
}
/**
* Handling the listener to dismiss the keyboard on device
*
* #param context <br>
* #param view is parent view <br>
*/
public static void setupDismissKeyboardListener(Context context, View view) {
// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener((v, event) -> {
hideSoftKeyboard((Activity) context);
return false;
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupDismissKeyboardListener(context, innerView);
}
}
}
/**
* Converting the DP value to PX to display on device
*
* #param context <br>
* #param value is DP value
* #return PX value
*/
public static int parseFromDPtoPX(Context context, float value) {
Resources resources = context.getResources();
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
value,
resources.getDisplayMetrics()
);
}
public static void setupUI(View view, final Activity activity) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener((v, event) -> {
hideSoftKeyboard(activity);
return false;
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView, activity);
}
}
}
/**
*
*/
protected Utils() {
}
public static final String TAG = "Utils";
public static final int DEFAULT_BUFFER_SIZE = 8192;
private static String sFormatEmail = "^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\\.[a-zA-Z]{2,4}$";
/**
* #return true if JellyBean or higher
*/
public static boolean isJellyBeanOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}
/**
* #return true if Ice Cream or higher
*/
public static boolean isICSOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
/**
* #return true if HoneyComb or higher
*/
public static boolean isHoneycombOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
/**
* #return true if GingerBreak or higher
*/
public static boolean isGingerbreadOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
/**
* #return true if Froyo or higher
*/
public static boolean isFroyoOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}
/**
* Check SdCard
*
* #return true if External Strorage available
*/
public static boolean isExtStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState());
}
/**
* Check internet
*
* #param context
* #return true if Network connected
*/
public static boolean isNetworkConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
return activeNetworkInfo.isConnected();
}
return false;
}
/**
* Check wifi
*
* #param context
* #return true if Wifi connected
*/
public static boolean isWifiConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetworkInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetworkInfo != null) {
return wifiNetworkInfo.isConnected();
}
return false;
}
/**
* Check on/off gps
*
* #return true if GPS available
*/
public static boolean checkAvailableGps(Context context) {
LocationManager manager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
/**
* Download data url
*
* #param urlString
* #return InputStream
* #throws IOException IOException
*/
/**
* #return an {#link HttpURLConnection} using sensible default settings for
* mobile and taking care of buggy behavior prior to Froyo.
* #throws IOException exception
*/
public static HttpURLConnection buildHttpUrlConnection(String urlString)
throws IOException {
Utils.disableConnectionReuseIfNecessary();
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoInput(true);
conn.setRequestMethod("GET");
return conn;
}
/**
* Prior to Android 2.2 (Froyo), {#link HttpURLConnection} had some
* frustrating bugs. In particular, calling close() on a readable
* InputStream could poison the connection pool. Work around this by
* disabling connection pooling.
*/
public static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (!isFroyoOrHigher()) {
System.setProperty("http.keepAlive", "false");
}
}
/**
* Check an email is valid or not
*
* #param email the email need to check
* #return {#code true} if valid, {#code false} if invalid
*/
public static boolean isValidEmail(Context context, String email) {
boolean result = false;
Pattern pt = Pattern.compile(sFormatEmail);
Matcher mt = pt.matcher(email);
if (mt.matches()) {
result = true;
}
return result;
}
/**
* A method to download json data from url
*/
#SuppressWarnings("ThrowFromFinallyBlock")
public static String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
assert iStream != null;
iStream.close();
urlConnection.disconnect();
}
return data;
}
}

*********************************************
Calling Api USing Retrofit
*********************************************
**Dependancies** :-
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.android.support:cardview-v7:27.1.1'
enter code here
**Model**
use the Pozo class
**Api Call**
-> getLogin() // use the method
//API call for Login
private void getLogin()
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("email_id", edit_email.getText().toString());
requestParams.put("password", edit_password.getText().toString());
Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
ShowProgress();
}
#Override
public void onFinish() {
super.onFinish();
Hideprogress();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("", "Login RESPONSE-" + response);
Login login = new Gson().fromJson(String.valueOf(response), Login.class);
edit_email.setText("");
edit_password.setText("");
if (login.getStatus().equals("true")) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
mdToast.show();
Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
hideKeyboard(SignInActivity.this);
Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("", throwable.getMessage());
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
});
}

**Q :- How to Calling a Api Using Retrofit in Android**
Library :-
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
**[1] Insert & Show Record :-**
*[i]ApiClient :-*
public class ApiClient
{
public static final String BASE_URL ="";
private static Retrofit retrofit = null;
public static Retrofit getClient()
{
if (retrofit == null)
{
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
*[ii]ApiInterface :-*
public interface ApiInterface
{
#FormUrlEncoded
#POST("api/name")
Call<MainStatus> getDetails(#FieldMap HashMap<String, String> params);
}
*[iii]MainStatus :-*
public class MainStatus
{
#SerializedName("status")
#Expose
private String status;
#SerializedName("msg")
#Expose
private String msg;
}
*[iv]MainActivity.java :-*
public class Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
new getData();
}
public void getData()
{
ApiInterface apiObj = ApiClient.getClient().create(ApiInterface.class);
//Optional
//HashMap<String, String> hashMap = new HashMap<>();
//hashMap.put("emp_id", read(USERID));
Call<MainStatus> call = apiObj.getDetails(hashMap);
call.enqueue(new Callback<MainStatus>()
{
#Override
public void onResponse(Call<MainStatus> call, Response<MainStatus> response)
{
Log.d("RESPONS#",""+response);
if (response.body().getStatus().equalsIgnoreCase("true"))
{
mainstatus= response.body().getDetails();
}
}
#Override
public void onFailure(Call<EmployeeLeaveMainDetails> call, Throwable t)
{
Toast.makeText(LeaveApplicationDetails.this, getString("Error"), Toast.LENGTH_SHORT).show();
}
});
}

Related

Variable is not reflecting the assigned value while working with retrofit library: Android

I am trying to get the photo of the day from bing using this url
http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US
I am having trouble saving the value of the url which i am getting through retrofit library.
This is my code:
MainActivity.class
package com.gadgetsaint.downloadmanagerexample;
import android.Manifest;
import android.app.DownloadManager;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
public class MainActivity extends AppCompatActivity {
private DownloadManager downloadManager;
private long refid;
private Uri Download_Uri;
String url,name;
ArrayList<Long> list = new ArrayList<>();
ApiInterface apiService;
TextView btnSingle ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiService=ApiClient.getClient().create(ApiInterface.class);
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
getImageUrl();
registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
//url is showing null value even after assigning the data obtained through json .
Download_Uri = Uri.parse(url);
btnSingle = (TextView) findViewById(R.id.single);
btnSingle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.clear();
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("Abhishek Adhikari's file Downloading " + name + ".png");
request.setDescription("Downloading " + name + ".jpg");
request.setVisibleInDownloadsUi(true);
request.setDestinationInExternalPublicDir(Environment.getExternalStorageState(), "/adhikariabhishek/" + "/" + name + ".jpg");
refid = downloadManager.enqueue(request);
Log.e("OUT", "" + refid);
list.add(refid);
}
});
// TextView btnMultiple = (TextView) findViewById(R.id.multiple);
if(!isStoragePermissionGranted())
{
}
/* btnMultiple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.clear();
for(int i = 0; i < 2; i++)
{
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("GadgetSaint Downloading " + "Sample_" + i + ".png");
request.setDescription("Downloading " + "Sample_" + i + ".png");
request.setVisibleInDownloadsUi(true);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/GadgetSaint/" + "/" + "Sample_" + i + ".png");
refid = downloadManager.enqueue(request);
Log.e("OUTNM", "" + refid);
list.add(refid);
}
}
});
*/
}
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
Log.e("IN", "" + referenceId);
list.remove(referenceId);
if (list.isEmpty())
{
Log.e("INSIDE", "" + referenceId);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FileDownloader")
.setContentText("All Download completed");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(455, mBuilder.build());
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onComplete);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
// permission granted
}
}
private void getImageUrl() {
Call<ImageModel> call = apiService.getImageDetails("js","0","1","en-US");
call.enqueue(new Callback<ImageModel>() {
#Override
public void onResponse(Response<ImageModel> response, Retrofit retrofit) {
try {
Toast.makeText(MainActivity.this, "inside onresponse()", Toast.LENGTH_SHORT).show();
url=response.body().getImages().get(0).getUrl().toString();
//Here variable "url" is showing the data obtained through json
// but not reflecting changes back in "oncreate" method when used with variable "Download_uri"
Toast.makeText(MainActivity.this, url, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(MainActivity.this, "Cannot download the image", Toast.LENGTH_SHORT).show();
}
});
}
#Subscribe(sticky = true,threadMode = ThreadMode.MAIN)
public void onMessage(String url){
Toast.makeText(MainActivity.this, "inside Eventbus : "+url+" ", Toast.LENGTH_SHORT).show();
}
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
}
ApiInterface.class
package com.gadgetsaint.downloadmanagerexample;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;
public interface ApiInterface {
#GET("HPImageArchive.aspx")
Call<ImageModel> getImageDetails(#Query("format") String format,
#Query("idx") String idx, #Query("n") String n, #Query("mkt") String
mkt);
}
ApiClient.class
package com.gadgetsaint.downloadmanagerexample;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
public class ApiClient {
public static final String BASE_URL = "http://www.bing.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
ImageModel.class
package com.gadgetsaint.downloadmanagerexample;
import java.util.List;
public class ImageModel {
/**
* images : [{"startdate":"20170920","fullstartdate":"201709200700","enddate":"20170921","url":"/az/hprichbg/rb/RotenbergVineyards_EN-US11270850012_1920x1080.jpg","urlbase":"/az/hprichbg/rb/RotenbergVineyards_EN-US11270850012","copyright":"Vineyards at Rotenberg in Baden-Württemberg, Germany (© Werner Dieterich/plainpicture)","copyrightlink":"http://www.bing.com/search?q=rotenberg+stuttgart&form=hpcapt&filters=HpDate:%2220170920_0700%22","quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20170920_RotenbergVineyards%22&FORM=HPQUIZ","wp":true,"hsh":"0b5b6af9429a1f1e53c494ee482c73bc","drk":1,"top":1,"bot":1,"hs":[]}]
* tooltips : {"loading":"Loading...","previous":"Previous image","next":"Next image","walle":"This image is not available to download as wallpaper.","walls":"Download this image. Use of this image is restricted to wallpaper only."}
*/
private TooltipsBean tooltips;
private List<ImagesBean> images;
public TooltipsBean getTooltips() {
return tooltips;
}
public void setTooltips(TooltipsBean tooltips) {
this.tooltips = tooltips;
}
public List<ImagesBean> getImages() {
return images;
}
public void setImages(List<ImagesBean> images) {
this.images = images;
}
public static class TooltipsBean {
/**
* loading : Loading...
* previous : Previous image
* next : Next image
* walle : This image is not available to download as wallpaper.
* walls : Download this image. Use of this image is restricted to wallpaper only.
*/
private String loading;
private String previous;
private String next;
private String walle;
private String walls;
public String getLoading() {
return loading;
}
public void setLoading(String loading) {
this.loading = loading;
}
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public String getWalle() {
return walle;
}
public void setWalle(String walle) {
this.walle = walle;
}
public String getWalls() {
return walls;
}
public void setWalls(String walls) {
this.walls = walls;
}
}
public static class ImagesBean {
/**
* startdate : 20170920
* fullstartdate : 201709200700
* enddate : 20170921
* url : /az/hprichbg/rb/RotenbergVineyards_EN-US11270850012_1920x1080.jpg
* urlbase : /az/hprichbg/rb/RotenbergVineyards_EN-US11270850012
* copyright : Vineyards at Rotenberg in Baden-Württemberg, Germany (© Werner Dieterich/plainpicture)
* copyrightlink : http://www.bing.com/search?q=rotenberg+stuttgart&form=hpcapt&filters=HpDate:%2220170920_0700%22
* quiz : /search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20170920_RotenbergVineyards%22&FORM=HPQUIZ
* wp : true
* hsh : 0b5b6af9429a1f1e53c494ee482c73bc
* drk : 1
* top : 1
* bot : 1
* hs : []
*/
private String startdate;
private String fullstartdate;
private String enddate;
private String url;
private String urlbase;
private String copyright;
private String copyrightlink;
private String quiz;
private boolean wp;
private String hsh;
private int drk;
private int top;
private int bot;
private List<?> hs;
public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getFullstartdate() {
return fullstartdate;
}
public void setFullstartdate(String fullstartdate) {
this.fullstartdate = fullstartdate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlbase() {
return urlbase;
}
public void setUrlbase(String urlbase) {
this.urlbase = urlbase;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getCopyrightlink() {
return copyrightlink;
}
public void setCopyrightlink(String copyrightlink) {
this.copyrightlink = copyrightlink;
}
public String getQuiz() {
return quiz;
}
public void setQuiz(String quiz) {
this.quiz = quiz;
}
public boolean isWp() {
return wp;
}
public void setWp(boolean wp) {
this.wp = wp;
}
public String getHsh() {
return hsh;
}
public void setHsh(String hsh) {
this.hsh = hsh;
}
public int getDrk() {
return drk;
}
public void setDrk(int drk) {
this.drk = drk;
}
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
public int getBot() {
return bot;
}
public void setBot(int bot) {
this.bot = bot;
}
public List<?> getHs() {
return hs;
}
public void setHs(List<?> hs) {
this.hs = hs;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.gadgetsaint.downloadmanagerexample.MainActivity">
<TextView
android:id="#+id/single"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#fff"
android:padding="20dp"
android:background="#ce3910"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download single file" />
</RelativeLayout>
There is some trouble with the getImageUrl() method in MainActivity.class.
Help me out guys!!
Replace your getImageUrl() like this
private String getImageUrl() {
String imurl;
Call<ImageModel> call = apiService.getImageDetails("js","0","1","en-US");
call.enqueue(new Callback<ImageModel>() {
#Override
public void onResponse(Response<ImageModel> response, Retrofit retrofit) {
try {
Toast.makeText(MainActivity.this, "inside onresponse()", Toast.LENGTH_SHORT).show();
imurl=response.body().getImages().get(0).getUrl().toString();
//Here variable "url" is showing the data obtained through json
// but not reflecting changes back in "oncreate" method when used with variable "Download_uri"
Toast.makeText(MainActivity.this, url, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(MainActivity.this, "Cannot download the image", Toast.LENGTH_SHORT).show();
}
});
return imurl;
}
and in oncreate change,
Download_Uri = Uri.parse(url);
by this
Download_Uri = Uri.parse(getImageUrl());

Android app crash on Bluetooth LE write

I am developing an Android app to control stepper motors via a Android Due and a Bluetooth HM-10 BLE module.
So far everything works, but there seems to be a problem on some devices, which cause the app to crash. On my Nexus 5 and 7 it is working fine, but for example on a Samsung Galaxy S5 it keeps crashing. All devices have Andoird 6.0.1, so they should be equal.
I am getting this error report from the user:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothGattCharacteristic.setValue(byte[])' on a null object reference
at pm.puremoco.BluetoothLeService.WriteValue(BluetoothLeService.java:70)
at pm.puremoco.frag_moviesetlinear$3.onFinish(frag_moviesetlinear.java:266)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
So the error is occuring, when opening, at "onCreateView". There is the command to transmit a value:
mBluetoothLeService.WriteValue("1900_" + String.valueOf(variables.vidUpdateIntervall) + "#");
Here is almost the full fragment:
public class frag_moviesetlinear extends Fragment {
public static final String methodtocall = "ooo";
private final static String TAG = DeviceControlFragment.class.getSimpleName();
public AlertDialog alertTransmitData;
public BluetoothLeService mBluetoothLeService; //TODO evtl. private
public String methodcalled = "aaa";
public String dataLineReceived;
public long countDownTimerDelay = 200;
public AlertDialog alertTimeTooShort;
NumberPicker noPick1 = null;
NumberPicker noPick2 = null;
NumberPicker noPick3 = null;
long alertTransmitDataLength = 21000;
DeviceControlFragment devConFrag;
double minTimeFactor = 0;
TextView vid_maxSpeedU;
TextView vid_maxSpeedV;
TextView vid_maxSpeedW;
TextView vid_maxSpeedX;
TextView vid_maxSpeedY;
TextView vid_maxSpeedZ;
TextView vid_maxSpeedUspline;
TextView vid_maxSpeedVspline;
TextView vid_maxSpeedWspline;
TextView vid_maxSpeedXspline;
TextView vid_maxSpeedYspline;
TextView vid_maxSpeedZspline;
TextView txt_vidDuration;
TextView txt_vidUpdateIntervall;
TextView txt_minTime;
int timeForCalculation = 0;
int calculatedSpeedU = 0;
int calculatedSpeedV = 0;
int calculatedSpeedW = 0;
int calculatedSpeedX = 0;
int calculatedSpeedY = 0;
int calculatedSpeedZ = 0;
boolean movingHome = false;
private String mDeviceAddress;
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");
getActivity().finish();
}
Log.e(TAG, "mBluetoothLeService is okay");
// Log.e(TAG, mDeviceAddress);
// Automatically connects to the device upon successful start-up initialization.
if (mDeviceAddress == "---") {
Toast.makeText(getActivity(), "Bluetooth-Device not selected!", Toast.LENGTH_SHORT).show();
} else {
mBluetoothLeService.connect(mDeviceAddress);
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private String mDeviceName;
private TextView mDataField;
private Button btn_vidSplineStart;
private Button btn_vidUpdateIntervalNeg;
private Button btn_vidUpdateIntervalPos;
private boolean mConnected = false;
// 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)) { //���ӳɹ�
Log.e(TAG, "Only gatt, just wait");
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { //�Ͽ�����
mConnected = false;
getActivity().invalidateOptionsMenu();
// btnSend.setEnabled(false);
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) //���Կ�ʼ�ɻ���
{
mConnected = true;
// mDataField.setText("");
// ShowDialog();
//btnSend.setEnabled(true);
Log.e(TAG, "In what we need");
getActivity().invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { //�յ�����
Log.e(TAG, "RECV DATA");
final String data = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
Log.e(TAG, data);
if (data != null && data.substring(0, 1).equals("#") && data.substring(data.length() - 1).equals("$")) {
// if (mDataField.length() > 500)
// mDataField.setText("");
// mDataField.append(data);
dataLineReceived = data.substring(1, data.length() - 1);
ActionHandlerDataReceived();
}
}
}
};
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);
intentFilter.addAction(BluetoothDevice.ACTION_UUID);
return intentFilter;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final Intent intent = getActivity().getIntent();
// mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
// mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
mDeviceAddress = variables.BluetoothAddress;
mDeviceName = variables.BluetoothName;
methodcalled = intent.getStringExtra(methodtocall);
Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
Log.d(TAG, "Try to bindService=" + getActivity().bindService(gattServiceIntent, mServiceConnection, getActivity().BIND_AUTO_CREATE));
getActivity().registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public void onPause() {
super.onPause();
try {
getActivity().unregisterReceiver(mGattUpdateReceiver);
}
catch(Exception e){
}
try {
getActivity().unbindService(mServiceConnection);
}
catch(Exception e){
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "We are in destroy");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.setmovie, null);
vid_maxSpeedU = (TextView) layout.findViewById(R.id.vid_maxSpeedU);
vid_maxSpeedU.setText(String.valueOf(variables.speedU));
vid_maxSpeedV = (TextView) layout.findViewById(R.id.vid_maxSpeedV);
vid_maxSpeedV.setText(String.valueOf(variables.speedV));
vid_maxSpeedW = (TextView) layout.findViewById(R.id.vid_maxSpeedW);
vid_maxSpeedW.setText(String.valueOf(variables.speedW));
vid_maxSpeedX = (TextView) layout.findViewById(R.id.vid_maxSpeedX);
vid_maxSpeedX.setText(String.valueOf(variables.speedX));
vid_maxSpeedY = (TextView) layout.findViewById(R.id.vid_maxSpeedY);
vid_maxSpeedY.setText(String.valueOf(variables.speedY));
vid_maxSpeedZ = (TextView) layout.findViewById(R.id.vid_maxSpeedZ);
vid_maxSpeedZ.setText(String.valueOf(variables.speedZ));
double duration = 3700 * (double) variables.vidUpdateIntervall / 1000;
txt_vidUpdateIntervall = (TextView) layout.findViewById(R.id.txt_vidUpdateIntervall);
txt_vidUpdateIntervall.setText(String.valueOf(variables.vidUpdateIntervall));
txt_vidDuration = (TextView) layout.findViewById(R.id.txt_vidDuration);
txt_vidDuration.setText(String.format("%.2f", duration) + " s");
vid_maxSpeedUspline = (TextView) layout.findViewById(R.id.vid_maxSpeedUspline);
vid_maxSpeedVspline = (TextView) layout.findViewById(R.id.vid_maxSpeedVspline);
vid_maxSpeedWspline = (TextView) layout.findViewById(R.id.vid_maxSpeedWspline);
vid_maxSpeedXspline = (TextView) layout.findViewById(R.id.vid_maxSpeedXspline);
vid_maxSpeedYspline = (TextView) layout.findViewById(R.id.vid_maxSpeedYspline);
vid_maxSpeedZspline = (TextView) layout.findViewById(R.id.vid_maxSpeedZspline);
txt_minTime = (TextView) layout.findViewById(R.id.txt_minTime);
btn_vidSplineStart = (Button) layout.findViewById(R.id.btn_vidSplineStart);
btn_vidSplineStart.setOnClickListener(new event_btn_vidSplineStart());
btn_vidUpdateIntervalPos = (Button) layout.findViewById(R.id.btn_vidUpdateIntervalPos);
btn_vidUpdateIntervalPos.setOnClickListener(new event_btn_vidUpdateIntervalPos());
btn_vidUpdateIntervalNeg = (Button) layout.findViewById(R.id.btn_vidUpdateIntervalNeg);
btn_vidUpdateIntervalNeg.setOnClickListener(new event_btn_vidUpdateIntervalNeg());
//-----start-button------
minTimeFactor = 0;
timeForCalculation = variables.vidUpdateIntervall;
new CountDownTimer(countDownTimerDelay * 1, 1) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
mBluetoothLeService.WriteValue("1900_" + String.valueOf(variables.vidUpdateIntervall) + "#");
}
}.start();
new CountDownTimer(countDownTimerDelay * 2, 1) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
mBluetoothLeService.WriteValue("2000_" + String.valueOf(variables.linearWithFade) + "#");
}
}.start();
//-----start-button------
transmitDataAlert("calculation");
return layout;
}
private void ActionHandlerDataReceived() {
String variable;
String value;
String[] parts = dataLineReceived.split("_"); // escape .
variable = parts[0];
value = parts[1];
switch (variable) {
case "vidMaxSpeedU":
vid_maxSpeedUspline.setText(String.valueOf(value));
variables.vid_maxSpeedUspline = Integer.parseInt(value);
calculatedSpeedU = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedU) {
vid_maxSpeedUspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedUspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorU = Double.valueOf(value) / variables.speedU;
if (minTimeFactor < FactorU) {
minTimeFactor = FactorU;
}
break;
case "vidMaxSpeedV":
vid_maxSpeedVspline.setText(String.valueOf(value));
variables.vid_maxSpeedVspline = Integer.parseInt(value);
calculatedSpeedV = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedV) {
vid_maxSpeedVspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedVspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorV = Double.valueOf(value) / variables.speedV;
if (minTimeFactor < FactorV) {
minTimeFactor = FactorV;
}
break;
case "vidMaxSpeedW":
vid_maxSpeedWspline.setText(String.valueOf(value));
variables.vid_maxSpeedWspline = Integer.parseInt(value);
calculatedSpeedW = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedW) {
vid_maxSpeedWspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedWspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorW = Double.valueOf(value) / variables.speedW;
if (minTimeFactor < FactorW) {
minTimeFactor = FactorW;
}
break;
case "vidMaxSpeedX":
vid_maxSpeedXspline.setText(String.valueOf(value));
variables.vid_maxSpeedXspline = Integer.parseInt(value);
calculatedSpeedX = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedX) {
vid_maxSpeedXspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedXspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorX = Double.valueOf(value) / variables.speedX;
if (minTimeFactor < FactorX) {
minTimeFactor = FactorX;
}
break;
case "vidMaxSpeedY":
vid_maxSpeedYspline.setText(String.valueOf(value));
variables.vid_maxSpeedYspline = Integer.parseInt(value);
calculatedSpeedY = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedY) {
vid_maxSpeedYspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedYspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorY = Double.valueOf(value) / variables.speedY;
if (minTimeFactor < FactorY) {
minTimeFactor = FactorY;
}
break;
case "vidMaxSpeedZ":
vid_maxSpeedZspline.setText(String.valueOf(value));
variables.vid_maxSpeedZspline = Integer.parseInt(value);
calculatedSpeedZ = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedZ) {
vid_maxSpeedZspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedZspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorZ = Double.valueOf(value) / variables.speedZ;
if (minTimeFactor < FactorZ) {
minTimeFactor = FactorZ;
}
alertTransmitData.dismiss();
double vidMin = Math.ceil(minTimeFactor * timeForCalculation);
variables.vidMinIntervall = (int) vidMin;
//txt_minTime.setText(String.valueOf(variables.vidMinIntervall));
double duration = (3700 * (double) variables.vidMinIntervall) / 1000;
txt_minTime.setText(String.format("%.2f", duration) + " s");
if(variables.vidMinIntervall<=variables.vidUpdateIntervall) {
btn_vidSplineStart.setEnabled(true);
}
break;
case "movieFinished":
btn_vidSplineStart.setText("Move home");
btn_vidSplineStart.setEnabled(true);
movingHome = true;
alertTransmitData.dismiss();
break;
case "movieHome":
btn_vidSplineStart.setText("Start");
btn_vidSplineStart.setEnabled(true);
alertTransmitData.dismiss();
break;
}
}
void calculateNewSpeeds() {
//--------------U-Axis-----------------
if (variables.vid_maxSpeedUspline != 0) {
variables.vid_maxSpeedUspline = (timeForCalculation * calculatedSpeedU) / variables.vidUpdateIntervall;
vid_maxSpeedUspline.setText(String.valueOf(variables.vid_maxSpeedUspline));
if (variables.vid_maxSpeedUspline > variables.speedU) {
vid_maxSpeedUspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedUspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
//--------------V-Axis-----------------
if (variables.vid_maxSpeedVspline != 0) {
variables.vid_maxSpeedVspline = (timeForCalculation * calculatedSpeedV) / variables.vidUpdateIntervall;
vid_maxSpeedVspline.setText(String.valueOf(variables.vid_maxSpeedVspline));
if (variables.vid_maxSpeedVspline > variables.speedV) {
vid_maxSpeedVspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedVspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
//--------------W-Axis-----------------
if (variables.vid_maxSpeedWspline != 0) {
variables.vid_maxSpeedWspline = (timeForCalculation * calculatedSpeedW) / variables.vidUpdateIntervall;
vid_maxSpeedWspline.setText(String.valueOf(variables.vid_maxSpeedWspline));
if (variables.vid_maxSpeedWspline > variables.speedW) {
vid_maxSpeedWspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedWspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
//--------------X-Axis-----------------
if (variables.vid_maxSpeedXspline != 0) {
variables.vid_maxSpeedXspline = (timeForCalculation * calculatedSpeedX) / variables.vidUpdateIntervall;
vid_maxSpeedXspline.setText(String.valueOf(variables.vid_maxSpeedXspline));
if (variables.vid_maxSpeedXspline > variables.speedX) {
vid_maxSpeedXspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedXspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
//--------------Y-Axis-----------------
if (variables.vid_maxSpeedYspline != 0) {
variables.vid_maxSpeedYspline = (timeForCalculation * calculatedSpeedY) / variables.vidUpdateIntervall;
vid_maxSpeedYspline.setText(String.valueOf(variables.vid_maxSpeedYspline));
if (variables.vid_maxSpeedYspline > variables.speedY) {
vid_maxSpeedYspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedYspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
//--------------Z-Axis-----------------
if (variables.vid_maxSpeedZspline != 0) {
variables.vid_maxSpeedZspline = (timeForCalculation * calculatedSpeedZ) / variables.vidUpdateIntervall;
vid_maxSpeedZspline.setText(String.valueOf(variables.vid_maxSpeedZspline));
if (variables.vid_maxSpeedZspline > variables.speedZ) {
vid_maxSpeedZspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedZspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
}
public void alert_TimeTooShort(int errorCase, int movieLengthSecondsNEW) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
// set title
alertDialogBuilder.setTitle("Error");
String errorMessage = "error";
// set dialog message
alertDialogBuilder
.setMessage(errorMessage)
.setCancelable(false);
alertDialogBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
});
// create alert dialog
alertTimeTooShort = alertDialogBuilder.create();
// show it
alertTimeTooShort.show();
}
public void transmitDataAlert(String type) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View promptView = layoutInflater.inflate(R.layout.alert_transmitdata, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setView(promptView);
final ProgressBar progressbar = (ProgressBar) promptView.findViewById(R.id.progressBar_transmitData);
final TextView txt_PleaseWait = (TextView) promptView.findViewById(R.id.txt_PleaseWait);
final TextView txt_timeRemainVideo = (TextView) promptView.findViewById(R.id.txt_timeRemainVideo);
final TextView txt_timeRemainVideoTXT = (TextView) promptView.findViewById(R.id.txt_timeRemainVideoTXT);
new CountDownTimer(alertTransmitDataLength, 1) {
public void onTick(long millisUntilFinished) {
int longtointRemain = (int) millisUntilFinished;
int longtointFull = (int) alertTransmitDataLength;
int percentprogress = 100 - ((100 * longtointRemain) / longtointFull);
progressbar.setProgress(percentprogress);
float duration = (float) millisUntilFinished/1000;
txt_timeRemainVideo.setText(String.format("%.1f", duration) + " s");
}
public void onFinish() {
}
}.start();
}
alertDialogBuilder.setCancelable(false);
alertTransmitData = alertDialogBuilder.create();
alertTransmitData.show();
}
class event_btn_vidSplineStart implements View.OnClickListener {
#Override
public void onClick(View v) {
btn_vidSplineStart.setEnabled(false);
btn_vidSplineStart.setText("Moving...");
new CountDownTimer(countDownTimerDelay * 1, 1) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//MotionMode
mBluetoothLeService.WriteValue("1900_" + String.valueOf(variables.vidUpdateIntervall) + "#");
}
}.start();
new CountDownTimer(countDownTimerDelay * 2, 1) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//MotionMode
mBluetoothLeService.WriteValue("1110_0#");
}
}.start();
alertTransmitDataLength = (long) variables.vidUpdateIntervall*3700;
if(movingHome==true){
transmitDataAlert("moveHome");
movingHome=false;
}
else {
transmitDataAlert("videomove");
}
}
}
class event_btn_vidUpdateIntervalPos implements View.OnClickListener {
#Override
public void onClick(View v) {
variables.vidUpdateIntervall++;
double duration = (3700 * (double) variables.vidUpdateIntervall) / 1000;
txt_vidDuration.setText(String.format("%.2f", duration) + " s");
txt_vidUpdateIntervall.setText(String.valueOf(variables.vidUpdateIntervall));
calculateNewSpeeds();
if(variables.vidMinIntervall<=variables.vidUpdateIntervall) {
btn_vidSplineStart.setEnabled(true);
}
else{
btn_vidSplineStart.setEnabled(false);
}
}
}
class event_btn_vidUpdateIntervalNeg implements View.OnClickListener {
#Override
public void onClick(View v) {
if (variables.vidUpdateIntervall > 1) {
variables.vidUpdateIntervall--;
}
double duration = (3700 * (double) variables.vidUpdateIntervall) / 1000;
txt_vidDuration.setText(String.format("%.2f", duration) + " s");
txt_vidUpdateIntervall.setText(String.valueOf(variables.vidUpdateIntervall));
calculateNewSpeeds();
if(variables.vidMinIntervall<=variables.vidUpdateIntervall) {
btn_vidSplineStart.setEnabled(true);
}
else{
btn_vidSplineStart.setEnabled(false);
}
}
}
}
And here is the full BluetoothLeService, which I got from the website of the HM-10 Bluetooth manufacturer:
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 android.widget.Toast;
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 BluetoothGatt mBluetoothGatt;
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_NOTIFY =
UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
public final static UUID UUID_SERVICE =
UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");
public BluetoothGattCharacteristic mNotifyCharacteristic;
public void WriteValue(String strValue)
{
mNotifyCharacteristic.setValue(strValue.getBytes());
mBluetoothGatt.writeCharacteristic(mNotifyCharacteristic);
}
public void findService(List<BluetoothGattService> gattServices)
{
Log.i(TAG, "Count is:" + gattServices.size());
for (BluetoothGattService gattService : gattServices)
{
Log.i(TAG, gattService.getUuid().toString());
Log.i(TAG, UUID_SERVICE.toString());
if(gattService.getUuid().toString().equalsIgnoreCase(UUID_SERVICE.toString()))
{
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
Log.i(TAG, "Count is:" + gattCharacteristics.size());
for (BluetoothGattCharacteristic gattCharacteristic :
gattCharacteristics)
{
if(gattCharacteristic.getUuid().toString().equalsIgnoreCase(UUID_NOTIFY.toString()))
{
Log.i(TAG, gattCharacteristic.getUuid().toString());
Log.i(TAG, UUID_NOTIFY.toString());
mNotifyCharacteristic = gattCharacteristic;
setCharacteristicNotification(gattCharacteristic, true);
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
return;
}
}
}
}
}
// 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;
Log.i(TAG, "oldStatus=" + status + " NewStates=" + newState);
if(status == BluetoothGatt.GATT_SUCCESS)
{
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_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;
mBluetoothGatt.close();
mBluetoothGatt = null;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.w(TAG, "onServicesDiscovered received: " + status);
findService(gatt.getServices());
} else {
if(mBluetoothGatt.getDevice().getUuids() == null)
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);
Log.e(TAG, "OnCharacteristicWrite");
}
#Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
int status)
{
Log.e(TAG, "OnCharacteristicWrite");
}
#Override
public void onDescriptorRead(BluetoothGatt gatt,
BluetoothGattDescriptor bd,
int status) {
Log.e(TAG, "onDescriptorRead");
}
#Override
public void onDescriptorWrite(BluetoothGatt gatt,
BluetoothGattDescriptor bd,
int status) {
Log.e(TAG, "onDescriptorWrite");
}
#Override
public void onReadRemoteRssi(BluetoothGatt gatt, int a, int b)
{
Log.e(TAG, "onReadRemoteRssi");
}
#Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int a)
{
Log.e(TAG, "onReliableWriteCompleted");
}
};
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
// 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());
intent.putExtra(EXTRA_DATA, new String(data));
}
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;
}
}
*/
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.
if(mBluetoothGatt != null)
{
mBluetoothGatt.close();
mBluetoothGatt = null;
}
mBluetoothGatt = device.connectGatt(this.getApplication(), false, mGattCallback);
//mBluetoothGatt.connect();
Log.d(TAG, "Trying to create a new connection.");
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();
}
}

Qr scanner scanned result in fragment

I am beginner to android..I integrated qr scanner ZXING library in my app..in fragment layout..this library working..On click button..qr scanner is opening..but scanned result is not displaying inside edit text in fragment layout..how to display result in fragment?
below is my On click button code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = null;
view = inflater.inflate(R.layout.configure_switch,container,false);
button = (Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(getActivity());
integrator.initiateScan();
}
});
it's simple. after getting scanned result, you need to put the following code.
YourEditTextName.setText(ResultText);
look as my related answer here,
[ https://stackoverflow.com/a/36788367/3981656 ]
here is the full code,
MainActivity.java
package futurevision.jsk.barcodesanner;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn;
private TextView formatTxt, contentTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scanBtn = (Button)findViewById(R.id.scan_button);
formatTxt = (TextView)findViewById(R.id.scan_format);
contentTxt = (TextView)findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
}
public void onClick(View v){
if(v.getId()==R.id.scan_button){
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
IntentIntegrator.java
package com.google.zxing.integration.android;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class IntentIntegrator {
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
private static final String TAG = IntentIntegrator.class.getSimpleName();
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
public static final String DEFAULT_MESSAGE =
"This application requires Barcode Scanner. Would you like to install it?";
public static final String DEFAULT_YES = "Yes";
public static final String DEFAULT_NO = "No";
private static final String BS_PACKAGE = "com.google.zxing.client.android";
private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
// supported barcode formats
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
public static final Collection<String> ONE_D_CODE_TYPES =
list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
"ITF", "RSS_14", "RSS_EXPANDED");
public static final Collection<String> QR_CODE_TYPES = Collections.singleton("QR_CODE");
public static final Collection<String> DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
public static final Collection<String> ALL_CODE_TYPES = null;
public static final List<String> TARGET_BARCODE_SCANNER_ONLY = Collections.singletonList(BS_PACKAGE);
public static final List<String> TARGET_ALL_KNOWN = list(
BS_PACKAGE, // Barcode Scanner
BSPLUS_PACKAGE, // Barcode Scanner+
BSPLUS_PACKAGE + ".simple" // Barcode Scanner+ Simple
// What else supports this intent?
);
private final Activity activity;
private String title;
private String message;
private String buttonYes;
private String buttonNo;
private List<String> targetApplications;
private final Map<String,Object> moreExtras;
public IntentIntegrator(Activity activity) {
this.activity = activity;
title = DEFAULT_TITLE;
message = DEFAULT_MESSAGE;
buttonYes = DEFAULT_YES;
buttonNo = DEFAULT_NO;
targetApplications = TARGET_ALL_KNOWN;
moreExtras = new HashMap<String,Object>(3);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitleByID(int titleID) {
title = activity.getString(titleID);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setMessageByID(int messageID) {
message = activity.getString(messageID);
}
public String getButtonYes() {
return buttonYes;
}
public void setButtonYes(String buttonYes) {
this.buttonYes = buttonYes;
}
public void setButtonYesByID(int buttonYesID) {
buttonYes = activity.getString(buttonYesID);
}
public String getButtonNo() {
return buttonNo;
}
public void setButtonNo(String buttonNo) {
this.buttonNo = buttonNo;
}
public void setButtonNoByID(int buttonNoID) {
buttonNo = activity.getString(buttonNoID);
}
public Collection<String> getTargetApplications() {
return targetApplications;
}
public final void setTargetApplications(List<String> targetApplications) {
if (targetApplications.isEmpty()) {
throw new IllegalArgumentException("No target applications");
}
this.targetApplications = targetApplications;
}
public void setSingleTargetApplication(String targetApplication) {
this.targetApplications = Collections.singletonList(targetApplication);
}
public Map<String,?> getMoreExtras() {
return moreExtras;
}
public final void addExtra(String key, Object value) {
moreExtras.put(key, value);
}
public final AlertDialog initiateScan() {
return initiateScan(ALL_CODE_TYPES);
}
public final AlertDialog initiateScan(Collection<String> desiredBarcodeFormats) {
Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// check which types of codes to scan for
if (desiredBarcodeFormats != null) {
// set the desired barcode types
StringBuilder joinedByComma = new StringBuilder();
for (String format : desiredBarcodeFormats) {
if (joinedByComma.length() > 0) {
joinedByComma.append(',');
}
joinedByComma.append(format);
}
intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
}
String targetAppPackage = findTargetAppPackage(intentScan);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intentScan.setPackage(targetAppPackage);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intentScan);
startActivityForResult(intentScan, REQUEST_CODE);
return null;
}
protected void startActivityForResult(Intent intent, int code) {
activity.startActivityForResult(intent, code);
}
private String findTargetAppPackage(Intent intent) {
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (availableApps != null) {
for (ResolveInfo availableApp : availableApps) {
String packageName = availableApp.activityInfo.packageName;
if (targetApplications.contains(packageName)) {
return packageName;
}
}
}
return null;
}
private AlertDialog showDownloadDialog() {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String packageName = targetApplications.get(0);
Uri uri = Uri.parse("market://details?id=" + packageName);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
// Hmm, market is not installed
Log.w(TAG, "Google Play is not installed; cannot install " + packageName);
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {}
});
return downloadDialog.show();
}
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents,
formatName,
rawBytes,
orientation,
errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
public final AlertDialog shareText(CharSequence text, CharSequence type) {
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setAction(BS_PACKAGE + ".ENCODE");
intent.putExtra("ENCODE_TYPE", type);
intent.putExtra("ENCODE_DATA", text);
String targetAppPackage = findTargetAppPackage(intent);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intent.setPackage(targetAppPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intent);
activity.startActivity(intent);
return null;
}
private static List<String> list(String... values) {
return Collections.unmodifiableList(Arrays.asList(values));
}
private void attachMoreExtras(Intent intent) {
for (Map.Entry<String,Object> entry : moreExtras.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// Kind of hacky
if (value instanceof Integer) {
intent.putExtra(key, (Integer) value);
} else if (value instanceof Long) {
intent.putExtra(key, (Long) value);
} else if (value instanceof Boolean) {
intent.putExtra(key, (Boolean) value);
} else if (value instanceof Double) {
intent.putExtra(key, (Double) value);
} else if (value instanceof Float) {
intent.putExtra(key, (Float) value);
} else if (value instanceof Bundle) {
intent.putExtra(key, (Bundle) value);
} else {
intent.putExtra(key, value.toString());
}
}
}
}
IntentResult.java
package com.google.zxing.integration.android;
public final class IntentResult {
private final String contents;
private final String formatName;
private final byte[] rawBytes;
private final Integer orientation;
private final String errorCorrectionLevel;
IntentResult() {
this(null, null, null, null, null);
}
IntentResult(String contents,
String formatName,
byte[] rawBytes,
Integer orientation,
String errorCorrectionLevel) {
this.contents = contents;
this.formatName = formatName;
this.rawBytes = rawBytes;
this.orientation = orientation;
this.errorCorrectionLevel = errorCorrectionLevel;
}
public String getContents() {
return contents;
}
public String getFormatName() {
return formatName;
}
public byte[] getRawBytes() {
return rawBytes;
}
public Integer getOrientation() {
return orientation;
}
public String getErrorCorrectionLevel() {
return errorCorrectionLevel;
}
#Override
public String toString() {
StringBuilder dialogText = new StringBuilder(100);
dialogText.append("Format: ").append(formatName).append('\n');
dialogText.append("Contents: ").append(contents).append('\n');
int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
dialogText.append("Orientation: ").append(orientation).append('\n');
dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
return dialogText.toString();
}
}
Happy coding.!!!
when you receive the result to a activity get the current fragment and call that method like below
CustomFragmentClass will be your fragment.
Fragment fragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof CustomFragmentClass){
fragment.onActivityResult(int requestCode, int resultCode, Intent data);
}
or you can also refer this onActivityResult is not being called in Fragment

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