Skip to content

Commit

Permalink
Merge pull request #192 from WatchFriends/syncadapter
Browse files Browse the repository at this point in the history
Search keyboard close fix + Syncadapter beginning
  • Loading branch information
nielsbril authored Jan 26, 2017
2 parents aa5141d + ab89d16 commit 48b5332
Show file tree
Hide file tree
Showing 7 changed files with 203 additions and 13 deletions.
17 changes: 15 additions & 2 deletions WatchFriends/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />

<application
android:allowBackup="true"
Expand Down Expand Up @@ -76,6 +77,18 @@
android:resource="@xml/account_authenticator" />
</service>

<service
android:name="nmct.jaspernielsmichielhein.watchfriends.sync.SyncService"
android:exported="true"
android:process=":sync">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="@xml/syncadapter" />
</service>

<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
Expand All @@ -87,7 +100,7 @@
<provider
android:name=".provider.FollowedSeriesProvider"
android:authorities="nmct.jaspernielsmichielhein.watchfriends.followedseries"
android:exported="true" />
android:exported="false" />
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
package nmct.jaspernielsmichielhein.watchfriends.api;

import android.databinding.ObservableArrayList;

import com.android.annotations.Nullable;
import com.google.gson.JsonObject;

import java.util.ArrayList;
Expand All @@ -24,8 +21,8 @@
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.PUT;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Observable;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,16 @@
import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.audiofx.AcousticEchoCanceler;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.facebook.login.LoginManager;

import java.util.concurrent.TimeUnit;

public class AuthHelper {

private static String mToken = "";
Expand All @@ -41,6 +36,21 @@ public static String getEmail(Context context) {
}
}

public static Account getAccount(Context context) {
mAccountManager = AccountManager.get(context);

if (ActivityCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
return null;
}
Account[] accounts = mAccountManager.getAccountsByType(Contract.ACCOUNT_TYPE);

if (accounts.length > 0) {
return accounts[0];
} else {
return null;
}
}

public static String getAuthToken(Context context) {
if (mToken.equals("")) {
mAccountManager = AccountManager.get(context);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package nmct.jaspernielsmichielhein.watchfriends.sync;

import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
import android.util.Log;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import nmct.jaspernielsmichielhein.watchfriends.helper.ApiHelper;
import nmct.jaspernielsmichielhein.watchfriends.helper.ApiWatchFriendsHelper;
import nmct.jaspernielsmichielhein.watchfriends.helper.AuthHelper;
import nmct.jaspernielsmichielhein.watchfriends.model.Series;
import nmct.jaspernielsmichielhein.watchfriends.model.UserData;
import nmct.jaspernielsmichielhein.watchfriends.provider.Contract;
import rx.functions.Action1;

public class SyncAdapter extends AbstractThreadedSyncAdapter {

private ContentResolver contentResolver;
private SyncResult syncResult;

public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
this.contentResolver = context.getContentResolver();
}

public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
this.contentResolver = context.getContentResolver();
}

@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
try {
this.syncResult = syncResult;
syncWatched(account);
} catch (Exception ex) {
ex.printStackTrace();
}
}

private void syncWatched(Account account) {
Log.d("SyncAdapter", "Syncing");
try {
final List<Series> followingSeries = new ArrayList<>();

ApiHelper.subscribe(ApiWatchFriendsHelper.getWatchFriendsServiceInstance().getUser(null, AuthHelper.getAuthToken(this.getContext())), new Action1<UserData>() {
@Override
public void call(UserData userData) {
if (userData != null) {
followingSeries.addAll(userData.getWatchlist());
updateFollowingSeries(followingSeries);
}
}
});

} catch (Exception ex) {
ex.printStackTrace();
syncResult.stats.numIoExceptions++;
throw ex;
}
}

private void updateFollowingSeries(List<Series> followingSeries) {
ArrayList<ContentProviderOperation> operationList = new ArrayList<>();

//lokale followings verwijderen
ContentProviderOperation delete = ContentProviderOperation.newDelete(Contract.FOLLOWEDSERIES_URI).build();
operationList.add(delete);
syncResult.stats.numDeletes++;

//alle followings lokaal toevoegen
for (Series s : followingSeries) {
ContentValues values = seriesToContentValuesList(s);
ContentProviderOperation insert = ContentProviderOperation.newInsert(Contract.FOLLOWEDSERIES_URI).withValues(values).build();
operationList.add(insert);
syncResult.stats.numInserts++;
}

if (operationList.size() > 0) {
try {
contentResolver.applyBatch(Contract.AUTHORITY, operationList);
contentResolver.notifyChange(Contract.FOLLOWEDSERIES_URI, null, false);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

private ContentValues seriesToContentValuesList(Series s) {
String[] columns = new String[]{
nmct.jaspernielsmichielhein.watchfriends.database.Contract.FollowedSeriesColumns.COLUMN_FOLLOWEDSERIES_NR,
nmct.jaspernielsmichielhein.watchfriends.database.Contract.FollowedSeriesColumns.COLUMN_FOLLOWEDSERIES_FOLLOWING
};
Object[] columnValues = new Object[]{s.getId(), s.getFollowing()};

ContentValues values = new ContentValues();
int counter = 0;
for (String column : columns) {
Type type = columnValues[counter].getClass();

if (type == String.class) {
values.put(column, (String) columnValues[counter]);
} else if (type == Integer.class) {
values.put(column, (Integer) columnValues[counter]);
} else if (type == Boolean.class) {
values.put(column, (Boolean) columnValues[counter]);
} else if (type == Double.class) {
values.put(column, (Double) columnValues[counter]);
}

counter++;
}
return values;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package nmct.jaspernielsmichielhein.watchfriends.sync;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

public class SyncService extends Service {

private static final Object syncAdapterLock = new Object();
private static SyncAdapter syncAdapter = null;

@Override
public void onCreate() {
synchronized (syncAdapterLock) {
if (syncAdapter == null) {
syncAdapter = new SyncAdapter(getApplicationContext(), true);
}
}
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return syncAdapter.getSyncAdapterBinder();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
Expand Down Expand Up @@ -126,7 +127,7 @@ public void onClick(View v) {
appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);

Stetho.initializeWithDefaults(this);
if(savedInstanceState == null){ //started the app
if (savedInstanceState == null) { //started the app
navigate(HomeFragment.newInstance(), "homeFragment");
}
}
Expand All @@ -138,6 +139,13 @@ protected void onStart() {
AuthHelper.logUserOff(this);
LoginManager.getInstance().logOut();
showLoginActivity();
} else {
if (AuthHelper.getAccount(getApplicationContext()) != null) {
Bundle settingsBundle = new Bundle();
settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
ContentResolver.requestSync(AuthHelper.getAccount(getApplicationContext()), nmct.jaspernielsmichielhein.watchfriends.provider.Contract.AUTHORITY, settingsBundle);
}
}
}

Expand Down Expand Up @@ -322,6 +330,7 @@ private void navigate(Fragment fragment, String tag) {
public boolean onQueryTextSubmit(String query) {
//search button press
navigate(SearchFragment.newInstance(query), "searchFragment");
searchView.clearFocus();
return false;
}

Expand Down Expand Up @@ -354,5 +363,4 @@ public void onEpisodeSelected(Episode episode, int seriesId) {
public void onProfileSelected(String userId) {
navigate(ProfileFragment.newInstance(), "profileFragment");
}

}
9 changes: 9 additions & 0 deletions WatchFriends/app/src/main/res/xml/syncadapter.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<sync-adapter
xmlns:android="http://schemas.android.com/apk/res/android"
android:contentAuthority="nmct.jaspernielsmichielhein.watchfriends"
android:accountType="nmct.jaspernielsmichielhein.watchfriends.account"
android:userVisible="true"
android:supportsUploading="false"
android:allowParallelSyncs="false"
android:isAlwaysSyncable="true" />

0 comments on commit 48b5332

Please sign in to comment.