how to solve android service has leaked error - java

I have an activity that calls a service on its onCreate , however when I try yo run the project I keep getting an error saying the service has leaked and longer bound on the activity that called/registered it .
"Activity com.xera.deviceinsight.home.DataUsageActivity has leaked ServiceConnection com.xera.deviceinsight.home.DataUsageActivity$3#42676a48 that was originally bound here" I am assuming this might have something to do with the lifecycle of the activity . I have both the activity and the service in question below
myActivity
public class DataUsageActivity extends AppCompatActivity implements MonitorService.ServiceCallback
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TinyDB settings = new TinyDB(this);
if (settings.getBoolean(AppPreferences.HAS_LOGGED_IN))
{
this.bindService(
new Intent(this, MonitorService.class),
serviceConnection,
Context.BIND_AUTO_CREATE);
return;
}
}
public void sendResults(int resultCode, Bundle b)
{
// adapter.notifyDataSetChanged();
}
private ServiceConnection serviceConnection = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName className, IBinder service)
{
MonitorService.LocalBinder binder = (MonitorService.LocalBinder)service;
backgroundService = binder.getService();
backgroundService.setCallback(DataUsageActivity.this);
backgroundService.start();
}
#Override
public void onServiceDisconnected(ComponentName className)
{
backgroundService = null;
}
};
#Override
public void onResume()
{
super.onResume();
if(backgroundService != null)
{
backgroundService.setCallback(this);
}
}
#Override
public void onPause()
{
super.onPause();
if(backgroundService != null)
{
backgroundService.setCallback(null);
}
}
}
**myService**
public class MonitorService extends Service
{
private boolean initialized = false;
private final IBinder mBinder = new LocalBinder();
private ServiceCallback callback = null;
private Timer timer = null;
private final Handler mHandler = new Handler();
private String foreground = null;
private ArrayList<HashMap<String,Object>> processList;
private ArrayList<String> packages;
private Date split = null;
// private Date startTime = null;
public int timeCheckVariable = 0 ;
public static int SERVICE_PERIOD = 5000; // TODO: customize (this is for scan every 5 seconds)
private final ProcessList pl = new ProcessList(this)
{
#Override
protected boolean isFilteredByName(String pack)
{
// TODO: filter processes by names, return true to skip the process
// always return false (by default) to monitor all processes
return false;
}
};
public interface ServiceCallback
{
void sendResults(int resultCode, Bundle b);
}
public class LocalBinder extends Binder
{
MonitorService getService()
{
// Return this instance of the service so clients can call public methods
return MonitorService.this;
}
}
#Override
public void onCreate()
{
super.onCreate();
initialized = true;
processList = ((DeviceInsightApp)getApplication()).getProcessList();
packages = ((DeviceInsightApp)getApplication()).getPackages();
}
#Override
public IBinder onBind(Intent intent)
{
if(initialized)
{
return mBinder;
}
return null;
}
public void setCallback(ServiceCallback callback)
{
this.callback = callback;
}
// private boolean addToStatistics(String target , Long startTime)
private boolean addToStatistics(String target )
{
boolean changed = false;
Date now = new Date();
if(!TextUtils.isEmpty(target))
{
if(!target.equals(foreground))
{
int i;
// timeCheckVariable = i ;
if(foreground != null && split != null)
{
// TODO: calculate time difference from current moment
// to the moment when previous foreground process was activated
i = packages.indexOf(foreground);
timeCheckVariable = i ;
long delta = (now.getTime() - split.getTime()) / 1000;
Long time = (Long)processList.get(i).get(ProcessList.COLUMN_PROCESS_TIME);
if(time != null)
{
// TODO: add the delta to statistics of 'foreground'
time += delta;
}
else
{
time = new Long(delta);
}
processList.get(i).put(ProcessList.COLUMN_PROCESS_TIME, time);
//String applicationName = (String)processList.get(i).get(ProcessList.COLUMN_PROCESS_NAME);
// DatabaseHandler db = new DatabaseHandler(this);
// int x = time.intValue( );
// db.addAppRecord(new AppUsageClass(applicationName , x));
// db.getApplicationCount();
// List<AppUsageClass> appUsageClass = db.getAllApplications();
// db.getApplicationCount();
// for (AppUsageClass cn : appUsageClass) {
//String log = "Id: " + cn.getID() + " ,ApplicationName : " + cn.getName() + " ,TimeSpent: " + cn.getTimeSpent();
// Log.d("Name: ", log);
//}
}
//update count of process activation for new 'target'
i = packages.indexOf(target);
Integer count = (Integer)processList.get(i).get(ProcessList.COLUMN_PROCESS_COUNT);
if(count != null) count++;
else
{
count = new Integer(1);
}
processList.get(i).put(ProcessList.COLUMN_PROCESS_COUNT, count);
foreground = target;
split = now;
changed = true;
}
}
//Long checkTimeNow = (Long)processList.get(timeCheckVariable).get(ProcessList.COLUMN_PROCESS_TIME);
return changed;
}
public void start()
{
if(timer == null)
{
timer = new Timer();
timer.schedule(new MonitoringTimerTask(), 500, SERVICE_PERIOD);
}
// TODO: startForeground(srvcid, createNotification(null));
}
public void stop()
{
timer.cancel();
timer.purge();
timer = null;
}
private class MonitoringTimerTask extends TimerTask
{
#Override
public void run()
{
fillProcessList();
ActivityManager activityManager = (ActivityManager)MonitorService.this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
String current = taskInfo.get(0).topActivity.getPackageName(); // gets the application which is in the foreground
int i = packages.indexOf(current);
Long timecheck = (Long)processList.get(i).get(ProcessList.COLUMN_PROCESS_TIME);
if(addToStatistics(current)&& callback != null)
{
final Bundle b = new Bundle();
// TODO: pass necessary info to UI via bundle
mHandler.post(new Runnable()
{
public void run()
{
callback.sendResults(1, b);
}
});
}
}
}
private void fillProcessList()
{
pl.fillProcessList(processList, packages);
}

The problem is that you don't unbind from you service in .onPause() or in .onDestroy(), so if you Activity is destroyed, connection still last, so there is leaked connection. If you want you service to run all the time, you should start it by .startService() and then bind to it. In .onStop() or .onDestroy() unbind from that service

Related

Why does my Java code for Android App Generate 2 threads?

I am new to Java coding for android. I need to understand why does my code generate 2 threads. The problem that can be created over here is perhaps competition for Camera Resources which results in the camera not being used by the user. Kindly suggest a solution to my problem as well.
I have also attached a picture where there are 2 requests for a new activity. There is also proof by having 2 thread IDs active.
EDIT for clarity:
I want to generate a new thread which solely handles the activity to record the video, no other thread should be doing it. But there are two that are performing their own activity to record video.
public class MainActivity extends AppCompatActivity implements SensorEventListener/*, ActivityCompat.OnRequestPermissionsResultCallback*/ {
private Camera c;
private MainActivity reference_this = this;
private BooleanObject recorded_video = new BooleanObject("recorded_video",false);
private BooleanObject recorded_motions_chest = new BooleanObject("recorded_motions_chest", false);
private ChangeListener listener_change;
public void setListener(ChangeListener arg_listener_change) {
listener_change = arg_listener_change;
}
public interface ChangeListener {
void onChange(String arg_name);
}
public void set_recorded_video(boolean arg_recorded_video) {
recorded_video.set_value(arg_recorded_video);
if (listener_change != null) { listener_change.onChange(recorded_video.get_name()); }
}
public void set_recorded_motions_chest(boolean arg_recorded_motions_chest) {
recorded_motions_chest.set_value(arg_recorded_motions_chest);
if (listener_change != null) { listener_change.onChange(recorded_motions_chest.get_name()); }
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))) {
this.finish();
System.exit(0);
}
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
this.setListener(new MainActivity.ChangeListener() {
#Override
public void onChange(String arg_name) {
Log.i("CHNG", "fired");
if (arg_name.equals(recorded_video.get_name())) {
VideoCapture video_capture = new VideoCapture();
video_capture.open(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video_finger.mp4");
Mat frame = new Mat();
int length_video = (int) video_capture.get(Videoio.CAP_PROP_FRAME_COUNT);
int rate_frame = (int) video_capture.get(Videoio.CAP_PROP_FPS);
while (true) {
video_capture.read(frame);
Size size_img = frame.size();
Log.i("MAT", String.valueOf(size_img.width) + ' ' + String.valueOf(size_img.height));
}
}
else if (arg_name.equals(recorded_motions_chest.get_name())) {}
}
});
// new Thread(new Runnable() {
// public void run() {
Button button_symptoms = (Button) findViewById(R.id.button_symptoms);
Button button_upload_signs = (Button) findViewById(R.id.button_upload_signs);
Button button_measure_heart_rate = (Button) findViewById(R.id.button_measure_heart_rate);
Button button_measure_respiratory_rate = (Button) findViewById(R.id.button_measure_respiratory_rate);
CameraView cv1 = new CameraView(getApplicationContext(), reference_this);
FrameLayout view_camera = (FrameLayout) findViewById(R.id.view_camera);
view_camera.addView(cv1);
TextView finger_on_sensor = (TextView) findViewById(R.id.text_finger_on_sensor);
finger_on_sensor.setVisibility(View.INVISIBLE);
finger_on_sensor.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch (View arg_view, MotionEvent arg_me){
finger_on_sensor.setVisibility(View.INVISIBLE);
/*GENERATING THREADS OVER HERE*/ new Thread(new Runnable() {
public void run() {
File file_video = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video_finger.mp4");
// final int REQUEST_WRITE_PERMISSION = 786;
final int VIDEO_CAPTURE = 1;
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent_record_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent_record_video.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 45);
Uri fileUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cse535a1.provider", file_video);
intent_record_video.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
if (intent_record_video.resolveActivity(getPackageManager()) != null) {
Log.i("CAM", "CAM requeted");
Log.i("Thread ID", String.valueOf(Thread.currentThread().getId()));
startActivityForResult(intent_record_video, VIDEO_CAPTURE);
// reference_this.set_recorded_video(true);
}
}
}).start();
return true;
}
});
button_symptoms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View arg_view){
Intent intent = new Intent(getApplicationContext(), Loggin_symptoms.class);
startActivity(intent);
}
});
button_upload_signs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View arg_view){
}
});
button_measure_heart_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View arg_view){ finger_on_sensor.setVisibility(View.VISIBLE); }
});
button_measure_respiratory_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
SensorManager manager_sensor = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor_accelerometer = manager_sensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
manager_sensor.registerListener(MainActivity.this, sensor_accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
});
// }}).start();
}
public void setCam(Camera arg_camera) { c = arg_camera; }
#Override
public void onSensorChanged(SensorEvent arg_event) {
float x = arg_event.values[0];
float y = arg_event.values[1];
float z = arg_event.values[2];
Log.i("ACCELEROMETER", String.valueOf(x) + ' ' + String.valueOf(y) + ' ' + String.valueOf(z));
}
#Override
public void onAccuracyChanged(Sensor arg_sensor, int arg_accuracy) {
}
#Override
protected void onPause() {
super.onPause();
c.unlock();
// Log.i("CAM", "unlocked");
// if (c != null) {
// c.stopPreview();
//// c.release();
//// c = null;
// }
}
#Override
protected void onResume() {
super.onResume();
if (c != null) c.lock();
// if (c != null) {
// c.stopPreview();
// c.release();
// c = null;
/// }
// cv1 = new CameraView(getApplicationContext(), this);
// view_camera.addView(cv1);
}
#Override
protected void onDestroy() {
if (c != null) {
// c.unlock();
c.stopPreview();
c.release();
c = null;
}
super.onDestroy();
}
private static class BooleanObject {
private String name = "BooleanObject";
private boolean value = false;
public BooleanObject(String arg_name, boolean arg_value) {
name = arg_name;
value = arg_value;
}
public String set_name(String arg_name) {
name = arg_name;
return name;
}
public boolean set_value(boolean arg_value) {
value = arg_value;
return value;
}
public String get_name() { return name; }
public boolean get_value() { return value; }
};
}
Every time you tap on TextView, as you are using onTouchListener, it will be fired twice, once for ACTION_DOWN and ACTION_UP, so check for ACTION_UP as in
finger_on_sensor.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch (View arg_view, MotionEvent arg_me){
if(arg_me.getAction() == MotionEvent.ACTION_UP){ //add this condition
finger_on_sensor.setVisibility(View.INVISIBLE);
new Thread(new Runnable() {
public void run() {
File file_video = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video_finger.mp4");
// final int REQUEST_WRITE_PERMISSION = 786;
final int VIDEO_CAPTURE = 1;
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent_record_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent_record_video.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 45);
Uri fileUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cse535a1.provider", file_video);
intent_record_video.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
if (intent_record_video.resolveActivity(getPackageManager()) != null) {
Log.i("CAM", "CAM requeted");
Log.i("Thread ID", String.valueOf(Thread.currentThread().getId()));
startActivityForResult(intent_record_video, VIDEO_CAPTURE);
//reference_this.set_recorded_video(true);
}
}
}).start();
return true;
}
});

android studio java web service control every 45 seconds

I have to do an android service that communicates with a web service within 45 seconds. but i can't do it with business service or normal service. The system automatically shuts itself down after 10 minutes. I need help.
public class bildirim extends JobService {
int Kul_Id = 0;
String[] sto;
int sayac = 0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public boolean onStartJob(JobParameters params) {
final ipdatabase dbo = new ipdatabase(getBaseContext());
sto = dbo.ipler(getBaseContext());
database db = new database(bildirim.this);
if (db.dbkontrol()) {
List<String> cr = db.veriListele(2);
if (!cr.isEmpty()) {
Kul_Id = Integer.parseInt(cr.get(4));
}
}
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
new arkaplan().execute("http://" + sto[0] + "/Services.asmx/bildirimal?Kul_ID=" + Kul_Id+"&durum=1");
}
},0,30000);
return false;
}
#Override
public boolean onStopJob(JobParameters params) {
return false;
}
#Override
public void onDestroy() {
JobSchedulerService.scheduleJob(getApplicationContext());
super.onDestroy();
}
class arkaplan extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
return jsonparser.getdata(params[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject obj = new JSONObject(s);
JSONArray listarray = obj.getJSONArray("list");
JSONObject fistobj;
for (int i = 0; i < listarray.length(); i++) {
fistobj = listarray.getJSONObject(i);
int icon = R.drawable.redwhitefav;
NotificationManagerCompat notifiynm = NotificationManagerCompat.from(bildirim.this);
Notification notifiy = new NotificationCompat.Builder(bildirim.this, CHANNEL_1_ID)
.setSmallIcon(icon)
.setContentTitle(fistobj.getString("Gork_Deger") + ": " + fistobj.getString("Gork_Mstad"))
.setContentText("Tanım: "+ fistobj.getString("Gork_Tanim") + "\n"+ "Tarih: " + fistobj.getString("Gork_Baslangic"))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.build();
notifiynm.notify(sayac, notifiy);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

Android Studio Ble Gatt connection writing data to a custom service characteristic

I am trying to write some custom data to a BLE device with a custom service on it. I have followed this tutorial: https://www.youtube.com/watch?v=vUbFB1Qypg8&feature=emb_logo which is from android.
I can see my custom service with data on it. Also via another application (NRF connect) I can write data to this custom service. Therefore, I know its possible to write data to the service.
The issue I have is other examples of how to write data to the custom service use BluetoothGatt whereas, this code seems to use BluetoothLeService instead. This is an issue as the documentation does not seem to have a read API for the BluetoothLeService. So I can not use something like mBluetoothGatt.readCharacteristic(mReadCharacteristic);
How can I go about creating a function to write a value (integer) to the characterisitic.
My UUID for the service is: "f3641400-00b0-4240-ba50-05ca45bf8abc"
My UUID for the characteristic is: "f3641401-00b0-4240-ba50-05ca45bf8abc"
For reference my code is below:
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 EditText Command_string;
private BluetoothGatt mGatt;
private Button btn_gatt_connect;
private Button btn_live,btn_command;
private String mDeviceName;
private String mDeviceAddress;
private String User_data;
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";
private String Switch_case ="Connect";
private boolean Write_ble_command = true;
// 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 Gatt_Connect()
{
switch(Switch_case) {
case "Connect":
btn_gatt_connect.setText("Disconnect");//Presently connected allow to disconnect
mBluetoothLeService.connect(mDeviceAddress);
Switch_case = "Disconnect";
break;
case "Disconnect":
btn_gatt_connect.setText("Connect");//Presently disconnected allow to connect
mBluetoothLeService.disconnect();
Switch_case = "Connect";
break;
}
}
private void Live_data(){
//Ensure you are disconnected
btn_gatt_connect.setText("Connect");//Presently disconnected allow to connect
mBluetoothLeService.disconnect();//Might only run if connected
Switch_case = "Connect";
Intent myIntent = new Intent(DeviceControlActivity.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("User_data", User_data);//Pass through the user's email address to the main activity for display
myIntent.putExtras(bundle);
DeviceControlActivity.this.startActivity(myIntent);//Run the main activity}
}
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);
//Get the extras passed in
Bundle bundle = getIntent().getExtras();
mDeviceName = bundle.getString("Device_Name");
mDeviceAddress = bundle.getString("Device_Address");
User_data = bundle.getString("User_data");
// Sets up UI references.
((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
Command_string = (EditText)findViewById(R.id.Command_string);
btn_gatt_connect = (Button)findViewById(R.id.btn_gatt_connect);
btn_live = (Button) findViewById(R.id.btn_live);
btn_command = (Button) findViewById(R.id.btn_command);
btn_gatt_connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Gatt_Connect();
}
});
btn_gatt_connect.setText("Disconnect");//Presently disconnected allow to connect
btn_live.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Live_data();
}
});
btn_command.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Send_Command();//Sends the command in the text box to the nordic board
}
});
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);
//setTitle(mDeviceAddress);//Change the title to Scanner as the device is no longer being read
Intent gattServiceIntent = new Intent(DeviceControlActivity.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;
}
protected void Send_Command()
{
Write_ble_command = true;//Write command issued on display gatt service
}
#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;
}
}
I fixed my issue by creating a function inside of the Bluetoothle service. This is where the bluetooth gatt connection is. The function is like so.
public void writeCharacteristic(int Data) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
byte[] value = intToByteArray(Data);
BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("f3641400-00b0-4240-ba50-05ca45bf8abc"));
if(mCustomService == null){
Log.w(TAG, "Custom BLE Service not found");
return;
}
/*get the read characteristic from the service*/
BluetoothGattCharacteristic characteristic = mCustomService.getCharacteristic(UUID.fromString("f3641401-00b0-4240-ba50-05ca45bf8abc"));
characteristic.setValue(value);
mBluetoothGatt.writeCharacteristic(characteristic);
}
It just needs a data (Int value passing into it). Then this is received by my Bluetooth board and, can see its data on a terminal being sent correctly.

Android MIDI Threading InteruptedException - Aftertouch Messages

Trying to run MIDI on my Android app. I'm following the midisuite example to configure my app and it works fine with the exception of aftertouch. Whenever I try to trigger aftertouch, I run into a threading exception type
InteruptedException. How should I prevent this threading issue? My knowledge on multithreading isn't the best or else I would've figured this out already. All I can really tell right now is that the message is sending too fast and the thread hasn't woken up yet from its sleep call.
I followed the github repo with my code as follows:
MidiReceiver subclass:
#TargetApi(Build.VERSION_CODES.M)
public class MidiEngine extends MidiReceiver {
public AudioActivity activity;
private MidiEventScheduler eventScheduler;
private MidiFramer midiFramer;
private MidiReceiver midiReceiver = new MyReceiver();
private Thread mThread;
private boolean go;
private int mProgram;
public MidiEngine() {
this(new AudioActivity());
}
public MidiEngine(AudioActivity activity) {
this.activity = activity;
midiReceiver = new MyReceiver();
midiFramer = new MidiFramer(midiReceiver);
}
public AudioActivity getActivity() {
return this.activity;
}
/* This will be called when MIDI data arrives. */
#Override
public void onSend(byte[] data, int offset, int count, long timestamp)
throws IOException {
if (eventScheduler != null) {
if (!MidiConstants.isAllActiveSensing(data, offset, count)) {
eventScheduler.getReceiver().send(data, offset, count,
timestamp);
}
}
}
// Custom Listener to send to correct methods
private class MyReceiver extends MidiReceiver {
#Override
public void onSend(byte[] msg, int offset, int count, long timestamp) throws IOException {
byte command = (byte)(msg[0] & MidiConstants.STATUS_COMMAND_MASK);
int channel = (byte)(msg[0] & MidiConstants.STATUS_CHANNEL_MASK);
switch (command) {
case MidiConstants.STATUS_NOTE_ON:
activity.keyDown(i, msg[1], msg[2]);
break;
case MidiConstants.STATUS_NOTE_OFF:
activity.keyUp(channel, msg[1]);
break;
case MidiConstants.STATUS_POLYPHONIC_AFTERTOUCH:
activity.keyDown(channel, msg[1], msg[2]);
break;
case MidiConstants.STATUS_PITCH_BEND:
activity.pitchBendAction(channel, (msg[2] << 7) + msg[1]);
break;
case MidiConstants.STATUS_CONTROL_CHANGE:
activity.ccAction(channel, msg[1], msg[2]);
break;
case MidiConstants.STATUS_PROGRAM_CHANGE:
mProgram = msg[1];
break;
default:
break;
}
}
}
class MyRunnable implements Runnable {
#Override
public void run() {
do {
try {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
processMidiEvents();
}
catch (Exception e) {
Log.e("Java", "SynthEngine background thread exception.", e);
}
}
});
Thread.sleep(100);
}
catch (InterruptedException e) {
Log.e("Java", "Threading exception", e);
}
}
while (go);
}
}
/**
* #throws IOException
*
*/
private void processMidiEvents() throws IOException {
long now = System.nanoTime();
MidiEventScheduler.MidiEvent event = (MidiEventScheduler.MidiEvent) eventScheduler.getNextEvent(now);
while (event != null) {
midiFramer.send(event.data, 0, event.count, event.getTimestamp());
eventScheduler.addEventToPool(event);
event = (MidiEventScheduler.MidiEvent) eventScheduler.getNextEvent(now);
}
}
public void start() {
stop();
go = true;
mThread = new Thread(new MyRunnable());
mThread.setPriority(6);
eventScheduler = new MidiEventScheduler();
mThread.start();
}
public void stop() {
go = false;
if (mThread != null) {
try {
mThread.interrupt();
mThread.join(500);
}
catch (Exception e) {
}
mThread = null;
eventScheduler = null;
}
}
}
Stack Trace Error (line 154 refers to the Thread.sleep part in my custom Runnable class):
Java: Threading exception
java.lang.InterruptedException
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:1031)
at java.lang.Thread.sleep(Thread.java:985)
at com.rfoo.midiapp.communication.MidiEngineInput$MyRunnable.run(MidiEngineInput.java:154)
at java.lang.Thread.run(Thread.java:818)
Thanks!
EDIT: Thread start
Midi Device Service subclass (thread will start whenever a device has connected or disconnected).
#TargetApi(Build.VERSION_CODES.M)
public class MidiSynthDeviceService extends MidiDeviceService {
private static final String TAG = "MidiSynthDeviceService";
private boolean midiStarted = false;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
AudioActivity.midiEngine.stop();
super.onDestroy();
}
#Override
// Declare the receivers associated with your input ports.
public MidiReceiver[] onGetInputPortReceivers() {
return new MidiReceiver[] { AudioActivity.midiEngine };
}
/**
* This will get called when clients connect or disconnect.
* You can use it to turn on your synth only when needed.
*/
#Override
public void onDeviceStatusChanged(MidiDeviceStatus status) {
if (status.isInputPortOpen(0) && !midiStarted) {
AudioActivity.midiEngine.start();
midiStarted = true;
} else if (!status.isInputPortOpen(0) && midiStarted){
AudioActivity.midiEngine.stop();
midiStarted = false;
}
}
}
Activity class:
public class AudioActivity extends AppCompatActivity {
private Thread thread;
public static MidiEngine midiEngine;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Layout inits
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Setup MIDI:
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_MIDI)) {
Toast.makeText(this, "MIDI not supported!", Toast.LENGTH_LONG).show();
}
else {
midiEngine = new MidiEngine(this);
setupMidi();
}
// Setup audio thread:
if (thread == null) {
thread = new Thread() {
public void run() {
setPriority(Thread.MAX_PRIORITY);
// Runs an Open SL audio thread (C++)
// This generates a waveform.
// AudioEngine is a wrapper class connecting C++ to Java
AudioEngine.runProcess();
}
}
}
}
public void setupMidi() {
if (activity == null) activity = (AudioActivity) getContext();
mMidiManager = (MidiManager) activity.getSystemService(AudioActivity.MIDI_SERVICE);
if (mMidiManager == null) {
Toast.makeText(activity, "MidiManager is null!", Toast.LENGTH_LONG).show();
return;
}
// Get Device Info
MidiDeviceInfo deviceInfo = MidiTools.findDevice(mMidiManager, "RFOO", "AudioApp");
// MIDI Input
portIndex = 0;
inputPortSelector = new MidiOutputPortConnectionSelector(mMidiManager, activity, R.id
.inputListView, deviceInfo, portIndex);
inputPortSelector.setConnectedListener(new MyPortsConnectedListener());
midi_ch_input = 0;
midi_ch_output = 0;
}
// Bunch of UI code here....
}

Finding location in android using Gabe Sechan's tutorial

I have tried using androidhive's standard tutorial for finding location,but it fails at certain times.So i found another tutorial on this link:
http://gabesechansoftware.com/location-tracking/
He uses two classes which implement an interface:
The first class:
package com.example.marinamapseg;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
public class FallbackLocationTracker implements LocationTracker, LocationTracker.LocationUpdateListener {
private boolean isRunning;
private ProviderLocationTracker gps;
private ProviderLocationTracker net;
private LocationUpdateListener listener;
Location lastLoc;
long lastTime;
public FallbackLocationTracker(Context context) {
gps = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.GPS);
net = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.NETWORK);
}
public void start(){
if(isRunning){
//Already running, do nothing
return;
}
//Start both
gps.start(this);
net.start(this);
isRunning = true;
}
public void start(LocationUpdateListener update) {
start();
listener = update;
}
public void stop(){
if(isRunning){
gps.stop();
net.stop();
isRunning = false;
listener = null;
}
}
public boolean hasLocation(){
//If either has a location, use it
return gps.hasLocation() || net.hasLocation();
}
public boolean hasPossiblyStaleLocation(){
//If either has a location, use it
return gps.hasPossiblyStaleLocation() || net.hasPossiblyStaleLocation();
}
public Location getLocation(){
Location ret = gps.getLocation();
if(ret == null){
ret = net.getLocation();
}
return ret;
}
public Location getPossiblyStaleLocation(){
Location ret = gps.getPossiblyStaleLocation();
if(ret == null){
ret = net.getPossiblyStaleLocation();
}
return ret;
}
public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime) {
boolean update = false;
//We should update only if there is no last location, the provider is the same, or the provider is more accurate, or the old location is stale
if(lastLoc == null){
update = true;
}
else if(lastLoc != null && lastLoc.getProvider().equals(newLoc.getProvider())){
update = true;
}
else if(newLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){
update = true;
}
else if (newTime - lastTime > 5 * 60 * 1000){
update = true;
}
if(update){
lastLoc = newLoc;
lastTime = newTime;
if(listener != null){
listener.onUpdate(lastLoc, lastTime, newLoc, newTime);
}
}
}
}
The second class:
package com.example.marinamapseg;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class ProviderLocationTracker implements LocationListener, LocationTracker {
// The minimum distance to change Updates in meters
private static final long MIN_UPDATE_DISTANCE = 0;
// The minimum time between updates in milliseconds
private static final long MIN_UPDATE_TIME = 0;
private LocationManager lm;
public enum ProviderType{
NETWORK,
GPS
};
private String provider;
private Location lastLocation;
private long lastTime;
private boolean isRunning;
private LocationUpdateListener listener;
public ProviderLocationTracker(Context context, ProviderType type) {
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if(type == ProviderType.NETWORK){
provider = LocationManager.NETWORK_PROVIDER;
}
else{
provider = LocationManager.GPS_PROVIDER;
}
}
public void start(){
if(isRunning){
//Already running, do nothing
return;
}
//The provider is on, so start getting updates. Update current location
isRunning = true;
lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);
lastLocation = null;
lastTime = 0;
return;
}
public void start(LocationUpdateListener update) {
start();
listener = update;
}
public void stop(){
if(isRunning){
lm.removeUpdates(this);
isRunning = false;
listener = null;
}
}
public boolean hasLocation(){
if(lastLocation == null){
return false;
}
if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
return false; //stale
}
return true;
}
public boolean hasPossiblyStaleLocation(){
if(lastLocation != null){
return true;
}
return lm.getLastKnownLocation(provider)!= null;
}
public Location getLocation(){
if(lastLocation == null){
return null;
}
if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
return null; //stale
}
return lastLocation;
}
public Location getPossiblyStaleLocation(){
if(lastLocation != null){
return lastLocation;
}
return lm.getLastKnownLocation(provider);
}
public void onLocationChanged(Location newLoc) {
long now = System.currentTimeMillis();
if(listener != null){
listener.onUpdate(lastLocation, lastTime, newLoc, now);
}
lastLocation = newLoc;
lastTime = now;
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
But the issue is that he has not mentioned as how to use the following two classes in the android app.So i tried the following:
FallbackLocationTracker fobj;
fobj=new FallbackLocationTracker(MainActivity.this);
fobj.start();
if(fobj.hasLocation())
{
Location locobj=fobj.getLocation();
current_latitude=locobj.getLatitude();
current_longitude=locobj.getLongitude();
Toast.makeText(getApplicationContext(),current_latitude+" "+current_longitude,Toast.LENGTH_LONG).show();
placemarkersonmap();
}
When i debug the code the hasLocation method returns false, Because the onLocationChanged method in the first class is getting called only after the haslocation method is called.So the lastlocation object will be null and false would be returned.
But why doesnt onlocationchanged get called as soon as the following line runs:
lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);
Or is there any way somenone can tell me as how to use the code.Please help!!
onLocationChanged is a callback, meaning that it is event driven and does not run until the device detects a change of location. If you are taking location only from GPS, then it can take several minutes before you get a fix. If you are indoors without a clear view of the sky, then it may never run.
You may add the following in your actitvity's onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewHeading = (TextView) this.findViewById(R.id.text_heading);
textViewLong = (TextView) this.findViewById(R.id.text_long);
textViewLat = (TextView) this.findViewById(R.id.text_lat);
textViewHeight = (TextView) this.findViewById(R.id.text_height);
textViewAccuracy = (TextView) this.findViewById(R.id.text_accuracy);
counter = (long) 0;
gps = new ProviderLocationTracker(this,
ProviderLocationTracker.ProviderType.GPS);
listener = new LocationUpdateListener() {
#Override
public void onUpdate(Location oldLoc, long oldTime, Location newLoc,
long newTime) {
// TODO Auto-generated method stub
counter = counter + (long) 1;
if (gps.hasLocation()) {
text1="GPS has location ( " + counter.toString() + " )";
} else {
text1="GPS has no location ( " + counter.toString() + " )";
}
if (gps.hasPossiblyStaleLocation()) {
text1 = text1 + " plus stale location";
}
Double longitude = newLoc.getLongitude();
Double latitude = newLoc.getLatitude();
Double height = newLoc.getAltitude();
Float accuracy = newLoc.getAccuracy();
text2 = "Longitude = " + longitude.toString();
text3 = "Latitude = " + latitude.toString();
text4 = "Altitude = " + height.toString();
text5 = "Accuracy = " + accuracy.toString();
textViewHeading.setText(text1);
textViewLong.setText(text2);
textViewLat.setText(text3);
textViewHeight.setText(text4);
textViewAccuracy.setText(text5);
}
};
gps.start(listener);
} // end method onCreate
It seems that this post already has an answer that shows how to use the ProviderLocationTracker. I am putting in my answer just to show how easy it get's with the FallbackLocationTracker.
I do not remember making any significant changes to the FallbackLocationTracker so I am not going to post the whole code.
public class MainActivity extends AppCompatActivity {
private FallbackLocationTracker tracker;
private Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tracker = new FallbackLocationTracker(MainActivity.this);
}
#Override
protected void onResume() {
super.onResume();
// Check for permission to access location and start location
// tracking if permissions are granted and location services
// are enabled
if (locationPermissionGranted && locationServicesEnabled) {
startLocationUpdates();
} else {
// Handle accordingly
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void startLocationUpdates() {
tracker.start(new LocationTracker.LocationUpdateListener() {
#Override
public void onUpdate(Location oldLocation, long oldTime,
Location newLocation, long newTime) {
// You will receive updated changes to your location here
location = newLocation;
}
});
}
private void stopLocationUpdates() {
tracker.stop();
}
}
That's it.

Categories