Hi, So I have managed to get similar code working in the main/ui thread but I was wondering if any of you may know why I cant get this running in my Service code?
I need the Code to run the onStart Segment at the set time...
Thanx In Advance!
Code:
public class Service1 extends Service {
public BroadcastReceiver alarmReceiver;
public PendingIntent pendingIntent;
public AlarmManager alarmManager;
public Handler serviceHandler;
@Override
public void onCreate()
{
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int H1 = Integer.parseInt(loadHour());
int M1 = Integer.parseInt(loadMin());
int D1 = Integer.parseInt(loadDay());
if (calendar.get(Calendar.HOUR_OF_DAY) > H1)
{
D1+=1;
}
calendar.set(Calendar.DAY_OF_YEAR, D1);
calendar.set(Calendar.HOUR_OF_DAY, H1);
calendar.set(Calendar.MINUTE, M1);
calendar.set(Calendar.SECOND, 00);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
};
public void onStart()
{
Intent intent = new Intent(ALARM_REFRESH_ACTION);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(Service1.this, "Success!", Toast.LENGTH_LONG).show();
}
};
Related
Hello,
I'm trying to write code of a widget sms for android. But I have a problem of cursor, after lot of test on compiling I dircoverd that
Code:
Cursor c = context.getContentResolver().query(Uri.parse("content://sms/"), null, null ,null,null);
make an error and I don't no why. If somebody knows how use a cursor or have a better idea to view sms without cursor, I woold like share it with him!
thank's
try something like this
Code:
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriSms, null,null,null,null);
Thank's to you Draffodx, I such begin my widget, now it can put on screen the sms I want... but I can't change of SMS with th button I've created. I don't understand how make a button with the widget because it need to be an Activity for a button and I've made an AppWidget...
I trying to do like this:
Code:
public class MySMSwidget extends AppWidgetProvider implements View.OnClickListener {
private Button Bnext;
private int sms_id=0;
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.widget_layout);
final Button button = (Button) findViewById(R.id.next);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (v==Bnext){sms_id=sms_id+1;}
}
});
}
}.... and the rest of the code
But when I click the button, nothing happend.
hey, my idea seems to be a bad idea so I try this way:
Code:
public class MySMSwidget extends AppWidgetProvider {
private int sms_id=0;
public void onReceive (Context context, Intent intent){
if (Intent.ACTION_ATTACH_DATA.equals(intent.getAction()))
{
Bundle extra = intent.getExtras();
sms_id = extra.getInt("Data");
}
}
public void onUpdate(Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds) {
Cursor c = context.getContentResolver().query(Uri.parse("content://
sms/inbox"), null, null ,null,null);
String body = null;
String number = null;
String date = null;
c.moveToPosition(sms_id);
body = c.getString(c.getColumnIndexOrThrow("body")).toString();
number =
c.getString(c.getColumnIndexOrThrow("address")).toString();
date = c.getString(c.getColumnIndexOrThrow("date")).toString();
c.close();
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
updateViews.setTextColor(R.id.text, 0xFF000000);
updateViews.setTextViewText(R.id.text,date+'\n'+number+'\n'+body);
ComponentName thisWidget = new ComponentName(context,
MySMSwidget.class);
appWidgetManager.updateAppWidget(thisWidget, updateViews);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_ATTACH_DATA);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.next, changeData(context));
}
private PendingIntent changeData(Context context) {
Intent Next = new Intent();
Next.putExtra("Data", sms_id+1);
Next.setAction(Intent.ACTION_ATTACH_DATA);
return(PendingIntent.getBroadcast(context,
0, Next, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
my code isn't terminated.
I hope there will be someone to help to correct it.
Just want to display next SMS.
Please help.
Can someone tell me how can i use something like a timer to start a video recording interval process for a period of time (eg: 5mins) then restarts to record another set of 5min video until the user intervene to stop the process..
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
public static boolean recordingStatus;
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
private MediaRecorder mediaRecorder;
private static int encodingStatus;
private static String videoResolution;
private static String fileFormat;
private static boolean audioStatus;
private static int timeInterval;
private static final String TAG = "Exception";
public boolean startRecording(){
try {
encodingStatus = Tab1Activity.encodingPref;
videoResolution = Tab1Activity.videoResPref;
fileFormat = Tab1Activity.fileFormatPref;
audioStatus = Tab2Activity.audioPref;
timeInterval = Tab2Activity.timeIntervalPref;
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
ServiceCamera.reconnect();
ServiceCamera.unlock();
}
catch(Exception e){
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(ServiceCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setMaxDuration(timeInterval);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(encodingStatus);
//mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(dirlist.exists()))
dirlist.mkdir();
File TempFile = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + fileFormat);
mediaRecorder.setOutputFile(TempFile.getPath());
String[] separatedRes = videoResolution.split("x");
separatedRes[0];
separatedRes[1];
mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
//mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.reset();
mediaRecorder.release();
recordingStatus = false;
}
}
someone please help...
Thread
you are writing a service, right? typically this service should also implement a thread. inside this thread you could implement your timer feature.
-didi
But the thing is i don't know how to even implement or even write the timer codes into my serviceRecording.java file... Can you help me on this?
i recently did this with a widget. i used an AlarmManager to set repeating alarms that would broadcast an intent that could be caught by a broadcastReciever and then do something... im at work now but when i get home i can try to give you some sample code.
you sure this needs to be a service? a service is something that is doing work but not at the forefront of the ui. its unseen. do you want your recording to be done in the background? i only ask because i did some research on services and found that they cannot be a BroadCastReciever and thus cannot use the AlarmManager that i said would work.
as far as a timer i have not looked into that particular class...
sorry i was no help. but if you decide to use the AlarmManager i could help
Someone recently recommended using these code to implement the sort of interval recording i wanted with this code below but i don't seems to know how to implement these codes into my current code could someone lend me a hand how how can can i implement the appropriate codes into my code to make my code work? Or is there simpler way to achieve "dynamic" (with Preferences) interval recording?
Code:
final ServiceRecording recording = ....
final AtomicBoolean started = new AtomicBoolean(false);
ScheduledExecutorService executor = Executors.newScheduledExecutor(1);
executor.scheduleAtFixedRate(new Runnable() { public void run() { //only stop if we have started if(started.get()) { recording.stop(); } else { started.set(true); } recording.start(); }}, 5, 5, TimeUnit.MINUTES);
My serviceRecording
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
public static boolean recordingStatus;
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
{
startRecording();
//new Timer().scheduleAtFixedRate(task, after, interval);
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
private MediaRecorder mediaRecorder;
private static int encodingType;
private static String videoResolution;
private static String fileFormat;
private static boolean audioStatus;
private static int timeInterval;
//timeInterval = Integer.parseInt(Tab2Activity.timeIntervalPref);
private static final String TAG = "Exception";
public boolean startRecording(){
try {
SharedPreferences prefs_tab1 = getSharedPreferences("tab1", Context.MODE_PRIVATE);
SharedPreferences prefs_tab2 = getSharedPreferences("tab2", Context.MODE_PRIVATE);
encodingType = Integer.parseInt(prefs_tab1.getString("EncodingPref", "1"));
//******************************************************************************
String stringRes = CameraTest.resParams;
String[] entriesValues = stringRes.split(",");
String rawResolution = entriesValues[0];
videoResolution = prefs_tab1.getString("ResolutionPref", rawResolution);
//******************************************************************************
fileFormat = prefs_tab1.getString("FileFormatPref", ".mp4");
//******************************************************************************
audioStatus = prefs_tab2.getBoolean("AudioPref", true); //false
//******************************************************************************
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
ServiceCamera.reconnect();
ServiceCamera.unlock();
}
catch(Exception e){
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(ServiceCamera);
if(!audioStatus)
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
}
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
if(!audioStatus)
{
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
}
mediaRecorder.setVideoEncoder(encodingType);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(dirlist.exists()))
dirlist.mkdir();
File TempFile = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + fileFormat);
mediaRecorder.setOutputFile(TempFile.getPath());
String[] separatedRes = videoResolution.split("x");
mediaRecorder.setVideoSize(Integer.parseInt(separatedRes[0]),Integer.parseInt(separatedRes[1]));
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.reset();
mediaRecorder.release();
recordingStatus = false;
}
Any progress on this? I was thinking you coukd have a private inner class in your service class that handles the timing with an AlarmManager
Im on my phone right now but something along these lines...
Private Class MyTimer extends BroadcastReciever {
//Implement onRecieve
Public void onRecieve(Context c, Intent i) {
//if intent matches 5min alarm
//start recording
}
Then in your service you can make a recurring alarm using the AlarmManager class to signal your inner class to start or even stop the recording based on what intent you pass it
When i get home ill right a bit more code as an example
From something awesome
i wrote a bit of code. its incomplete. and you will have to maybe mess with making the AlarmServicer class either static, public, private or something to make it work. basicly your service creates a five minute alarm directed at the AlarmServicer that it catches in the onRecieve() method and then starts your recording again and then creates another alarm directed at itself. you can use some if/then logic to change wether or not the alarm will be created again based on if the user wants it to stop or not. and then to get it going again the service would invoke the setOneTimeAlarm method again.
Code:
public class ServiceRecording extends Service {
// NEW CONSTANT
public static final String FIVE_MIN_ALARM = "FIVE_MIN_ALARM";
public static final int FIVE_MINUTES = 300;
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
//set the first alarm
AlarmServicer.setOneTimeAlarm(AlarmServicer.class, this, ServiceRecording.FIVE_MINUTES , ServiceRecording.FIVE_MIN_ALARM);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { }
public boolean startRecording() {}
public void stopRecording() {}
// NEW CODE
private static class AlarmServicer extends BroadcastReciever {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(ServiceRecording.FIVE_MIN_ALARM)) {
ServiceRecording.startRecording();
//set another five min alarm
setOneTimeAlarm(AlarmServicer.class, this, ServiceRecording.FIVE_MINUTES, ServiceRecording.FIVE_MIN_ALARM;
}
}
private static void setOneTimeAlarm(java.lang.Class<?> cls, Context context, int seconds, String action) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, cls);
intent.setAction(action);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (seconds * 1000), pendingIntent);
}
}
}
and i believe that you need to register the inner class as a broadcastreciever in the android manifest.
**
** this most likely wont work....
**
Hello guys. I'm making an app, its a kind of alarm scheduler but I have a problem with the code. Thats what im using
Code:
ScheduledThreadPoolExecutor scheduler=new ScheduledThreadPoolExecutor(1);
scheduler.schedule(new Runnable() {
public void run(){
alarm(1);
} }, delay , TimeUnit.SECONDS);
It works for low values of "delay" if I put a high value (11000 for example) and leave the device alone, I think it enters in sleep mode and dont execute the timer.
How can I solve that?
Thanks in advance
I dont know about the scheduler but an alarm manager can wake the phone from sleep if you want. Or run the alarm in the background while asleep
From something awesome
Thanks for your answer, worked for me.
Here's the code, it maybe help others
MainUI.java:
Code:
public class MainUI extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView boton =(TextView)findViewById(R.id.botonAplicar);
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainUI.this, WakeUpReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainUI.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
int delay=1;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, delay);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Log.i("Test","Programmed");
}
});
}
}
WakeUpReceiver.java:
Code:
public class WakeUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Test","Wake Up Received");
}
}
Manifest:
Code:
<receiver android:process=":remote" android:name="WakeUpReceiver"></receiver>
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 )
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