[Q] need to get num of satelites and HDOP - Java for Android App Development

'm trying to write app which will get the number of satellites and the HDOP.
my main activity implements GpsStatus.Listener and GpsStatus.NmeaListener.
however, even though there is GPS activity in my device , the methods
onGpsStatusChanged onNmeaReceived
are never getting called.
why?
here is my code:
public class MainActivity extends ActionBarActivity implements
GpsStatus.Listener,GpsStatus.NmeaListener {
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UpdateLocation();
}
public void UpdateLocation() {
locationManager = (LocationManager) getSystemService(this.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
@override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
float speed = location.getSpeed();
float heading=location.getBearing();
float acc= location.getAccuracy();
L.m(""+acc);
//Log.d("YANIV", "latitude : "+latitude);
//Log.d("YANIV","longitude : "+longitude);
//Log.d("YANIV","speed : "+speed);
//Log.d("YANIV","heading : "+heading);
//Log.d("YANIV","GPS LOCKED? :" + locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
};
};
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000,
// 0, locationListener);
}
@override
public void onGpsStatusChanged(int event) {
GpsStatus gpsStatus = locationManager.getGpsStatus(null);
if(gpsStatus != null) {
Iterable<GpsSatellite>satellites = gpsStatus.getSatellites();
Iterator<GpsSatellite>sat = satellites.iterator();
int i=0;
while (sat.hasNext()) {
GpsSatellite satellite = sat.next();
L.m((i++) + ": " + satellite.getPrn() + "," + satellite.usedInFix() + "," + satellite.getSnr() + "," + satellite.getAzimuth() + "," + satellite.getElevation()+ "\n\n");
}
}
}
@override
public void onNmeaReceived(long timestamp, String nmea) {
L.m(nmea);
}

Related

Playing videos using mediastore with custom player

Not that anyone will actually reply but I'm about to go insane to be honest, ALL i want to do is play a video from a list view using media store and a custom video player (Not stock player!) but so far all my attempts have failed.
So i need some professional help!
My MediaStore code:
Code:
public class VideoManager {
public VideoManager() {
}
private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
public ArrayList<HashMap<String, String>> getPlayList(Context c) {
/*use content provider to get beginning of database query that queries for all audio by display name, path
and mimtype which i dont use but got it incase you want to scan for mp3 files only you can compare with RFC mimetype for mp3's
*/
final Cursor mCursor = c.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA}, null, null,
"UPPER(" + MediaStore.Video.Media.TITLE + ") ASC");
String videoTitle = "";
String videoPath = "";
/* run through all the columns we got back and save the data we need into the arraylist for our listview*/
if (mCursor.moveToFirst()) {
do {
videoTitle = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));
videoPath = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
HashMap<String, String> video = new HashMap<String, String>();
video.put("videoTitle", videoTitle);
video.put("videoPath", videoPath);
videoList.add(video);
} while (mCursor.moveToNext());
}
mCursor.close(); //cursor has been consumed so close it
return videoList;
}
public ArrayList<HashMap<String, String>> getPlayList() {
// TODO Auto-generated method stub
return null;
}
}
The list code along with an OnItemClick method and Intent:
Code:
public class VideoActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
ListView videolist;
Cursor mCursor;
int videoTitle;
int count;
int videoPath;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos);
ArrayList<HashMap<String, String>> videoListData = new ArrayList<HashMap<String, String>>();
VideoManager plm = new VideoManager();
// get all songs from sdcard
this.videoList = plm.getPlayList(this);
// looping through playlist
for (int i = 0; i < videoList.size(); i++) {
// creating new HashMap
HashMap<String, String> video = videoList.get(i);
// adding HashList to ArrayList
videoListData.add(video);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, videoListData,
R.layout.video_item, new String[] { "videoTitle" }, new int[] {
R.id.videoTitle });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int videoIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
VideoPlayerActivity.class);
Log.d("TAG","onItemClick");
// Sending songIndex to PlayerActivity
in.putExtra("videoPath", videoIndex);
startActivity(in);
// Closing PlayListView
finish();
}
});
}
}
And lastly, the players code:
Code:
public class VideoPlayerActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
private VideoManager videoManager;
private int currentvideoIndex = 0;
private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
videoManager = new VideoManager();
controller = new VideoControllerView(this);
videoList = videoManager.getPlayList(this);
}
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 0){
currentvideoIndex = data.getExtras().getInt("videoPath");
// play selected song
playVideo(currentvideoIndex);
}
}
public void playVideo(int videoIndex){
try {
player.setDataSource(videoList.get(videoIndex).get("videoPath"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
// Implement SurfaceHolder.Callback
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
player.prepareAsync();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
// End SurfaceHolder.Callback
// Implement MediaPlayer.OnPreparedListener
@Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
try {
player.prepare();
player.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return player.getCurrentPosition();
}
@Override
public int getDuration() {
return player.getDuration();
}
@Override
public boolean isPlaying() {
return player.isPlaying();
}
@Override
public void pause() {
player.pause();
}
@Override
public void seekTo(int i) {
player.seekTo(i);
}
@Override
public void start() {
player.start();
}
@Override
public boolean isFullScreen() {
return false;
}
@Override
public void toggleFullScreen() {
}
}
Right now PLEASE HELP ME!! :crying:
Why do you look up the videoPath in onActivityResult? Why do you need that Method? You'd add playVideo(getIntent().getBundle().getIntExtra("videopath")); to the end of your onCreate.
Regards
EmptinessFiller said:
Why do you look up the videoPath in onActivityResult? Why do you need that Method? You'd add playVideo(getIntent().getBundle().getIntExtra("videopath")); to the end of your onCreate.
Regards
Click to expand...
Click to collapse
Hi, thanks for the reply but unfortunately it didn't work.
I assume the code i entered is correct..
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
playVideo(getIntent().getExtras().getInt("videoPath"));
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
videoManager = new VideoManager();
controller = new VideoControllerView(this);
videoList = videoManager.getPlayList();
}
public void playVideo(int videoIndex){
try {
player.setDataSource(videoList.get(videoIndex).get("videoPath"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

[Q] GPS with Fragment

Good day. I start learn Fragment and I want use GPS in my Application. and I use Fragment. in fragment who view coordinate i writed next code
Code:
public class MyFragment2 extends Fragment {
public static final String BUTTON_INDEX = "button_index";
private static final int BUTTON_INDEX_DEFAULT = -1;
static TextView txt;
static TextView txt2;
String[] mCatDescription;
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
View viewHier = inflater.inflate(R.layout.fragment2, container, false);
txt = (TextView)viewHier.findViewById(R.id.textView1);
txt2 = (TextView)viewHier.findViewById(R.id.textView2);
mCatDescription =getResources().getStringArray(R.array.cats);
Bundle args = getArguments();
int buttonIndex = args != null ? args.getInt(BUTTON_INDEX, BUTTON_INDEX_DEFAULT):BUTTON_INDEX_DEFAULT;
if(buttonIndex != BUTTON_INDEX_DEFAULT){
setDiscription(buttonIndex);
}
return viewHier;
}
public void setDiscription(int buttonIndex){
GPSWork gpsWork = new GPSWork();
switch(buttonIndex){
case 1:
txt2.setText("one");
break;
case 2:
gpsWork.GetCoordinates();
break;
case 3:
txt2.setText("therd");
break;
}
}
}
Ok. when we click on button 2 we call method GetCoordinates(). this class have next code
Code:
public class GPSWork{
LocationManager locationManager;
public GPSWork(){
locationManager = (LocationManager)MainActivity.mContext.getSystemService(Context.LOCATION_SERVICE);
}
public void GetCoordinates(){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, locationListener);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onProviderDisabled(String provider) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onProviderEnabled(String provider) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
MyFragment2.txt2.setText("OK");
}
};
}
how we see, we should get text OK on TextView on MainActivity. but we don't have text, whats wrong? and if I change code in method GetCoordinates() on
Code:
public void GetCoordinates(){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000, 10, locationListener);
}
all work fine, i see text in TextView (OK )

Passing data between two fragments

Hello guys,
I have a list of fragments created and I want to delete these fragment by long pressing on them. However, before doing so I want dialog fragment to pop up and offer the user the choice to delete or not. I have created the two fragments but I can't get the data across each other. I can't give functionality to the 'OK' button. Here is my code:
Code:
public class CourseListFragment extends Fragment implements
OnItemClickListener, OnItemLongClickListener {
public static final String ARG_ITEM_ID = "course_list";
public static final String YES_NO = "modify";
Activity activity;
ListView courseListView;
ArrayList<Course> courses;
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
private GetEmpTask task;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
courseDAO = new CourseDAO(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.schedule_fragment_course_list,
container, false);
findViewsById(view);
task = new GetEmpTask(activity);
task.execute((Void) null);
courseListView.setOnItemClickListener(this);
courseListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
courseListView = (ListView) view.findViewById(R.id.list_course);
}
@Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Course course = (Course) list.getItemAtPosition(position);
if (course != null) {
Bundle arguments = new Bundle();
arguments.putParcelable("selectedCourse", course);
CustomCourseDialogFragment customEmpDialogFragment = new CustomCourseDialogFragment();
customEmpDialogFragment.setArguments(arguments);
customEmpDialogFragment.show(getFragmentManager(),
CustomCourseDialogFragment.ARG_ITEM_ID);
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// Show dialogFragment
FragmentManager fm = getActivity().getSupportFragmentManager();
CheckDialogFragment dialog = new CheckDialogFragment();
dialog.show(fm, YES_NO);
Course employee = (Course) parent.getItemAtPosition(position);
// Use AsyncTask to delete from database
courseDAO.deleteEmployee(employee);
courseListAdapter.remove(employee);
return true;
}
public class GetEmpTask extends AsyncTask<Void, Void, ArrayList<Course>> {
private final WeakReference<Activity> activityWeakRef;
public GetEmpTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected ArrayList<Course> doInBackground(Void... arg0) {
ArrayList<Course> courseList = courseDAO.getCourses();
return courseList;
}
@Override
protected void onPostExecute(ArrayList<Course> empList) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
courses = empList;
if (empList != null) {
if (empList.size() != 0) {
courseListAdapter = new CourseListAdapter(activity,
empList);
courseListView.setAdapter(courseListAdapter);
} else {
Toast.makeText(activity, "No Course Records",
Toast.LENGTH_LONG).show();
}
}
}
}
}
/*
* This method is invoked from MainActivity onFinishDialog() method. It is
* called from CustomEmpDialogFragment when an employee record is updated.
* This is used for communicating between fragments.
*/
public void updateView() {
task = new GetEmpTask(activity);
task.execute((Void) null);
}
@Override
public void onResume() {
getActivity().setTitle("Course Schedule");
getActivity().getActionBar().setTitle("Course Schedule");
super.onResume();
}
}
//Dialog Fragment
Code:
public class CheckDialogFragment extends DialogFragment {
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle("Do you want to delete?")
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
return builder.create();
}
}
I have problems trying to get the data from onItemLongClick() of CourseListFragment to CourseListFragment. Any help would be greatly appreciated.

[Q] Changing to another Activity when pressing on a Gridviewpager

I am trying to start a new certain Activity based on which page I am clicking on in a Gridview.
I tried to understand the Sample GridViewPager which is coming along with the sdk and trying to adapt the given explanation on stackoverflow (question # 26343337). But I really don't know how to bring these two things together and even where to start.
The first java.file Selection
Code:
public class Selection extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.selection_grid);
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setAdapter(new Workers(this, getFragmentManager()));
DotsPageIndicator dotsPageIndicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
dotsPageIndicator.setPager(pager);
}
}
and the second java.file Users (thats the Adapter):
Code:
public class Users extends FragmentGridPagerAdapter {
private static final int TRANSITION_DURATION_MILLIS = 100;
private final Context mContext;
private List<Row> mRows;
private ColorDrawable mDefaultBg;
private ColorDrawable mClearBg;
public Users (Context ctx, FragmentManager fm) {
super(fm);
mContext = ctx;
mRows = new ArrayList<Workers.Row>();
mRows.add(new Row(cardFragment(R.string.title, R.string.user1)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user2)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user3)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user4)));
// In case in one row several cardFragments are needed
// mRows.add(new Row(
// cardFragment(R.string.cards_title, R.string.cards_text),
// cardFragment(R.string.expansion_title, R.string.expansion_text)));
mDefaultBg = new ColorDrawable(R.color.dark_grey);
mClearBg = new ColorDrawable(android.R.color.transparent);
}
LruCache<Integer, Drawable> mRowBackgrounds = new LruCache<Integer, Drawable>(3) {
@Override
protected Drawable create(final Integer row) {
int resid = BG_IMAGES[row % BG_IMAGES.length];
new DrawableLoadingTask(mContext) {
@Override
protected void onPostExecute(Drawable result) {
TransitionDrawable background = new TransitionDrawable(new Drawable[] {
mDefaultBg,
result
});
mRowBackgrounds.put(row, background);
notifyRowBackgroundChanged(row);
background.startTransition(TRANSITION_DURATION_MILLIS);
}
}.execute(resid);
return mDefaultBg;
}
};
private Fragment cardFragment(int titleRes, int textRes) {
Resources res = mContext.getResources();
CardFragment fragment =
CardFragment.create(res.getText(titleRes), res.getText(textRes));
// Add some extra bottom margin to leave room for the page indicator
fragment.setCardMarginBottom(
res.getDimensionPixelSize(R.dimen.card_margin_bottom));
return fragment;
}
static final int[] BG_IMAGES = new int[] {
R.drawable.user1,
R.drawable.user2,
R.drawable.user3,
R.drawable.user4
};
/** A convenient container for a row of fragments. */
private class Row {
final List<Fragment> columns = new ArrayList<Fragment>();
public Row(Fragment... fragments) {
for (Fragment f : fragments) {
add(f);
}
}
public void add(Fragment f) {
columns.add(f);
}
Fragment getColumn(int i) {
return columns.get(i);
}
public int getColumnCount() {
return columns.size();
}
}
@Override
public Fragment getFragment(int row, int col) {
Row adapterRow = mRows.get(row);
return adapterRow.getColumn(col);
}
@Override
public Drawable getBackgroundForRow(final int row) {
return mRowBackgrounds.get(row);
}
@Override
public int getRowCount() {
return mRows.size();
}
@Override
public int getColumnCount(int rowNum) {
return mRows.get(rowNum).getColumnCount();
}
class DrawableLoadingTask extends AsyncTask<Integer, Void, Drawable> {
private static final String TAG = "Loader";
private Context context;
DrawableLoadingTask(Context context) {
this.context = context;
}
@Override
protected Drawable doInBackground(Integer... params) {
Log.d(TAG, "Loading asset 0x" + Integer.toHexString(params[0]));
return context.getResources().getDrawable(params[0]);
}
}
}

BLE Application (Display data from characteristic in a textView)

I used the BluetoothLeGatt example code to write an app that automatically connects to a bonded BLE peripheral upon launching the app. Now i am trying to display the data from one of the peripheral's characteristic in a textView. The BluetoothLeGatt example code only demonstrates this using ExpandableListView.OnChildClickListener, my app should require no user input and simply get he data from the characteristic. This is what i have so far:
Code:
private TextView mConnectionState;
private TextView mDataField;
private String mDeviceName;
private String mDeviceAddress;
private ExpandableListView mGattServicesList;
private BluetoothLeService mBluetoothLeService;
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);
mConnectionState.setTextColor(Color.parseColor("#FF17AA00"));
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)) {
*edit*
UUID chara = UUID.fromString("c97433f0-be8f-4dc8-b6f0-5343e6100eb4");
List<BluetoothGattService> servs = mBluetoothLeService.getSupportedGattServices();
for (int i = 0; servs.size() > i; i++) {
List<BluetoothGattCharacteristic> charac = servs.get(i).getCharacteristics();
for (int j = 0; charac.size() > i; i++) {
BluetoothGattCharacteristic ch = charac.get(i);
if (ch.getUuid() == chara) {
mBluetoothLeService.readCharacteristic(ch);
mBluetoothLeService.setCharacteristicNotification(ch, true);
}
}
}
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_control);
final Intent intent = getIntent();
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
mConnectionState = (TextView) findViewById(R.id.connection_state);
mDataField = (TextView) findViewById(R.id.data);
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
@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;
}
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);
}
}
private void clearUI() {
mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
mDataField.setText(R.string.no_data);
}
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;
}
I've successfully connected to an already bonded device, but now im trying to get the data from a characteristic using its uuid and display it in a textView. The BluetoothLeGatt example shows how a characteristic is selected by a user using an expandable list view onclick listener displaying the supported characteristics. I want to bypass all that and just get the data from the characteristic with the known uuid.
-EDIT-
figured it out

Categories

Resources