Send real data from service && a little refactor

This commit is contained in:
Mieszko Wrzeszczyński 2018-09-30 22:56:53 +02:00
parent 35af6aa70e
commit 136806adfd
12 changed files with 29 additions and 611 deletions

View File

@ -54,7 +54,7 @@
</activity>
<service
android:name=".service.GoogleService"/>
android:name=".service.BackgroundLocalizationService"/>
</application>

View File

@ -211,7 +211,7 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password,loginOption);
mAuthTask = new UserLoginTask(email, password, loginOption);
mAuthTask.execute((Void) null);
}
}
@ -354,10 +354,10 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
@Override
public void onSuccess(JwtToken jwtToken) {
String token = jwtToken.getToken();
JWT jwt = new JWT(token);
Claim role = jwt.getClaim("nameid");
Log.e("user",role.asString());
PrefUtils.storeApiKey(getApplicationContext(), token);
PrefUtils.storeUserId(getApplicationContext(), role.asString());

View File

@ -6,24 +6,17 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.uam.wmi.findmytutor.model.Coordinate;
import com.uam.wmi.findmytutor.model.LdapUser;
import com.uam.wmi.findmytutor.network.ApiClient;
import com.uam.wmi.findmytutor.service.CoordinateService;
import com.uam.wmi.findmytutor.service.GoogleService;
import com.uam.wmi.findmytutor.service.BackgroundLocalizationService;
import android.support.design.widget.FloatingActionButton;
import android.app.Fragment;
@ -35,24 +28,9 @@ import android.view.MenuItem;
import com.mapbox.mapboxsdk.Mapbox;
import com.uam.wmi.findmytutor.R;
import com.uam.wmi.findmytutor.service.LdapService;
import com.uam.wmi.findmytutor.service.LocationService;
import com.uam.wmi.findmytutor.utils.BroadcastLocalizationHandler;
import com.uam.wmi.findmytutor.utils.PrefUtils;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import java.io.IOException;
import java.util.List;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;
public class MainActivity extends AppCompatActivity {
private BottomNavigationView mMainNav;
@ -63,18 +41,11 @@ public class MainActivity extends AppCompatActivity {
private ProfileFragment profileFragment;
public static Intent backgroundLocalizationService = null;
;
private BroadcastReceiver broadcastReceiver = null;
private static final int REQUEST_PERMISSIONS = 100;
private boolean boolean_permission = false;
Double latitude, longitude;
/* CompositeDisposable disposable = new CompositeDisposable();
CoordinateService coordinateService = ApiClient.getClient(getApplicationContext())
.create(CoordinateService.class);*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -140,12 +111,7 @@ public class MainActivity extends AppCompatActivity {
fn_permission();
this.broadcastReceiver = new BroadcastLocalizationHandler();
}
private void setFragment(Fragment fragment) {
@ -159,19 +125,17 @@ public class MainActivity extends AppCompatActivity {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
if (boolean_permission) {
if (!PrefUtils.getIsServiceRunning(getApplicationContext())) {
Intent intent = new Intent(getApplicationContext(), GoogleService.class);
Intent intent = new Intent(getApplicationContext(), BackgroundLocalizationService.class);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
@ -181,9 +145,6 @@ public class MainActivity extends AppCompatActivity {
}
}
}
@Override
@ -205,7 +166,7 @@ public class MainActivity extends AppCompatActivity {
@Override
protected void onResume() {
super.onResume();
registerReceiver(this.broadcastReceiver, new IntentFilter(GoogleService.str_receiver));
registerReceiver(this.broadcastReceiver, new IntentFilter(BackgroundLocalizationService.str_receiver));
}
@Override

View File

@ -44,7 +44,6 @@ public class Coordinate extends BaseResponse {
this.longitude = longitude;
this.userId = userId;
this.label = label;
}
public Coordinate (Double latitude) {

View File

@ -2,7 +2,6 @@ package com.uam.wmi.findmytutor.service;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
@ -13,12 +12,8 @@ import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.uam.wmi.findmytutor.utils.PrefUtils;
import java.util.Timer;
import java.util.TimerTask;
@ -26,7 +21,7 @@ import java.util.TimerTask;
* Created by deepshikha on 24/11/16.
*/
public class GoogleService extends Service implements LocationListener{
public class BackgroundLocalizationService extends Service implements LocationListener{
boolean isGPSEnable = false;
@ -41,7 +36,7 @@ public class GoogleService extends Service implements LocationListener{
Intent intent;
public GoogleService() {}
public BackgroundLocalizationService() {}
@Nullable
@Override
@ -60,7 +55,7 @@ public class GoogleService extends Service implements LocationListener{
@Override
public void onLocationChanged(Location location) {
fn_getlocation();
}
@Override
@ -142,7 +137,7 @@ public class GoogleService extends Service implements LocationListener{
private class TimerTaskToGetLocation extends TimerTask{
@Override
public void run() {
mHandler.post(GoogleService.this::fn_getlocation);
mHandler.post(BackgroundLocalizationService.this::fn_getlocation);
}
}

View File

@ -23,47 +23,32 @@ import retrofit2.http.Path;
public interface CoordinateService {
@GET("api/coordinates")
Call<List<Coordinate>> getAllCoordinates();
Single<List<Coordinate>> getAllCoordinates();
@GET("api/coordinates/{id}")
Call<Coordinate> getCoordinatesById(@Path("id") String id);
Single<Coordinate> getCoordinatesById(@Path("id") String id);
@GET("api/coordinates/user/{userId}")
Call<List<Coordinate>> getCoordinatesByUserId(@Path("userId") String userId);
Single<List<Coordinate>> getCoordinatesByUserId(@Path("userId") String userId);
@GET("api/coordinates/userTop/{userId}")
Call<List<Coordinate>> getTopCoordinatesByUserId(@Path("userId") String userId);
Single<List<Coordinate>> getTopCoordinatesByUserId(@Path("userId") String userId);
@GET("api/coordinates/top")
Call<List<Coordinate>> getTopCoordinates();
Single<List<Coordinate>> getTopCoordinates();
@GET("api/coordinates/top/online")
Call<List<Coordinate>> getOnlineCoordinates();
/*
//works
@POST("api/coordinates")
Call <ResponseBody> postCoordinate(@Body RequestBody Coordinate);
*/
Single<List<Coordinate>> getOnlineCoordinates();
//works
@POST("api/coordinates")
Single <Coordinate> postCoordinate(@Body Coordinate coordinate);
/*
// Create note
@FormUrlEncoded
@POST("api/coordinates")
Observable <Coordinate> postCoordinate(@Field("latitude") Double latitude);
*/
@PUT("api/coordinates/{id}")
Call<Coordinate> putCoordinatesById(@Path("id") String id);
Single<Coordinate> putCoordinatesById(@Path("id") String id);
@DELETE("api/coordinates/{id}")
Call<Coordinate> deleteCoordinatesById(@Path("id") String id);
Single<Coordinate> deleteCoordinatesById(@Path("id") String id);
}

View File

@ -1,39 +0,0 @@
package com.uam.wmi.findmytutor.service;
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.preference.PreferenceManager;
public class LocationRequestHelper {
public final static String KEY_LOCATION_UPDATES_REQUESTED = "location-updates-requested";
public static void setRequesting(Context context, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(KEY_LOCATION_UPDATES_REQUESTED, value)
.apply();
}
public static boolean getRequesting(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_LOCATION_UPDATES_REQUESTED, false);
}
}

View File

@ -1,158 +0,0 @@
package com.uam.wmi.findmytutor.service;
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.app.NotificationChannel;
import com.uam.wmi.findmytutor.R;
import com.uam.wmi.findmytutor.activity.MainActivity;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
/**
* Class to process location results.
*/
public class LocationResultHelper {
public final static String KEY_LOCATION_UPDATES_RESULT = "location-update-result";
final private static String PRIMARY_CHANNEL = "default";
private Context mContext;
private List<Location> mLocations;
private NotificationManager mNotificationManager;
@RequiresApi(api = Build.VERSION_CODES.O)
LocationResultHelper(Context context, List<Location> locations) {
mContext = context;
mLocations = locations;
NotificationChannel channel = new NotificationChannel(PRIMARY_CHANNEL,
context.getString(R.string.default_channel), NotificationManager.IMPORTANCE_DEFAULT);
channel.setLightColor(Color.GREEN);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
getNotificationManager().createNotificationChannel(channel);
}
/**
* Returns the title for reporting about a list of {@link Location} objects.
*/
private String getLocationResultTitle() {
String numLocationsReported = mContext.getResources().getQuantityString(
R.plurals.num_locations_reported, mLocations.size(), mLocations.size());
return numLocationsReported + ": " + DateFormat.getDateTimeInstance().format(new Date());
}
private String getLocationResultText() {
if (mLocations.isEmpty()) {
return mContext.getString(R.string.unknown_location);
}
StringBuilder sb = new StringBuilder();
for (Location location : mLocations) {
sb.append("(");
sb.append(location.getLatitude());
sb.append(", ");
sb.append(location.getLongitude());
sb.append(")");
sb.append("\n");
}
return sb.toString();
}
/**
* Saves location result as a string to {@link android.content.SharedPreferences}.
*/
void saveResults() {
PreferenceManager.getDefaultSharedPreferences(mContext)
.edit()
.putString(KEY_LOCATION_UPDATES_RESULT, getLocationResultTitle() + "\n" +
getLocationResultText())
.apply();
}
/**
* Fetches location results from {@link android.content.SharedPreferences}.
*/
public static String getSavedLocationResult(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(KEY_LOCATION_UPDATES_RESULT, "");
}
/**
* Get the notification mNotificationManager.
* <p>
* Utility method as this helper works with it a lot.
*
* @return The system service NotificationManager
*/
private NotificationManager getNotificationManager() {
if (mNotificationManager == null) {
mNotificationManager = (NotificationManager) mContext.getSystemService(
Context.NOTIFICATION_SERVICE);
}
return mNotificationManager;
}
/**
* Displays a notification with the location results.
*/
void showNotification() {
Intent notificationIntent = new Intent(mContext, MainActivity.class);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(MainActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder notificationBuilder = null;
notificationBuilder = new Notification.Builder(mContext,
PRIMARY_CHANNEL)
.setContentTitle(getLocationResultTitle())
.setContentText(getLocationResultText())
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentIntent(notificationPendingIntent);
getNotificationManager().notify(0, notificationBuilder.build());
}
}

View File

@ -1,173 +0,0 @@
package com.uam.wmi.findmytutor.service;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
public class LocationService extends Service {
public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
Intent intent;
int counter = 0;
@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public void onDestroy() {
// handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
Log.v("STOP_SERVICE", "DONE");
locationManager.removeUpdates((LocationListener) listener);
}
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
@Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(final Location loc)
{
Log.i("*******", "Location changed");
if(isBetterLocation(loc, previousBestLocation)) {
loc.getLatitude();
loc.getLongitude();
Log.e("service", String.valueOf(loc));
intent.putExtra("Latitude", loc.getLatitude());
intent.putExtra("Longitude", loc.getLongitude());
intent.putExtra("Provider", loc.getProvider());
sendBroadcast(intent);
}
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}

View File

@ -41,11 +41,6 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent intent) {
Double latitude, longitude;
latitude = intent.getDoubleExtra("latitude", 0);
Log.e("Background service", String.valueOf(latitude));
final PendingResult pendingResult = goAsync();
Task asyncTask = new Task(pendingResult, intent);
asyncTask.execute();
@ -55,24 +50,31 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
private final PendingResult pendingResult;
private final Intent intent;
private Double latitude;
private Double longitude;
private CompositeDisposable disposable = new CompositeDisposable();
private CoordinateService coordinateService = ApiClient.getClient(getApplicationContext())
.create(CoordinateService .class);
.create(CoordinateService.class);
private Task(PendingResult pendingResult, Intent intent) {
this.pendingResult = pendingResult;
this.intent = intent;
this.latitude = intent.getDoubleExtra("latitude", 0);
this.longitude = intent.getDoubleExtra("longitude", 0);
}
@Override
protected Object doInBackground(Object[] objects) {
//Here you can obtain value from receiver
Log.e("task", String.valueOf(this.latitude));
Coordinate coordinate = new Coordinate(52.467099,16.927560, "android",PrefUtils.getUserId(getApplicationContext()));
Coordinate coordinate = new Coordinate(
this.latitude,
this.longitude,
"android",
PrefUtils.getUserId(getApplicationContext())
);
disposable.add(
coordinateService
@ -95,8 +97,6 @@ public class BroadcastLocalizationHandler extends BroadcastReceiver {
return null;
}
}
}

View File

@ -1,98 +0,0 @@
package com.uam.wmi.findmytutor.utils;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
public class MyDividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mOrientation;
private Context context;
private int margin;
public MyDividerItemDecoration(Context context, int orientation, int margin) {
this.context = context;
this.margin = margin;
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left + dpToPx(margin), top, right - dpToPx(margin), bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top + dpToPx(margin), right, bottom - dpToPx(margin));
mDivider.draw(c);
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
private int dpToPx(int dp) {
Resources r = context.getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
}

View File

@ -1,54 +0,0 @@
package com.uam.wmi.findmytutor.utils;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private ClickListener clicklistener;
private GestureDetector gestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener) {
this.clicklistener = clicklistener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recycleView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clicklistener != null) {
clicklistener.onLongClick(child, recycleView.getChildAdapterPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clicklistener != null && gestureDetector.onTouchEvent(e)) {
clicklistener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}