I am currently working with an Android content provider that i have created i use the query methode in a service because i have to update my result every 2 second my probleme is i want to get the last row in my databases, I put the sursor to the last position but every time his getting me all the data that he found in the database.
this is the service that I developed:
package fr.esigetel.echange.service;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import fr.esigetel.mediatag.cp.WifiProvider;
public class informationService extends Service {
Timer mTimer;
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
returnContentProvider();
}
};
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
Log.d("onCreate informationService", "onCreate informationService");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
mHandler.sendEmptyMessage(0);
}
}, 0, 5000);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
if (mHandler != null) {
mHandler = null;
}
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public informationService() {
}
private void returnContentProvider() {
Uri myuri = Uri.parse("content://fr.esigetel.mediatag.cp/maxdata");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(myuri, null, null, null, null);
int idRech = c.getColumnIndex(WifiProvider.MAX_COL_ID);
int nameap = c.getColumnIndex(WifiProvider.MAX_COL_APName);
int adressemac = c.getColumnIndex(WifiProvider.MAX_COL_AdresseMac);
int rssi = c.getColumnIndex(WifiProvider.MAX_COL_RSSI);
int frequence = c.getColumnIndex(WifiProvider.MAX_COL_Freq);
int daterech = c.getColumnIndex(WifiProvider.MAX_Date);
c.moveToLast();
while (c.moveToPrevious()) {
int id = c.getInt(idRech);
String name = c.getString(nameap);
String mac = c.getString(adressemac);
int Rssi = c.getInt(rssi);
int Freq = c.getInt(frequence);
int Daterech = c.getInt(daterech);
try {
} catch (Exception e) {
System.out.println(e.getMessage());
}
Log.d("aaaaaa", name);
}
c.close();
}
How could i request only the last row of my database? this methode alway give me the whole data.
Cursor c = cr.query(myuri, null, null, null, null);
c.moveToLast();
Now Cursor Is At Last Possition And get The Last Record Data
int idRech = c.getColumnIndex(WifiProvider.MAX_COL_ID);
int nameap = c.getColumnIndex(WifiProvider.MAX_COL_APName);
int adressemac = c.getColumnIndex(WifiProvider.MAX_COL_AdresseMac);
int rssi = c.getColumnIndex(WifiProvider.MAX_COL_RSSI);
int frequence = c.getColumnIndex(WifiProvider.MAX_COL_Freq);
int daterech = c.getColumnIndex(WifiProvider.MAX_Date);
Related
I m building an InterService. This service getting data from bluetooth device.
import android.annotation.SuppressLint;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import com.example.dcubeandroid.dietcontrol.MyDialog;
import com.example.dcubeandroid.dietcontrol.R;
import com.example.dcubeandroid.dietcontrol.apiRequest.iotrequests.DosimeterDataRequest;
import com.example.dcubeandroid.dietcontrol.datasyncingjobs.DosimeterSyncingJob;
import com.example.dcubeandroid.dietcontrol.dosimeter.protocol.BLEUtils;
import com.example.dcubeandroid.dietcontrol.dosimeter.protocol.CRC8Calculator;
import com.example.dcubeandroid.dietcontrol.dosimeter.protocol.MeasurementConverter;
import com.example.dcubeandroid.dietcontrol.dosimeter.protocol.PolismartConstants;
import com.example.dcubeandroid.dietcontrol.utils.AppConstants;
import com.example.dcubeandroid.dietcontrol.utils.Global;
import com.example.dcubeandroid.dietcontrol.utils.PreferenceHandler;
import com.example.dcubeandroid.dietcontrol.utils.Utilities;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
public class DosimeterDataSensingService extends IntentService {
private static final String TAG = "DosimeterDataSensingService";
public static boolean isStarted = false;
private MeasurementConverter measurementConvertor;
private Context mContext;
private int mStatus;
private BluetoothDevice mDevice;
private BluetoothGatt mConnGatt;
private boolean notificationsEnabled;
private long dosimeterScanningTime;
private boolean isThreadStarted = false;
private List<DosimeterDataRequest.DataBean> dosimeterDataList;
private DosimeterDataRequest dosimeterDataRequest;
private String macAddress;
private boolean isRecordingEnabled = false;
private String dose = "";
private int battery = -1;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public DosimeterDataSensingService(String name) {
super(name);
}
public DosimeterDataSensingService() {
super(null);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
dosimeterDataRequest = new DosimeterDataRequest();
dosimeterDataList = new ArrayList<>();
mContext = this;
measurementConvertor = new MeasurementConverter(this);
String scanningTime = PreferenceHandler.readString(this, PreferenceHandler.DOSIMETER_SCANNING_TIME, null);
Log.i("SCANNINGTIME", scanningTime);
if (scanningTime == null) {
dosimeterScanningTime = 0;
} else {
dosimeterScanningTime = Long.parseLong(scanningTime);
}
String mac = PreferenceHandler.readString(this, PreferenceHandler.DM_MAC, null);
if (mac != null) {
connectDosimeter(mac);
}
}
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = createNotificationChannel();
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.logoxhdpi)
.setCategory(Notification.CATEGORY_SERVICE)
.setContentTitle("Cardio App")
.setContentText("Getting data from Dosimeter")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Notification notification = mBuilder.build();
startForeground((int) (System.currentTimeMillis() + 1), notification);
isStarted = true;
if (PreferenceHandler.readString(this, PreferenceHandler.TYPE_USER, null).equals("2")) {
checkDosage();
}
checkBattery();
}
Intent isBatteryLow = new Intent(AppConstants.ACTION_LOW_BATTERY_RECEIVED);
#Override
public void onDestroy() {
isStarted = false;
disconnectDosimeter();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
/**
* connect dosimeter
*
* #param mac mac address of dosimeter
*/
#SuppressLint("LongLogTag")
private void connectDosimeter(String mac) {
macAddress = mac;
// Toast.makeText(getApplicationContext(), "Dosimeter connected", Toast.LENGTH_LONG).show();
Log.d("Global:: ", "Dosimeter Service Started");
mStatus = BluetoothProfile.STATE_DISCONNECTED;
BluetoothAdapter adapter = com.example.dcubeandroid.dietcontrol.zephyerble.BLEUtils.getAdapter();
isRecordingEnabled = true;
mDevice = adapter.getRemoteDevice(mac);
if (mDevice == null) {
mContext.sendBroadcast(new Intent(DosimeterConstants.ACTION_DOSIMETER_DISCONNECTED));
} else
// connect to Gatt
if ((mConnGatt == null) && (mStatus == BluetoothProfile.STATE_DISCONNECTED)) {
// try to connect
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mConnGatt = mDevice.connectGatt(mContext, false, mBluetoothGattCallback, 2);
} else {*/
mConnGatt = mDevice.connectGatt(mContext, false, mBluetoothGattCallback);
//}
mStatus = BluetoothProfile.STATE_CONNECTING;
//Toast.makeText(this, "Dosimeter connected", Toast.LENGTH_LONG).show();
} else {
if (mConnGatt != null) {
// re-connect and re-discover Services
mConnGatt.connect();
mConnGatt.discoverServices();
//mContext.sendBroadcast(new Intent(DosimeterConstants.ACTION_DOSIMETER_DISCONNECTED));
} else {
Log.e(TAG, "state error");
disconnectionHandler.postDelayed(disconnectionRunnable, dosimeterScanningTime);
// Toast.makeText(this, "Dosimeter connection error", Toast.LENGTH_LONG).show();
}
}
}
private BluetoothGattCharacteristic infoCharacteristic;
/**
* bluetooth gatt callback
*/
private BluetoothGattCallback mBluetoothGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
mStatus = newState;
mConnGatt.discoverServices();
//broadcast about connection
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
mStatus = newState;
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
int i = 0;
for (BluetoothGattService service : gatt.getServices()) {
if ((service == null) || (service.getUuid() == null)) {
continue;
}
if (DosimeterConstants.SERVICE_IMMEDIATE_ALERT.equalsIgnoreCase(service.getUuid().toString())) {
infoCharacteristic = service.getCharacteristic(UUID.fromString(DosimeterConstants.CHAR_ALERT_LEVEL));
}
//get charactersticks of third service...............
if (i == 2)
getCharacterSticsOfLastService(service, gatt, i);
i++;
}
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
if (DosimeterConstants.READ_DATA_INSTRUMENT.equalsIgnoreCase(characteristic.getUuid().toString())) {
byte[] value = characteristic.getValue();
if (CRC8Calculator.getCRC8(value, value.length) == value[0]) {
readStatusPacket(value);
//send notify write command
boolean submitted = BLEUtils.SetNotificationForCharacteristic(gatt, characteristic, notificationsEnabled ? BLEUtils.Notifications.DISABLED : BLEUtils.Notifications.NOTIFY);
if (submitted) {
notificationsEnabled = !notificationsEnabled;
}
}
}
}
}
#SuppressLint("LongLogTag")
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
Log.i(TAG, "on characteristicChanged=" + characteristic.getUuid().toString());
if (DosimeterConstants.READ_DATA_INSTRUMENT.equalsIgnoreCase(characteristic.getUuid().toString())) {
byte[] value = characteristic.getValue();
if (CRC8Calculator.getCRC8(value, value.length) == value[0]) {
readStatusPacket(value);
}
}
}
};
private void getCharacterSticsOfLastService(BluetoothGattService service, BluetoothGatt gatt, int i) {
BluetoothGattService blueToothGattService = service == null ? gatt.getServices().get(i) : gatt.getService(service.getUuid());
List<BluetoothGattCharacteristic> characteristics = blueToothGattService.getCharacteristics();
for (BluetoothGattCharacteristic bluetoothGattCharacteristic : characteristics) {
gatt.readCharacteristic(bluetoothGattCharacteristic);
// the engine parses through the data of the btgattcharac and returns a wrapper characteristic
// the wrapper characteristic is matched with accepted bt gatt profiles, provides field types/values/units
// Characteristic charact = Engine.getInstance().getCharacteristic(bluetoothGattCharacteristic.getUuid());
}
}
/**
* read packet data for status
*
* #param paramArrayOfByte packet data in form of byte array
*/
private void readStatusPacket(byte[] paramArrayOfByte) {
}
#SuppressLint("LongLogTag")
public void disconnectDosimeter() {
Log.v("Dosimeter", "isRecordingEnabled" + isRecordingEnabled);
Log.v("Dosimeter", "Disconnecteddd");
}
}
Now this IntentService use this variable :
String scanningTime = PreferenceHandler.readString(this, PreferenceHandler.DOSIMETER_SCANNING_TIME, null);
Now when the service is started, I want to change the values of this "scanningTime".
So I m build this code in another class:
String dosimeterScanningTime = "newValue";
PreferenceHandler.writeString(getApplicationContext(), PreferenceHandler.DOSIMETER_SCANNING_TIME, dosimeterScanningTime!=null ? dosimeterScanningTime.toString() : null);
if (Build.VERSION.SDK_INT >= 26) {
stopService(new Intent(this, DosimeterDataSensingService.class));
startForegroundService(new Intent(this, DosimeterDataSensingService.class));
} else {
stopService(new Intent(this, DosimeterDataSensingService.class));
startService(new Intent(getApplicationContext(), DosimeterDataSensingService.class));
}
Now the code works without issue or exception but If I don't restart my application the value of "scanningTime" in my IntentService is not changed.
If I restarted the application, scanningTime = newValue.
How can I fixed them?
I have this service which send my location to server and get some data from it.
package com.speed00.service;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.widget.Toast;
import com.google.gson.Gson;
import com.speed00.R;
import com.speed00.constant.AppConstant;
import com.speed00.helper.FunctionHelper;
import com.speed00.model.achivment.StepHelper;
import com.speed00.model.ride.RideResultResponse;
import com.speed00.model.ride.UpdateLocationData;
import com.speed00.model.ride.UpdateLocationResponse;
import com.speed00.prefrences.MyPreferences;
import com.speed00.prefrences.MySharedPreference;
import com.speed00.retrofit.ApiUtils;
import com.speed00.stepdetucter.StepDetector;
import com.speed00.stepdetucter.StepListener;
import com.speed00.ui.activity.HomeActivity;
import com.speed00.utils.Logger;
import com.speed00.utils.MySensorEventListener;
import com.speed00.utils.NetworkConnection;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MyService extends Service implements StepListener, SensorEventListener {
// constant
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
private Double locationRange = 1.0;
private String oldDegree;
private boolean isServiceRunning;
private int numSteps = 0;
private final int FINAL_STEP = 15;
private SensorManager sensorManager;
private Sensor accel;
String speed_received = "0";
private boolean pedoMetterHasStarted = false;
String pLatitude;
String pLongitude;
private SensorEventListener eListener;
private Sensor accelerometer, magFieldSensor;
private StepDetector simpleStepDetector;
#Override
public IBinder onBind(Intent intent) {
return null;
}
private BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, final Intent intent) {
// TODO Auto-generated method stub
new Handler().post(new Runnable() {
#Override
public void run() {
speed_received = intent.getStringExtra("current speed");
Logger.e("speed__recv" + speed_received);
if (speed_received != null) {
// setSpeedValue(speed_received);//this method is calling to set speed.
//This method is calling to validate Timer For Ride
if (speed_received.equalsIgnoreCase("0")) {
if (!pedoMetterHasStarted) {
numSteps = 0;
statPedoMeter();
}
}
//Calculating distance value
String latitude = MySharedPreference.getInstance(MyService.this).getLatitude();
String longitude = MySharedPreference.getInstance(MyService.this).getLongitude();
if (TextUtils.isEmpty(pLatitude)) {
pLatitude = latitude;
pLongitude = longitude;
} else {
/*
* if distance is more then 2 km then its calculatiog.
*
* */
Location pLocation = new Location("P");
pLocation.setLongitude(Double.parseDouble(pLatitude));
pLocation.setLongitude(Double.parseDouble(pLongitude));
Location nLocation = new Location("N");
nLocation.setLongitude(Double.parseDouble(latitude));
nLocation.setLongitude(Double.parseDouble(longitude));
Logger.e("distance----" + pLocation.distanceTo(nLocation));
if (pLocation.distanceTo(nLocation) >= 10) {
pLatitude = latitude;
pLongitude = longitude;
}
}
}
}
});
}
};
#Override
public void onCreate() {
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
eListener = new MySensorEventListener(this, sensorManager);//for direction
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magFieldSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
//callback sensor of ui
sensorManager.registerListener(eListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(eListener, magFieldSensor, SensorManager.SENSOR_DELAY_NORMAL);
assert sensorManager != null;
accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
simpleStepDetector = new StepDetector();
simpleStepDetector.registerListener(this);
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show();
isServiceRunning = true;
// Toast.makeText(getApplicationContext(), "service started", Toast.LENGTH_SHORT).show();
// cancel if already existed
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
// new Timer().scheduleAtFixedRate(new TimeDisplayTimerTask(), 100, NOTIFY_INTERVAL);
runLoop();
LocalBroadcastManager.getInstance(this).registerReceiver(message,
new IntentFilter("send"));
}
private void runLoop() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
updateDriverLocation();
if (isServiceRunning)
runLoop();
}
}, 1000);
}
/*
*
* This method is calling to update driver location
* */
private void updateDriverLocation() {
//Get all user details data.
String userId = MySharedPreference.getInstance(getApplicationContext()).getDriverId();
String latitudeData = MySharedPreference.getInstance(getApplicationContext()).getLatitude();
String longitudeData = MySharedPreference.getInstance(getApplicationContext()).getLongitude();
String speedData = MySharedPreference.getInstance(getApplicationContext()).getSpeedData();//how to roinf
Logger.e("SERVER " + latitudeData + " " + longitudeData);
Logger.e("SPEED " + speedData);
String directionValue = MySharedPreference.getInstance(getApplicationContext()).getDirectionValue();
String speeding = MySharedPreference.getInstance(getApplicationContext()).getSpeeding();
String language = MyPreferences.newInstance(getApplicationContext()).getLanguage();//send speeding data to bakend.
String directionText = MySharedPreference.getInstance(getApplicationContext()).getDirectionText();
long driveTime = FunctionHelper.getDifference(MySharedPreference.getInstance(getApplicationContext()).getStartTime());
String validateUTurn = validateUTurn();
// Logger.e("update_request--" + request);
ApiUtils.getAPIService().updateDriverLocation(validateUTurn, directionText, speeding, "" + driveTime, language, userId,
AppConstant.START_RIDE, speedData, directionValue, latitudeData, longitudeData).enqueue(new Callback<UpdateLocationResponse>() {
#Override
public void onResponse(Call<UpdateLocationResponse> call, Response<UpdateLocationResponse> response) {
if (response.isSuccessful()) {
UpdateLocationResponse updateLocationResponse = response.body();
if (updateLocationResponse.getErrorCode().equalsIgnoreCase(AppConstant.ERROR_CODE)) {
if (updateLocationResponse.getData().size() > 0) {
UpdateLocationData updateLocationData = updateLocationResponse.getData().get(0);
String eventData = FunctionHelper.validateData(updateLocationData);
broadCastEventData(eventData, updateLocationResponse.getErrorCode());
broadCastResponseData(updateLocationResponse);
}
}
}
}
#Override
public void onFailure(Call<UpdateLocationResponse> call, Throwable t) {
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
/*
*
*This method is calling to validateUTurn.
*
*
* */
private String validateUTurn() {
String currentDegree = MySharedPreference.getInstance(this).getDirectionValue();
String uTurnStatus = "0";
if (TextUtils.isEmpty(oldDegree)) {
oldDegree = currentDegree;
uTurnStatus = "0";
return uTurnStatus;
} else {
if (oldDegree == "0.0") {
oldDegree = currentDegree;
}
if (Float.parseFloat(oldDegree) <= Float.parseFloat(currentDegree)) {
uTurnStatus = "1";
} else {
uTurnStatus = "0";
}
if (Float.parseFloat(oldDegree) == 360 || Float.parseFloat(oldDegree) > 270) {
if (Float.parseFloat(currentDegree) > 0 && Float.parseFloat(oldDegree) <= 90) {
uTurnStatus = "1";
}
}
oldDegree = currentDegree;
return uTurnStatus;
}
}
public synchronized void broadCastEventData(String eventData, String errorCode) {
Intent intent = new Intent("event_broad_cast");
intent.putExtra("data", eventData);
intent.putExtra("error", errorCode);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
/*
* This method is calling to broadcast event data
* */
/*
* This method is calling to broadcast event data
* */
public synchronized void broadCastResponseData(UpdateLocationResponse updateLocationData) {
Intent intent = new Intent("location_update");
Bundle args = new Bundle();
args.putSerializable("data", (Serializable) updateLocationData);
intent.putExtra("myvalue", args);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
isServiceRunning = false;
LocalBroadcastManager.getInstance(this).unregisterReceiver(message);
// stopPedoMeter();
}
#Override
public void step(long timeNs) {
if (numSteps < 16)
Toast.makeText(this, "" + numSteps, Toast.LENGTH_SHORT).show();
saveStep();
if (calculateSteps()) {
stopRideAfter25step();
stopPedoMeter();//this method is calling to stop ResultActivity
} else if (Double.parseDouble(MySharedPreference.getInstance(this).getSpeedData()) > 10) {
MySharedPreference.getInstance(this).setSteps(new ArrayList<StepHelper>());
numSteps = 0;
} else {
Logger.e("stepsss " + numSteps);
numSteps = numSteps + 1;
}
}
private void stopRideAfter25step() {
MySharedPreference.getInstance(this).setSteps(new ArrayList<StepHelper>());
String speed = MySharedPreference.getInstance(this).getSpeedData();
String direction = MySharedPreference.getInstance(this).getDirectionValue();
String latitude = MySharedPreference.getInstance(this).getLatitude();
String longitude = MySharedPreference.getInstance(this).getLongitude();
String driverId = MySharedPreference.getInstance(this).getDriverId();
String language = MyPreferences.newInstance(this).getLanguage();
String speeding = MySharedPreference.getInstance(this).getSpeeding();
long driveTime = FunctionHelper.getDifference(MySharedPreference.getInstance(this).getStartTime());
//validate internet connection
if (NetworkConnection.isConnection(this)) {
stopRide("" + driveTime, language, speeding, driverId, latitude, longitude, AppConstant.STOP_RIDE, speed, direction);
} else {
Toast.makeText(this, getString(R.string.valid_please_check_network_connection), Toast.LENGTH_LONG).show();
}
}
public void stopRide(final String driveTime, final String languageKey, final String speedLimit, final String driverId, final String latitude, final String longitude, String rideStatus, final String speed, final String direction) {
String[] param = {driveTime, languageKey, speedLimit, driverId, speed, direction, latitude, longitude};
new stopLoc(this).execute(param);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
simpleStepDetector.updateAccel(event.timestamp, event.values[0], event.values[1], event.values[2]);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
private static class stopLoc extends AsyncTask<String[], Void, Void> {
Context mContext;
public stopLoc(Context mContext) {
this.mContext = mContext;
}
#Override
protected Void doInBackground(String[]... strings) {
Logger.e("stepsss stopingggg");
String driveTime = strings[0][0];
String languageKey = strings[0][1];
String speedLimit = strings[0][2];
String driverId = strings[0][3];
String speed = strings[0][4];
String direction = strings[0][5];
String latitude = strings[0][6];
String longitude = strings[0][7];
ApiUtils.getAPIService().stopTrip(driveTime, languageKey, speedLimit, driverId, AppConstant.STOP_RIDE, speed, direction, latitude, longitude).enqueue(new Callback<RideResultResponse>() {
#Override
public void onResponse(Call<RideResultResponse> call, Response<RideResultResponse> response) {
Logger.e("response----" + new Gson().toJson(response.body()));
if (response.isSuccessful()) {
String errorCode = response.body().getErrorCode();
if (errorCode.equalsIgnoreCase(AppConstant.ERROR_CODE)) {
tripSuccessData(response.body(), mContext);
} else {
Toast.makeText(mContext, "" + mContext.getString(R.string.text_some_erroroccurs), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<RideResultResponse> call, Throwable t) {
Toast.makeText(mContext, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
return null;
}
}
public static void tripSuccessData(Object data, Context context) {
RideResultResponse resultResponse = (RideResultResponse) data;
if (resultResponse.getErrorCode().equalsIgnoreCase(AppConstant.ERROR_CODE)) {
FunctionHelper.enableUserIntraction();
HomeActivity.bSpeedStatus = false;
Intent intent = new Intent("trip_ended");
intent.putExtra("trip_info", resultResponse.getData().get(0));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
((MyService) context).stopSelf();
} else {
Toast.makeText(context, resultResponse.getErrorMsg(), Toast.LENGTH_SHORT).show();
}
}
private boolean calculateSteps() {
ArrayList<StepHelper> arrayList = MySharedPreference.getInstance(this).getSteps();
ArrayList<StepHelper> newList = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
long seconds = FunctionHelper.getDifference(arrayList.get(i).getTime());
if ((int) seconds < 180) {
newList.add(arrayList.get(i));
}
}
if (numSteps - newList.get(0).getSteps() >= FINAL_STEP) {
return true;
} else {
MySharedPreference.getInstance(this).setSteps(newList);
return false;
}
}
private void saveStep() {
ArrayList<StepHelper> arrayList = MySharedPreference.getInstance(this).getSteps();
if (arrayList == null) {
arrayList = new ArrayList<>();
}
arrayList.add(new StepHelper(FunctionHelper.getCurrentDateWitTime(), numSteps));
MySharedPreference.getInstance(this).setSteps(arrayList);
}
private void statPedoMeter() {
// Toast.makeText(this, "start count", Toast.LENGTH_SHORT).show();
pedoMetterHasStarted = true;
MySharedPreference.getInstance(this).setStartPedoMeterTime(FunctionHelper.getCurrentDateWitTime());//store current time
if (sensorManager != null)
sensorManager.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);
}
/*
* This method is calling to stop pedo meter
*
* */
private void stopPedoMeter() {
numSteps = 0;
pedoMetterHasStarted = false;
sensorManager.unregisterListener(this, accelerometer);
sensorManager.unregisterListener(this, accel);
sensorManager.unregisterListener(this, magFieldSensor);
sensorManager = null;
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
Logger.e("MyService --- " + "isRuning");
if (HomeActivity.bSpeedStatus) {
updateDriverLocation();
}
}
});
}
}
}
My app starts and use only 170 MB , but after starting this service , it becomes 220 MB and after finishing it, it still 220 and if i open it again , ram become 240 and if i finish it still 240 and if i open it again it become 260 and so on until app crash
what's the wrong in the service ?
i make sure that it's stopped but don't know why ram not reduced after this service is finished
Try this approache, don't put the stopSelf() inside a static method. Instead, you should call startService again and add an action to the Intent.
So this is how an example actionable service should look like:
public class ExampleService
extends Service {
public static final String START_SERVICE_ACTION = "com.example.action.START_SERVICE";
public static final String STOP_SERVICE_ACTION = "com.example.action.STOP_SERVICE";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String intentAction = intent.getAction();
switch (intentAction) {
case START_SERVICE_ACTION:
//
break;
case STOP_SERVICE_ACTION:
stopSelf();
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// Used only in case if services are bound (Bound Services).
return null;
}
}
Interact with the Service from somewhere:
Start with it like this:
Intent service = new Intent(context, ExampleService.class);
service.setAction(NotificationService.START_SERVICE_ACTION);
startService(service);
Stop it like this:
Intent service = new Intent(context, ExampleService.class);
service.setAction(NotificationService.STOP_SERVICE_ACTION);
startService(service);
You don't really need to pass the START_SERVICE_ACTION in this example, just added it to better understand the design.
Hello my fellow programmers :)
I call the function waitRunnable(int seconds, int startId) 4 times every time I click a button in my application. So waitRunnable() should just wait a variable amount of time and the time is set by a parameter seconds. But they run all at the same time so if the longest waitRunnable gets 10 seconds to wait and the other 3 waitRunnables wait less time then all 4 waitRunnables finish after 10 seconds but the first one should finish and just then the second one should be started so the total amount of time would be the sum of all parameters. I hope this is not to bad explained.
In love your jason <3 Thx for help :)
package com.example.Uebung10;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.os.Handler;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by Jason on 14.01.2016.
*/
public class MyService extends Service {
final String LOG_TAG = "myServiceLogs";
Handler h = new Handler();
List<String> finishedTasksInTheLast60Sec = new ArrayList<>();
ExecutorService es;
Runnable r = new Runnable() {
#Override
public void run() {
sendBroadcast(finishedTasksInTheLast60Sec);
h.postDelayed(this, 60000);
finishedTasksInTheLast60Sec = new ArrayList<>();
}
};
private void waitRunnable(int seconds, int startId) {
h.postDelayed(new Runnable() {
#Override
public void run() {
finishedTasksInTheLast60Sec.add("Finished Task: MyRun#" + startId);
Log.d(LOG_TAG, "MyRun#" + startId + " end");
}
}, TimeUnit.SECONDS.toMillis(seconds));
}
private void sendBroadcast(List<String> finishedTasks) {
Intent intent = new Intent("myServiceUpdate");
intent.putExtra("finishedTasks", (ArrayList<String>)finishedTasks);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "MyService onCreate");
es = Executors.newFixedThreadPool(1);
h.postDelayed(r, 60000);
}
public void onDestroy() {
super.onDestroy();
h.removeCallbacks(r);
Log.d(LOG_TAG, "MyService onDestroy ");
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LOG_TAG, "MyService onStartCommand");
readFlags(flags);
int time = intent.getIntExtra("time", 1);
if (time != -1) {
MyRun mr = new MyRun(time, startId);
es.execute(mr);
} else stopSelf();
return START_NOT_STICKY;
//return START_STICKY;
//return START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
Log.d(LOG_TAG, "onBind");
return null;
}
void readFlags(int flags) {
if ((flags & START_FLAG_REDELIVERY) == START_FLAG_REDELIVERY)
Log.d(LOG_TAG, "START_FLAG_REDELIVERY");
if ((flags & START_FLAG_RETRY) == START_FLAG_RETRY)
Log.d(LOG_TAG, "START_FLAG_RETRY");
}
class MyRun implements Runnable {
int time;
int startId;
public MyRun(int time, int startId) {
this.time = time;
this.startId = startId;
Log.d(LOG_TAG, "MyRun#" + startId + " create");
}
#Override
public void run() {
Log.d(LOG_TAG, "MyRun#" + startId + " start, time = " + time);
waitRunnable(time, startId);
}
}
}
You can use an ExecutorService to store a queue of Runnables and perform them one at a time. Call ExecutorService#submit to add a Runnable to the queue.
http://developer.android.com/reference/java/util/concurrent/ExecutorService.html
I am trying to implement contact pciker in android, i am able to launch contact picker in android, but when i select the contact i get back null value, i.e. no number in my textfield. What am i doing wrong ?
Here is my code.
mainactivity.java
package com.example.textmessage;
import java.util.Timer;
import java.util.TimerTask;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.Settings;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import com.google.android.gms.maps.SupportMapFragment;
import android.widget.Toast;
public class MainActivity extends FragmentActivity{
protected static final int CONTACT_PICKER_RESULT = 0;
int count=0;
private RadioButton radioBtnten;
private RadioButton radioBtnone;
Button sendBtn,contact;
EditText txtphoneNo;
EditText txtMessage;
GPSTracker gps;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled)
{
Toast.makeText(getApplicationContext(), "Your GPS IS NOT ON SWITCH IT ON HERE",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
radioBtnten=(RadioButton)findViewById(R.id.ten);
radioBtnone=(RadioButton)findViewById(R.id.one);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo= (EditText) findViewById(R.id.editTextPhoneNo);
contact = (Button)findViewById(R.id.contact);
//txtMessage //= (EditText) findViewById(R.id.editTextSMS);
gps = new GPSTracker(MainActivity.this);
contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri contact = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = managedQuery(contact, null, null, null, null);
// c.moveToFirst();
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
txtphoneNo.setText(phone);
}
}
}
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTimer();
sendSMSMessage();
Intent toAnotherActivity = new Intent(MainActivity.this, maps.class);
startActivityForResult(toAnotherActivity, 0);
}
});
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms//
if(radioBtnten.isChecked()==true)
timer.schedule(timerTask, 5000, 10000);
// if(radioBtn2.isSelected()==true)
else if(radioBtnone.isChecked()==true)
timer.schedule(timerTask, 5000, 1000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
//get the current timeStamp
Toast.makeText(getApplicationContext(), "your message has been sent, the message(s) sent are:-"+count++,Toast.LENGTH_LONG).show();
sendSMSMessage();
//show the toast
}
});
}
};
}
public void stoptimertask(View v)
{
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
if (timer != null)
{
timer.cancel();
timer = null;
}
}
protected void sendSMSMessage() {
Log.i("Send SMS", "");
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String phoneNo = txtphoneNo.getText().toString();
String message = "These are my co-ordinates:-"+ latitude + ", " + longitude;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
P.S. i have mentioned the permission in manifest.
From your code it seems to be you have not added onActivityResult method. Put the following code in in onActivityResult method
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
Uri contact = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = managedQuery(contact, null, null, null, null);
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
tv.setText( phone);
}
}
}}
I am writing a service based app with a bound service, and the service's onBind() method never seems to be called (testing it with Toasts and Logs).
The service:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.gmail.zack.yovel.FlickAround.MyActivity;
import com.gmail.zack.yovel.FlickAround.R;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: Ziky
* Date: 09/04/13
* Time: 19:06
* To change this template use File | Settings | File Templates.
*/
public class UpdateService extends Service implements LocationListener, UpdatePhotosTask.OnHttpResponseListener {
private final static String API_KEY = "5255c7b02750c0fa4b15bd8ad4ec1fb7";
private final static String GET_PHOTOS_FOR_LOCATION_SCHEMA = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=" + API_KEY + "&lat=%d&lon=%d&format=json&nojsoncallback=1";
private static final String KEY_PHOTOS = "photos";
private static final String KEY_PHOTO = "photo";
private int NOTIFICATION = R.string.update_service_started;
private NotificationManager mNManager;
private LocationManager mLManager;
private String mProvider;
private Location mLocation;
private IBinder mBinder = new LocalBinder();
private UpdatePhotosTask task;
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "UpdateService.onBind()", Toast.LENGTH_LONG).show();
Log.i("test", "UpdateService.onBind()");
mLManager.requestLocationUpdates(mProvider, 0, 1000, this);
return mBinder;
}
#Override
public void onCreate() {
mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
mLManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mProvider = mLManager.getBestProvider(criteria, false);
mLocation = mLManager.getLastKnownLocation(mProvider);
return START_STICKY;
}
#Override
public void onDestroy() {
mNManager.cancel(NOTIFICATION);
Toast.makeText(this, R.string.update_service_stoped, Toast.LENGTH_SHORT).show();
}
private void showNotification() {
CharSequence text = getText(R.string.update_service_active);
Notification notification = new Notification(R.drawable.refresh, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0);
notification.setLatestEventInfo(this, getText(R.string.update_service_label), text, contentIntent);
mNManager.notify(NOTIFICATION, notification);
}
#Override
public void onLocationChanged(Location location) {
beginUpdate(location);
}
private void beginUpdate(Location location) {
Toast.makeText(this, "beginning update", Toast.LENGTH_LONG).show();
String url = buildUrl(location);
task = new UpdatePhotosTask(this);
task.execute(url);
}
private String buildUrl(Location location) {
return String.format(GET_PHOTOS_FOR_LOCATION_SCHEMA, location.getLatitude(), location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onHttpResponse(ArrayList<String> responses) {
if (responses.size() > 0) {
String response = responses.get(0);
try {
JSONObject jsonObject = new JSONObject(response);
jsonObject = jsonObject.getJSONObject(KEY_PHOTOS);
JSONArray jsonArray = jsonObject.getJSONArray(KEY_PHOTO);
ArrayList<String> photos = new ArrayList<String>();
for (int i = 0, length = jsonArray.length(); i < length; i++) {
jsonObject = jsonArray.getJSONObject(i);
Log.i("photo info", jsonObject.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class LocalBinder extends Binder {
public UpdateService getService() {
return UpdateService.this;
}
}
}
The AsyncTask:
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: Ziky
* Date: 09/04/13
* Time: 07:38
* To change this template use File | Settings | File Templates.
*/
public class UpdatePhotosTask extends AsyncTask<String, Void, ArrayList<String>> {
private OnHttpResponseListener listener;
public UpdatePhotosTask(OnHttpResponseListener listener) {
this.listener = listener;
}
#Override
protected ArrayList<String> doInBackground(String... urls) {
ArrayList<String> responses = new ArrayList<String>();
for (String url : urls) {
StringBuilder response = new StringBuilder();
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
StatusLine statusLine = execute.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response.append(s);
}
responses.add(response.toString());
} else {
Log.e(this.getClass().toString(), "Failed to download photo list");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responses;
}
#Override
protected void onPostExecute(ArrayList<String> responses) {
listener.onHttpResponse(responses);
}
public interface OnHttpResponseListener {
public void onHttpResponse(ArrayList<String> responses);
}
}
The activity:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;
import android.widget.Toast;
import com.gmail.zack.yovel.FlickAround.background.UpdateService;
public class MyActivity extends Activity {
private UpdateService mUpdateService;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mUpdateService = ((UpdateService.LocalBinder) service).getService();
Toast.makeText(MyActivity.this, R.string.update_service_connected, Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName name) {
mUpdateService = null;
Toast.makeText(MyActivity.this, R.string.local_service_disconnected, Toast.LENGTH_SHORT).show();
}
};
private boolean mIsBound;
void doBindService() {
Toast.makeText(this, "MyActivity.doBindService()", Toast.LENGTH_LONG).show();
bindService(new Intent(this, UpdateService.class), mConnection, BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Activate StrictMode
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().penaltyDeath().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog().penaltyDeath().build());
}
#Override
protected void onStart() {
super.onStart();
doBindService();
}
}
Why isn't it working?
Probably the most common source of binding silently failing is not having the service listed in the manifest. This does not raise an exception, so your app does not crash, but there should be a message (warning, IIRC) in LogCat pointing out your issue.