I am trying to implement a app which updates user location at every 15 seconds,stores data to database and show it to listview in my activity.
Location should always update even activity destroys,for that i have created LocationService class.
The problem is I am able to get updates and also able to store into database but i am unable to show these updates in listview at runtime means i want list should refresh at every 15 sec and show it to UI..
Also when I get details from database I am unable to get latest detail instead i get whole arraylist every time which affects my activity response.I want that only newly added data will be fetch from database so that it will take less time in loading but I want to display all data to list everytime.
I have implement a thread (Commented code)which fetch data and show to listview but this is not right way to update UI..please suggest me a way so that i can refresh my list when new data is added into database
This is my activity
public class MainActivity extends Activity {
List<MyLocation> locationList = new ArrayList();
ListView mList;
LocationAdapter adapter;
BroadcastReceiver receiver;
LocationService mService;
boolean mBound = false;
private DbHelper dbHelper;
private Button updateLocation;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
LocationService.LocalBinder binder = (LocationService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateLocation = (Button) findViewById(R.id.update_location);
mList = (ListView) findViewById(R.id.listView);
dbHelper = new DbHelper(this);
updateLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationList = mService.displayLocation();
adapter = new LocationAdapter(MainActivity.this, locationList);
mList.setAdapter(adapter);
}
});
/*
Thread mThread = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(500);
runOnUiThread(new Runnable() {
#Override
public void run() {
locationList = dbHelper.getLocationDetails();
Collections.reverse(locationList);
adapter = new LocationAdapter(MainActivity.this, locationList);
mList.setAdapter(adapter);
}
});
}
} catch (InterruptedException e) {
}
}
};
mThread.start();*/
}
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, LocationService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
}
LocationService
public class LocationService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks {
private final IBinder mBinder = new LocalBinder();
ArrayList<MyLocation> locationList = new ArrayList<>();
private DbHelper dbHelper;
private Location mLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private String TAG = "Service";
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
dbHelper = new DbHelper(this);
createLocationRequest();
displayLocation();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "service destroy");
}
public List<MyLocation> displayLocation() {
mLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
String lastUpdateTime = DateFormat.getTimeInstance().format(new Date());
dbHelper.insertLocationDetails(longitude, latitude, lastUpdateTime);
locationList = dbHelper.getLocationDetails();
return locationList;
} else {
return null;
}
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Connected to update");
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void onLocationChanged(Location location) {
mLocation = location;
Toast.makeText(getApplicationContext(), "Location changed",
Toast.LENGTH_SHORT).show();
displayLocation();
}
public void onConnected(Bundle arg0) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
public class LocalBinder extends Binder {
public LocationService getService() {
return LocationService.this;
}
}
}
Dbhelper
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String LONGITUDE = "longitude";
private static final String LATITUDE = "latitude";
private static final String LOCATION_CHANGE_TIME = "location_change_time";
private static final String LOCATION_DETAIL_TABLE = "location_detail_table";
private static final String CREATE_TABLE_LOCATION = "CREATE TABLE "
+ LOCATION_DETAIL_TABLE + " (" + LONGITUDE + " TEXT,"
+ LOCATION_CHANGE_TIME + " TEXT,"
+ LATITUDE + " TEXT)";
public static String DATABASE_NAME = "Location_database";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(CREATE_TABLE_LOCATION);
}
public void insertLocationDetails(double longitude, double latitude, String time) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(LONGITUDE, longitude);
values.put(LATITUDE, latitude);
values.put(LOCATION_CHANGE_TIME, time);
long id= database.insert(LOCATION_DETAIL_TABLE, null, values);
System.out.println("Newly added item id "+id);
database.close();
}
public ArrayList<MyLocation> getLocationDetails() {
ArrayList<MyLocation> locationList = new ArrayList();
String selectQuery = "SELECT * FROM " + LOCATION_DETAIL_TABLE;
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToNext()) {
do {
MyLocation location = new MyLocation();
String longitude = cursor.getString(cursor
.getColumnIndexOrThrow(LONGITUDE));
String latitude = cursor.getString(cursor.getColumnIndexOrThrow(LATITUDE));
String time = cursor.getString(cursor
.getColumnIndexOrThrow(LOCATION_CHANGE_TIME));
location.setLatitude(latitude);
location.setLongitude(longitude);
location.setLastUpdatedTime(time);
locationList.add(location);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
database.close();
return locationList;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
In your case, you can use ContentProvider and implements LoaderManager.LoaderCallbacks in your activity.
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
db = dbHelper.getWritableDatabase();
String table = uri.getLastPathSegment();
long rowID = db.insert(table, null, values);
Uri CONTENT_URI = Uri.parse("content://"
+ AUTHORITY + "/" + table);
Uri resultUri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(resultUri, null);
return resultUri;
}
Line
getContext().getContentResolver().notifyChange(resultUri, null);
in ContentProvider will cause requery data. And using SimpleAdapter in activity will update your UI.
You can use Callback for this purpose.
Define some interface like
public class LocationInterface(){
public void sendLocationDetails(Long lat, Long lon, String time);
}
Now let your Activity implement this interface.
public class MyActivity implements LocationInterface {
#Override
public void sendLocationDetails(Long lat, Long lon, String time){
//At this point, you have the required details
}
}
Now in LocationService.java you need to pass this interface as an argument.
public class LocationService {
private LocationInterface locationInterface;
LocationInterface(LocationInterface locationInterface){
this.locationInterface = locationInterface;
}
}
Now whenever you call displayLocation() method, you can call this interface and send data to the activity.
public List<MyLocation> displayLocation() {
mLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
String lastUpdateTime = DateFormat.getTimeInstance().format(new Date());
//At this point, you are calling the interface.
locationInterface.sendDetails(latitude,longitude,lastUpdateTime);
dbHelper.insertLocationDetails(longitude, latitude, lastUpdateTime);
locationList = dbHelper.getLocationDetails();
return locationList;
} else {
return null;
}
}
Related
How can I call the method "loginprep" of the LoginActivityClass from the FingerPrintClass?
See in the code...I wrote in where I want to call the loginprep with: "//Here I need the method loginprep() from the LoginActivity class"
FingerprintHandler.java
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private Context context;
// Constructor
public FingerprintHandler(Context mContext) {
context = mContext;
}
public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {
CancellationSignal cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
Toast.makeText((Activity)context, "Fingerprint Authentication error.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
Toast.makeText((Activity)context, "Fingerprint Authentication help.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationFailed() {
Toast.makeText((Activity)context, "Fingerprint Authentication failed.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
//Here I need the method loginprep() from the LoginActivity class
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
public void loginprep() {
SharedPreferences sharedPreferencesF = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPreferencesF.getString("username", "");
String pwd = sharedPreferencesF.getString("password", "");
loginUser(urn, pwd);
}
private void launchHomeScreen() {
Intent homeActivity = new Intent (LoginActivity.this,HomeActivity.class);
LoginActivity.this.startActivity(homeActivity);
finish();
}
public void loginUser(final String urn, final String pwd){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
System.out.println("JSON RESPONSE: " + jsonResponse.toString());
boolean success = jsonResponse.getBoolean("success");
if (success) {
launchHomeScreen();
pd.dismiss();
Toast.makeText(LoginActivity.this,"Welcome back " + urn,Toast.LENGTH_LONG).show();
SharedPreferences sharedPref = getSharedPreferences("loginDatas", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", urn);
editor.putString("password", pwd);
editor.apply();
}
else {
loginButton.setBackgroundColor(0x73000000);
Toast.makeText(LoginActivity.this,"Wrong Username or Password!",Toast.LENGTH_LONG).show();
pd.dismiss();
}
}
catch (JSONException e) {
loginButton.setBackgroundColor(0x73000000);
e.printStackTrace();
pd.dismiss();
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loginButton.setBackgroundColor(0x73000000);
pd.dismiss();
System.out.println("Error: " + error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put(KEY_USERNAME,urn);
params.put(KEY_PASSWORD,pwd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Following:
MainActivity mActivity = new MainActivity();
this is not the way Android is expecting you to create new instances of an activity, normally you wait the onCreate callback as described in the activity lifeCycle...
no following that approach you will need another way to communicate 2 different activities, what way must be taken depends on the specific arch of your application... the most commonly implemented could be using self defined interfaces and implement you custom callbacks...
You're writing a FingerPrint callback class, which means there is some onAuthenticationSucceeded method that is called when the "authentication succeeds."
How about you implement your own callback to pass back into the LoginActivity?
In other words, you'd
1) Write an interface
public interface LoginListener {
void onLoginSuccess();
void onLoginFailed();
}
2) Have the Activity implements LoginListener and have the Activity method of onLogin do your non-static stuff with the SharedPreferences,
public class LoginActivity extends AppCompatActivity
implements LoginListener {
public static final String KEY_USERNAME = "username";
public static final String KEY_PASS = "password";
private FingerprintHandler fingerprintHandler;
#Override
public void onLoginFailed() { }
#Override
public void onLoginSuccess() {
SharedPreferences sharedPrefs = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPrefs.getString(KEY_USERNAME, "");
String pwd = sharedPrefs.getString(KEY_PASS, "");
loginUser(urn, pwd);
}
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_login);
fingerprintHandler = new FingerprintHandler(this);
}
// public void loginUser(final String urn, final String pwd){ }
}
3) Expect to pass in a LoginListener as a parameter to that separate class.
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private final Context mContext;
private LoginListener mListener;
// Constructor
public FingerprintHandler(Context context) {
mContext = context;
if (context instanceof LoginListener) {
this.mListener = (LoginListener) context;
} else {
throw new ClassCastException("FingerprintHandler: context must implement LoginListener!");
}
}
4) And you do then can use your callback from the other callback.
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
if (mListener != null) {
mListener.onLoginSuccess();
}
}
I have made a class LocationFinder which gets the user's location.
I am instantiating the class and class and calling required methods to get the location.
Now after the location is found in LocationFinder class, I want to communicate with my MainActivity so that I can update the user's location on some TextView.
To do so, I have done this:
The constructor of my LocationFinder class looks like:
private Context context;
private OnLocationFoundListener onLocationFoundListener;
public LocationFinder(Context context) {
this.context = context;
onLocationFoundListener = (OnLocationFoundListener) context; // here is the exception is thrown
}
Where OnLocationFoundListener is an interface like:
public interface OnLocationFoundListener
{
void setOnLocationFoundListener(String cityName, String stateName, String countryName);
}
After this on successful location found I am using onLocationFoundListener.setOnLocationFoundListener(cityName, stateName, countryName); to notify the MainActivity where I'm implementing the OnLocationFoundListener and overriding the required method.
The code sample is:
The LocationFinder class:
public class LocationFinder implements LocationListener {
private Context context;
private OnLocationFoundListener onLocationFoundListener;
public LocationFinder(Context context) {
this.context = context;
onLocationFoundListener = (OnLocationFoundListener) context;
}
private static final int MY_PERMISSIONS_ACCESS_FINE_LOCATION = 1;
private LocationManager locationManager;
private ProgressDialog progressDialog;
void getCityByLocation() {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity)context,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Explanation not needed, since user requests this himself
} else {
ActivityCompat.requestPermissions((Activity)context,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_ACCESS_FINE_LOCATION);
}
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(context.getString(R.string.getting_location));
progressDialog.setCancelable(false);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
locationManager.removeUpdates(LocationFinder.this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
});
progressDialog.show();
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
} else {
showLocationSettingsDialog();
}
}
#Override
public void onLocationChanged(Location location) {
progressDialog.hide();
try {
locationManager.removeUpdates(this);
} catch (SecurityException e) {
Log.e("LocationManager", "Error while trying to stop listening for location updates. This is probably a permissions issue", e);
}
Log.i("LOCATION (" + location.getProvider().toUpperCase() + ")", location.getLatitude() + ", " + location.getLongitude());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
getCityDetails(latitude, longitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private void getCityDetails(double lat, double lon)
{
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat, lon, 1);
} catch (IOException e) {
e.printStackTrace();
}
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
progressDialog.dismiss();
onLocationFoundListener.setOnLocationFoundListener(cityName, stateName, countryName);
}
private void showLocationSettingsDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(R.string.location_settings);
alertDialog.setMessage(R.string.location_settings_message);
alertDialog.setPositiveButton(R.string.location_settings_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public interface OnLocationFoundListener
{
void setOnLocationFoundListener(String cityName, String stateName, String countryName);
}
}
The MainActivity :
public class MainActivity extends AppCompatActivity implements LocationFinder.OnLocationFoundListener {
Button getCurrentLocation;
TextView locationTextview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getCurrentLocation = (Button) findViewById(R.id.getCurrentCity);
locationTextview = (TextView) findViewById(R.id.current_city);
LocationFinder locationFinder = new LocationFinder(getApplicationContext());
locationFinder.getCityByLocation();
}
#Override
public void setOnLocationFoundListener(String cityName, String stateName, String countryName) {
locationTextview.setText("City : "+cityName+", "+"\nState : "+stateName+", "+"\nCountry : "+countryName);
}
}
Logcat:
Process: com.amitupadhyay.citybasedlocation, PID: 18474
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.amitupadhyay.citybasedlocation/com.amitupadhyay.citybasedlocation.MainActivity}:
java.lang.ClassCastException: android.app.Application cannot be cast
to
com.amitupadhyay.citybasedlocation.LocationFinder$OnLocationFoundListener
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2456)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2523)
at android.app.ActivityThread.access$900(ActivityThread.java:168)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5609)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: java.lang.ClassCastException: android.app.Application
cannot be cast to
com.amitupadhyay.citybasedlocation.LocationFinder$OnLocationFoundListener
at
com.amitupadhyay.citybasedlocation.LocationFinder.(LocationFinder.java:38)
at
com.amitupadhyay.citybasedlocation.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:6307)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2523)
at android.app.ActivityThread.access$900(ActivityThread.java:168)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5609)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
I don't understand why is this happening?
try passing this as context instead of application context.
LocationFinder locationFinder = new LocationFinder(this);
locationFinder.getCityByLocation();
EDIT That is exactly what your logcat says. You are trying to pass a application context to activity.
Change it like following,
public LocationFinder(Context context, OnLocationFoundListener listener) {
this.context = context;
onLocationFoundListener = listener;
}
And from Activity, initiate it like this,
LocationFinder locationFinder = new LocationFinder(getApplicationContext(), this);
You Should Change OnLocationFoundListener Context parameter in constructor with OnLocationFoundListener
public LocationFinder(OnLocationFoundListener context) {
this.context = context;
onLocationFoundListener = context; // here is the exception is thrown
}
And You should pass
MainActvity.this.
LocationFinder locationFinder = new LocationFinder(MainActvity.this);
I want to insert into SQLite the location every 5 minutes, but the location is inserted every time it changes, I'm new with this, I know I have the insert inside the onlocationchange, but it's supposed to call every x time. I do not know what to do
public class GPS extends Service {
public static final int notify = 1000*60*5; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler();
private Timer mTimer = null;
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
if (mTimer != null)
mTimer.cancel();
else {
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);
}
locationMangaer = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver,LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
public class MyLocationListener implements LocationListener {
dbISMLock dbismlock = new dbISMLock(getBaseContext());
final SQLiteDatabase db =dbismlock.getWritableDatabase();
#Override
public void onLocationChanged(Location loc) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
Toast.makeText(getBaseContext(),"fecha: "+ currentDateandTime +"Location changed : Lat: " + loc.getLatitude()+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String phoneID = telephonyManager.getDeviceId();
//INSERT
db.execSQL("INSERT INTO GEOLOCATION( phoneId,Fecha,longitude, latitude) VALUES('"+phoneID+"','"+currentDateandTime+"','"+longitude+"','"+latitude+"')");
Log.d("insertamos "," geolocation" );
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel();
Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
}
class TimeDisplay extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(GPS.this, coordenadas(), Toast.LENGTH_SHORT).show();
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
locationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(GPS.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(GPS.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
} else {
Log.d("Gps Status!!", "Your GPS is: OFF");
}
}
});
}
}
}
You can use a Service to listen to location change in background and update it every 5 minutes. onLocationchange() is used to listen manually to changes. So you can ignore it for example and use the Service.
I am trying to implement a basic weather app for both android phone and wear. The application gets its data from an Web API then it displays it on the phone. Right now if the app is open on the Wear and then you open it on the Phone, it syncs the weather on both. And if you change the weather on the phone, it changes on the wear too. I want to make the wear app get the weather from the phone whenever you open the wear app, and I tried to implement this by making the wear "ping" the phone via a message and then the phone sends the info via a datamap. This works except the wear doesn't receive the datamap from the phone although the phone says it has sent the datamap.
Wear Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_map);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
sendMessage("Ping");
Log.i("OnLayoutInflated","LAYOUT INFLATED");
}
});
setAmbientEnabled();
// Register the local broadcast receiver
IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND);
MessageReceiver messageReceiver = new MessageReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, messageFilter);
}
#Override
protected void onPause() {
super.onPause();
if (wearCommsManager.isConnected()) {
wearCommsManager.disconnectClient();
}
}
#Override
protected void onResume() {
super.onResume();
if (wearCommsManager == null) {
wearCommsManager = new WearCommsManager(this);
}
if (messageSender == null) {
messageSender = new WearMessageSender(wearCommsManager);
}
verifyCommsConnection();
}
protected void sendMessage(final String message) {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {;
messageSender.processRequest(message);
return null;
}
};
task.execute();
}
private void verifyCommsConnection() {
new WearCommsManager(this).verifyCommsConnection(new WearCommsManager.CommsCallback() {
#Override
public void onSuccess() {
}
#Override
public void onFailure() {
Log.e("ERROR","CONNECTION FAILED");
}
});
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getBundleExtra("datamap");
// Display received data in UI
String display =
data.getString("city") + "\n" +
data.getString("temperature") + "\n" +
data.getString("wind_speed") + "\n" +
data.getString("cloud_percent")+"\n"+
data.getString("lastupdate");
mTextView.setText(display);
}
}
Wear Listener:
public class ListenerService extends WearableListenerService{
private static final String WEARABLE_DATA_PATH = "/wearable_data";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
DataMap dataMap;
for (DataEvent event : dataEvents) {
Log.v("myTag", "DataMap received on watch: " + DataMapItem.fromDataItem(event.getDataItem()).getDataMap());
// Check the data type
if (event.getType() == DataEvent.TYPE_CHANGED) {
// Check the data path
String path = event.getDataItem().getUri().getPath();
if (path.equals(WEARABLE_DATA_PATH)) {}
dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
// Broadcast DataMap contents to wearable activity for display
// The content has the golf hole number and distances to the front,
// middle and back pin placements.
Intent messageIntent = new Intent();
messageIntent.setAction(Intent.ACTION_SEND);
messageIntent.putExtra("datamap", dataMap.toBundle());
LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
}
}
}
}
Phone Main Activity:
public class DataMapActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private TextView cityName;
private TextView temp;
private ImageView iconView;
private TextView description;
private TextView humidity;
private TextView pressure;
private TextView wind;
private TextView sunrise;
private TextView sunset;
private TextView updated;
Weather weather = new Weather();
GoogleApiClient googleClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_map);
cityName = (TextView) findViewById(R.id.cityText);
iconView = (ImageView) findViewById(R.id.thumbnailIcon);
temp = (TextView) findViewById(R.id.tempText);
description = (TextView) findViewById(R.id.CloudText);
humidity = (TextView) findViewById(R.id.HumidText);
pressure = (TextView) findViewById(R.id.PressureText);
wind = (TextView) findViewById(R.id.WindText);
sunrise = (TextView) findViewById(R.id.RiseText);
sunset = (TextView) findViewById(R.id.SetText);
updated = (TextView) findViewById(R.id.UpdateText);
CityPreference cityPreference=new CityPreference(DataMapActivity.this);
System.out.println(cityPreference.getCity());
renderWeatherData(cityPreference.getCity());
IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND);
MessageReceiver messageReceiver = new MessageReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, messageFilter);
// Build a new GoogleApiClient for the the Wearable API
googleClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
public void renderWeatherData(String city) {
WeatherTask weatherTask = new WeatherTask();
weatherTask.execute(new String[]{city + "&units=metric"});
}
private class WeatherTask extends AsyncTask<String, Void, Weather> {
#Override
protected Weather doInBackground(String... params) {
String data = ((new WeatherHttpClient()).getWeatherData(params[0]));
System.out.println(data);
weather = JSONParser.getWeather(data);
return weather;
}
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if(weather.currentCondition.getIcon() != null){
new DownloadImageAsyncTask().execute(weather.currentCondition.getIcon());
}
cityName.setText(weather.place.getCity() + "," + weather.place.getCountry());
temp.setText("" + (int)weather.currentCondition.getTemperature() + "°C");
wind.setText("Wind Speed: " + weather.wind.getSpeed()+"m/s" + " Degree: " + weather.wind.getDegree());
description.setText("Clouds: " + weather.clouds.getPrecipitation() + "%, " + weather.currentCondition.getDescription());
pressure.setText("Pressure: " + weather.currentCondition.getPressure()+"hpa");
humidity.setText("Humidity: " + weather.currentCondition.getHumidity()+"%");
Date mydate = new Date(weather.place.getSunrise() * 1000);
SimpleDateFormat dateformat = new SimpleDateFormat("HH:mm");
dateformat.setTimeZone(TimeZone.getTimeZone("GMT+3"));
String date = dateformat.format(mydate);
sunrise.setText("Sunrise: " + date);
mydate = new Date(weather.place.getSunset() * 1000);
date = dateformat.format(mydate);
sunset.setText("Sunset: " + date);
mydate = new Date(weather.place.getLastupdate() * 1000);
dateformat = new SimpleDateFormat("dd.MM.yyyy, HH:mm, z");
dateformat.setTimeZone(TimeZone.getDefault());
date = dateformat.format(mydate);
updated.setText("Last Updated: " + date);
sendWear();
//This part synchronizes perfectly with wear
}
}
private void sendWear(){
String WEARABLE_DATA_PATH = "/wear_data";
// Create a DataMap object and send it to the data layer
DataMap dataMap = new DataMap();
dataMap.putString("lastupdate", updated.getText().toString());
dataMap.putString("city", cityName.getText().toString());
dataMap.putString("temperature", temp.getText().toString());
dataMap.putString("wind_speed", wind.getText().toString());
dataMap.putString("cloud_percent", description.getText().toString());
//Requires a new thread to avoid blocking the UI
new SendToDataLayerThread(WEARABLE_DATA_PATH, dataMap).start();
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String s= intent.getStringExtra("Pinger");
if(s!=null) {
new SendToWearAsyncTask().execute();
}
}
}
private class SendToWearAsyncTask extends AsyncTask<Void,Void,Void>{
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
sendWear();
//this part wear doesn't receive the datamap
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
}
Make sure that the applicationID were the same in the build.gradle for mobile and wear app. Also make sure that the buildTypes part and the signingConfigs part are the same in both apps. Source. You can also send Long.toString(System.currentTimeMillis()) to verify that as it changes every time.
I am using service in my application, the service works fine.but when ever i close the application (press home button) and open the application again multiple instance of the service is created.
What i want is,when i close the application the service must also close and when i resume the application the service must start.
but now it is creating two instance of the same service when i close and open the application.
Service
public class SignalRService extends Service {
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private Handler mHandler; // to display Toast message
private final LocalBinder mBinder = new LocalBinder();
public Boolean is_service_connected = false;
public String ProfileId;
public String profileToken;
public String CompanyID;
public String DisplayName;
private Context context;
public SignalRService() {
mHubConnection = new HubConnection("chatHub");
}
#Override
public void onCreate() {
super.onCreate();
Log.d("service", "Inside oncreate - service");
SharedPreferences prefs = getSharedPreferences("zupportdesk", MODE_PRIVATE);
ProfileId = prefs.getString("ProfileId", "Not defined");
profileToken = prefs.getString("profileToken", "Not defined");
CompanyID = prefs.getString("companyId", "Not defined");
DisplayName = prefs.getString("DisplayName", "Not defined");
mHandler = new Handler(Looper.getMainLooper());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("service", "service start - service");
int result = super.onStartCommand(intent, flags, startId);
startSignalR();
return result;
}
#Override
public void onDestroy() {
mHubConnection.stop();
super.onDestroy();
}
#Override
public boolean onUnbind(Intent intent) {
Log.d("Unbounding", "SignalRservice Service unbound");
return super.onUnbind(intent);
}
#Override
public IBinder onBind(Intent intent) {
// Return the communication channel to the service.
Log.d("service", "onBind - service");
startSignalR();
return (IBinder) mBinder;
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public SignalRService getService() {
// Return this instance of SignalRService so clients can call public methods
return SignalRService.this;
}
}
/**
* method for clients (activities)
*/
private void getIncommingcht(){
Log.d("Inside : ", "getIncommingcht - service - Method");
mHubProxy.invoke("addOperatorsToGroup", ProfileId, CompanyID, "true", profileToken);
mHubProxy.invoke("GetIncomingChatQueue",ProfileId, profileToken);
// mHubProxy.invoke("getselectedVisitors", ProfileId, CompanyID, profileToken);
mHubProxy.invoke("getOtherActiveChat", ProfileId, CompanyID, profileToken);
}
public void select_Active_Visitor(String visitor_id, String ProfileId, String CompanyID, String DisplayName, String profileToken, String startTime){
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
mHubProxy.invoke("selectVisitor", visitor_id, ProfileId, CompanyID, DisplayName, timeStamp, profileToken, startTime);
}
private void startSignalR() {
// Create a new console logger
Logger logger = new Logger() {
#Override
public void log(String message, LogLevel level) {
Log.d("Log Message : ", message);
}
};
// Connect to the server
HubConnection conn = new HubConnection("https://MY URL/", "", true, logger);
// Create the hub proxy
HubProxy proxy = conn.createHubProxy("chatHub");
mHubProxy = proxy;
Subscription subscription = proxy.subscribe("getVisitorResponse");
subscription.addReceivedHandler(new Action<JsonElement[]>(){
public void run(JsonElement[] eventParameters) throws Exception {
Log.d("getVisitorResponse-data", String.valueOf(eventParameters[0]));
Log.d("getVisitorResponse-time", String.valueOf(eventParameters[1]));
IncommingFragment.getVisitorResponse(eventParameters[0]);
}
});
Subscription subscription1 = proxy.subscribe("recieveIncomingChat");
subscription1.addReceivedHandler(new Action<JsonElement[]>(){
public void run(JsonElement[] eventParameters) throws Exception {
Log.d("IncomingChat_data", String.valueOf(eventParameters[0]));
IncommingFragment.receivedincommingchats(eventParameters[0]);
}
});
Subscription subscription3 = proxy.subscribe("getOtherActiveChats");
subscription3.addReceivedHandler(new Action<JsonElement[]>(){
public void run(JsonElement[] eventParameters) throws Exception {
Log.d("getOtherChats - data", String.valueOf(eventParameters[0]));
OtherFragment.getOtherActiveChats(eventParameters[0]);
}
});
Subscription subscription4 = proxy.subscribe("removeChatQueue");
subscription4.addReceivedHandler(new Action<JsonElement[]>(){
public void run(JsonElement[] eventParameters) throws Exception {
Log.d("removeChatQueue - data", String.valueOf(eventParameters[0]));
IncommingFragment.removeVisitor(String.valueOf(eventParameters[0]));
}
});
Subscription subscription6 = proxy.subscribe("StartTransfer");
subscription6.addReceivedHandler(new Action<JsonElement[]>(){
public void run(JsonElement[] eventParameters) throws Exception {
Log.d("Transfer_visitorID", String.valueOf(eventParameters[0]));
Log.d("Transfer_receivername", String.valueOf(eventParameters[1]));
Log.d("Transfer_receiverID", String.valueOf(eventParameters[2]));
}
});
/*proxy.subscribe(new Object() {
#SuppressWarnings("unused")
public void recieveIncomingChat(RecieveIncomingchats recieveIncomingchats) {
MainFragment.receivedincommingchats(recieveIncomingchats);
Log.d("hit:", "Hit on receive Incoming chats");
}
#SuppressWarnings("unused")
public void serviceStatus(boolean temp){
Log.d("service_status", "status called");
}
});*/
// Subscribe to the error event
conn.error(new ErrorCallback() {
#Override
public void onError(Throwable error) {
error.printStackTrace();
}
});
// Subscribe to the connected event
conn.connected(new Runnable() {
#Override
public void run() {
System.out.println("CONNECTED");
is_service_connected = true;
getIncommingcht();
}
});
// Subscribe to the closed event
conn.closed(new Runnable() {
#Override
public void run() {
System.out.println("DISCONNECTED");
}
});
// Start the connection
conn.start().done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
System.out.println("Done Connecting!");
}
});
// Subscribe to the received event
conn.received(new MessageReceivedHandler() {
#Override
public void onMessageReceived(JsonElement json) {
System.out.println("RAW received message: " + json.toString());
}
});
}
}
Activity
public class ChatsTab extends AppCompatActivity {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
ProgressDialog pDialog;
private TabLayout tabLayout;
private ViewPager viewPager;
public static SignalRService mService = new SignalRService();
private boolean mBound;
private HelpLiveo mHelpLiveo;
private ApplicationEnvironmentURL applicationEnvironment;
public static String ProfileId;
public static String profileToken;
public static String CompanyID;
public String DisplayName;
private Context context;
public String BASEURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chats_tab);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
applicationEnvironment = new ApplicationEnvironmentURL(this.context);
context = this.getApplicationContext();
SharedPreferences prefs = getSharedPreferences("zupportdesk", MODE_PRIVATE);
ProfileId = prefs.getString("ProfileId", "Not defined");
profileToken = prefs.getString("profileToken", "Not defined");
CompanyID = prefs.getString("companyId", "Not defined");
DisplayName = prefs.getString("DisplayName", "Not defined");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
if(!isMyServiceRunning(SignalRService.class)) {
Intent intent = new Intent();
intent.setClass(this, SignalRService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
setCannedResponsesURL(ProfileId, CompanyID);
new getAllcannedResponse().execute(profileToken);
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id){
case R.id.home:
Toast.makeText(getApplicationContext(),"Home",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.settings:
Intent intent_settings = new Intent(getApplication(), Settings.class);
startActivity(intent_settings);
break;
case R.id.canned_responses:
Intent intent2 = new Intent(getApplication(), CannedResponses.class);
startActivity(intent2);
// Toast.makeText(getApplicationContext(),"canned responses",Toast.LENGTH_SHORT).show();
break;
case R.id.Operators:
Intent intent = new Intent(getApplication(), Operators.class);
startActivity(intent);
drawerLayout.closeDrawers();
break;
case R.id.logout:
finish();
}
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView)header.findViewById(R.id.tv_email);
tv_email.setText(DisplayName);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new IncommingFragment(), "Incoming");
adapter.addFragment(new ActiveFragment(), "Active");
adapter.addFragment(new OtherFragment(), "Other");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
/********************************* Service Methods ********************************************/
private final ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d("Activity : ", "Inside service connected - Activity ");
// We've bound to SignalRService, cast the IBinder and get SignalRService instance
SignalRService.LocalBinder binder = (SignalRService.LocalBinder) service;
mService = binder.getService();
mBound = true;
Log.d("Activity : ", "bound status - " + mBound);
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mService=null;
mBound = false;
Log.d("Activity : ", "bound disconnected - status - " + mBound);
}
};
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
Log.d("Activity : ", "bound disconnecting - status - " + mBound);
}
mService.onDestroy();
}
/**********************************************************************************************/
}
In your Main activity create a method
private boolean isMyServiceRunning(Class<?> SignalRService) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (SignalRService.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
and make a check in Main Activity oncreate method
if(isMyServiceRunning(SignalRService.class)== true){
// do nothing
}else{
// Start your service
}
Hope it will solve your problem.