From f3f4386319911ab7791b247edfcc1942d85fdaad Mon Sep 17 00:00:00 2001 From: Rashiq Date: Wed, 5 Apr 2017 11:28:03 +0200 Subject: [PATCH 1/2] Reindent --- .../kiwix/kiwixmobile/LibraryFragment.java | 68 ++++++++++--------- 1 file changed, 35 insertions(+), 33 deletions(-) diff --git a/src/org/kiwix/kiwixmobile/LibraryFragment.java b/src/org/kiwix/kiwixmobile/LibraryFragment.java index 69baea42d..676ea78db 100644 --- a/src/org/kiwix/kiwixmobile/LibraryFragment.java +++ b/src/org/kiwix/kiwixmobile/LibraryFragment.java @@ -96,43 +96,45 @@ public class LibraryFragment extends Fragment implements AdapterView.OnItemClick public static boolean isReceiverRegistered = false; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - faActivity = (ZimManageActivity) super.getActivity(); - // Replace LinearLayout by the type of the root element of the layout you're trying to load - llLayout = (LinearLayout) inflater.inflate(R.layout.activity_library, container, false); - // Of course you will want to faActivity and llLayout in the class and not this method to access them in the rest of - // the class, just initialize them here + @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { - // Don't use this method, it's handled by inflater.inflate() above : - // setContentView(R.layout.activity_layout); - ButterKnife.bind(this, llLayout); - DownloadService.setDownloadFragment(faActivity.mSectionsPagerAdapter.getDownloadFragment()); - kiwixService = ((KiwixApplication) super.getActivity().getApplication()).getKiwixService(); - conMan = (ConnectivityManager) super.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo network = conMan.getActiveNetworkInfo(); - if (network == null || !network.isConnected()) { - noNetworkConnection(); - } + faActivity = (ZimManageActivity) super.getActivity(); + // Replace LinearLayout by the type of the root element of the layout you're trying to load + llLayout = (LinearLayout) inflater.inflate(R.layout.activity_library, container, false); + // Of course you will want to faActivity and llLayout in the class and not this method to access them in the rest of + // the class, just initialize them here - networkBroadcastReceiver = new NetworkBroadcastReceiver(); - faActivity.registerReceiver(networkBroadcastReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); - isReceiverRegistered = true; - - BookDao bookDao = new BookDao(KiwixDatabase.getInstance(getActivity())); - for (Book book : bookDao.getDownloadingBooks()) { - if (!DownloadFragment.mDownloads.containsValue(book)) { - book.url = book.remoteUrl; - downloadFile(book); - } - } - // The FragmentActivity doesn't contain the layout directly so we must use our instance of LinearLayout : - //llLayout.findViewById(R.id.someGuiElement); - // Instead of : - // findViewById(R.id.someGuiElement); - return llLayout; // We must return the loaded Layout + // Don't use this method, it's handled by inflater.inflate() above : + // setContentView(R.layout.activity_layout); + ButterKnife.bind(this, llLayout); + DownloadService.setDownloadFragment(faActivity.mSectionsPagerAdapter.getDownloadFragment()); + kiwixService = ((KiwixApplication) super.getActivity().getApplication()).getKiwixService(); + conMan = + (ConnectivityManager) super.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo network = conMan.getActiveNetworkInfo(); + if (network == null || !network.isConnected()) { + noNetworkConnection(); } + networkBroadcastReceiver = new NetworkBroadcastReceiver(); + faActivity.registerReceiver(networkBroadcastReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); + isReceiverRegistered = true; + + BookDao bookDao = new BookDao(KiwixDatabase.getInstance(getActivity())); + for (Book book : bookDao.getDownloadingBooks()) { + if (!DownloadFragment.mDownloads.containsValue(book)) { + book.url = book.remoteUrl; + downloadFile(book); + } + } + // The FragmentActivity doesn't contain the layout directly so we must use our instance of LinearLayout : + //llLayout.findViewById(R.id.someGuiElement); + // Instead of : + // findViewById(R.id.someGuiElement); + return llLayout; // We must return the loaded Layout + } + public void getLibraryData(){ progressBar.setVisibility(View.VISIBLE); From 31e5a9f5c8e8c9087d295cd9f6a06d79634e40f1 Mon Sep 17 00:00:00 2001 From: Rashiq Date: Wed, 5 Apr 2017 11:45:56 +0200 Subject: [PATCH 2/2] Add dagger For now only OkHttp, Retrofit and the LocationManager are being supplied for dagger, but I will add more as I go --- build.gradle | 7 +- src/org/kiwix/kiwixmobile/BaseActivity.java | 49 ++++++++++++ .../kiwix/kiwixmobile/KiwixApplication.java | 40 ++++------ .../kiwixmobile/KiwixMobileActivity.java | 27 ++++--- .../kiwix/kiwixmobile/LibraryFragment.java | 77 ++++++++++--------- src/org/kiwix/kiwixmobile/di/PerActivity.java | 9 +++ .../di/components/ApplicationComponent.java | 22 ++++++ .../di/modules/ApplicationModule.java | 24 ++++++ .../kiwixmobile/di/modules/NetworkModule.java | 28 +++++++ .../downloader/DownloadService.java | 46 +++++------ 10 files changed, 231 insertions(+), 98 deletions(-) create mode 100644 src/org/kiwix/kiwixmobile/BaseActivity.java create mode 100644 src/org/kiwix/kiwixmobile/di/PerActivity.java create mode 100644 src/org/kiwix/kiwixmobile/di/components/ApplicationComponent.java create mode 100644 src/org/kiwix/kiwixmobile/di/modules/ApplicationModule.java create mode 100644 src/org/kiwix/kiwixmobile/di/modules/NetworkModule.java diff --git a/build.gradle b/build.gradle index 5cfba51ae..324722108 100644 --- a/build.gradle +++ b/build.gradle @@ -28,11 +28,12 @@ dependencies { compile 'com.android.support:design:24.1.0' compile 'com.android.support:cardview-v7:24.1.0' - androidTestCompile 'com.android.support:support-annotations:24.1.0' androidTestCompile 'com.android.support.test:runner:0.5' androidTestCompile 'com.android.support.test:rules:0.5' + compile 'com.google.dagger:dagger:2.0.2' + apt "com.google.dagger:dagger-compiler:2.0.2" compile 'com.yahoo.squidb:squidb:2.0.0' compile 'com.yahoo.squidb:squidb-annotations:2.0.0' @@ -53,7 +54,7 @@ dependencies { compile 'eu.mhutti1.utils.storage:android-storage-devices:0.4.8' compile 'com.jakewharton:butterknife:8.0.1' apt 'com.jakewharton:butterknife-compiler:8.0.1' - + compile files("$buildDir/native-libs/native-libs.jar") compile group: 'com.google.guava', name: 'guava', version: '19.0' @@ -88,7 +89,7 @@ dependencies { dexOptions { javaMaxHeapSize "4g" } - + sourceSets { main { manifest.srcFile 'AndroidManifest.xml' diff --git a/src/org/kiwix/kiwixmobile/BaseActivity.java b/src/org/kiwix/kiwixmobile/BaseActivity.java new file mode 100644 index 000000000..61feaeb96 --- /dev/null +++ b/src/org/kiwix/kiwixmobile/BaseActivity.java @@ -0,0 +1,49 @@ +package org.kiwix.kiwixmobile; + +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.support.v7.app.AppCompatActivity; +import org.kiwix.kiwixmobile.di.components.ApplicationComponent; + +public abstract class BaseActivity extends AppCompatActivity { + + + @Override protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setupDagger(KiwixApplication.getInstance().getApplicationComponent()); + //attachPresenter(); + } + + @Override protected void onStart() { + super.onStart(); + //presenter.onStart(); + } + + @Override protected void onResume() { + super.onResume(); + //presenter.onResume(); + } + + @Override protected void onPause() { + super.onPause(); + //presenter.onPause(); + } + + @Override protected void onStop() { + super.onStop(); + //presenter.onStop(); + } + + @Override protected void onDestroy() { + super.onDestroy(); + //presenter.onDestroy(); + } + + //protected void attachPresenter(Presenter presenter) { + // this.presenter = presenter; + //} + + protected abstract void setupDagger(ApplicationComponent appComponent); + + //public abstract void attachPresenter(); +} diff --git a/src/org/kiwix/kiwixmobile/KiwixApplication.java b/src/org/kiwix/kiwixmobile/KiwixApplication.java index e3cf803f6..2ebfd9819 100644 --- a/src/org/kiwix/kiwixmobile/KiwixApplication.java +++ b/src/org/kiwix/kiwixmobile/KiwixApplication.java @@ -1,40 +1,32 @@ package org.kiwix.kiwixmobile; import android.app.Application; -import okhttp3.OkHttpClient; -import org.kiwix.kiwixmobile.network.KiwixService; -import retrofit2.Retrofit; -import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; -import retrofit2.converter.simplexml.SimpleXmlConverterFactory; -import rx.schedulers.Schedulers; +import org.kiwix.kiwixmobile.di.components.ApplicationComponent; +import org.kiwix.kiwixmobile.di.components.DaggerApplicationComponent; +import org.kiwix.kiwixmobile.di.modules.ApplicationModule; public class KiwixApplication extends Application { - private static KiwixService service; - private static OkHttpClient client = new OkHttpClient().newBuilder().followRedirects(true).followSslRedirects(true).build(); + private static KiwixApplication application; + private ApplicationComponent applicationComponent; + + public static KiwixApplication getInstance() { + return application; + } @Override public void onCreate() { super.onCreate(); - createRetrofitService(); - + application = this; + initializeInjector(); } - private void createRetrofitService() { - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("http://download.kiwix.org/") - .client(client) - .addConverterFactory(SimpleXmlConverterFactory.create()) - .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) + private void initializeInjector() { + this.applicationComponent = DaggerApplicationComponent.builder() + .applicationModule(new ApplicationModule(this)) .build(); - - service = retrofit.create(KiwixService.class); } - public KiwixService getKiwixService() { - return service; - } - - public OkHttpClient getOkHttpClient() { - return client; + public ApplicationComponent getApplicationComponent() { + return this.applicationComponent; } } diff --git a/src/org/kiwix/kiwixmobile/KiwixMobileActivity.java b/src/org/kiwix/kiwixmobile/KiwixMobileActivity.java index 83683a957..7f66c6875 100644 --- a/src/org/kiwix/kiwixmobile/KiwixMobileActivity.java +++ b/src/org/kiwix/kiwixmobile/KiwixMobileActivity.java @@ -46,7 +46,6 @@ import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; -import android.support.v7.app.AppCompatActivity; import android.support.v7.view.menu.ActionMenuItemView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; @@ -74,10 +73,18 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; - +import butterknife.BindView; +import butterknife.ButterKnife; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import javax.inject.Inject; +import okhttp3.OkHttpClient; import org.json.JSONArray; import org.kiwix.kiwixmobile.database.BookmarksDao; import org.kiwix.kiwixmobile.database.KiwixDatabase; +import org.kiwix.kiwixmobile.di.components.ApplicationComponent; import org.kiwix.kiwixmobile.settings.Constants; import org.kiwix.kiwixmobile.settings.KiwixSettingsActivity; import org.kiwix.kiwixmobile.utils.DimenUtils; @@ -96,20 +103,12 @@ import org.kiwix.kiwixmobile.views.web.KiwixWebView; import org.kiwix.kiwixmobile.views.web.ToolbarScrollingKiwixWebView; import org.kiwix.kiwixmobile.views.web.ToolbarStaticKiwixWebView; -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import butterknife.BindView; -import butterknife.ButterKnife; - import static android.content.res.Configuration.ORIENTATION_LANDSCAPE; import static org.kiwix.kiwixmobile.TableDrawerAdapter.DocumentSection; import static org.kiwix.kiwixmobile.TableDrawerAdapter.TableClickListener; import static org.kiwix.kiwixmobile.utils.StyleUtils.dialogStyle; -public class KiwixMobileActivity extends AppCompatActivity implements WebViewCallback { +public class KiwixMobileActivity extends BaseActivity implements WebViewCallback { public static final int REQUEST_FILE_SEARCH = 1236; @@ -257,6 +256,8 @@ public class KiwixMobileActivity extends AppCompatActivity implements WebViewCal @BindView(R.id.action_forward) View tabForwardButtonContainer; + @Inject OkHttpClient okHttpClient; + @Override public void onActionModeStarted(ActionMode mode) { @@ -576,6 +577,10 @@ public class KiwixMobileActivity extends AppCompatActivity implements WebViewCal tts.shutdown(); } + @Override protected void setupDagger(ApplicationComponent appComponent) { + appComponent.inject(this); + } + private void updateTableOfContents() { getCurrentWebView().loadUrl("javascript:(" + documentParserJs + ")()"); } diff --git a/src/org/kiwix/kiwixmobile/LibraryFragment.java b/src/org/kiwix/kiwixmobile/LibraryFragment.java index 676ea78db..0a6fda06c 100644 --- a/src/org/kiwix/kiwixmobile/LibraryFragment.java +++ b/src/org/kiwix/kiwixmobile/LibraryFragment.java @@ -1,5 +1,6 @@ package org.kiwix.kiwixmobile; +import android.app.Fragment; import android.app.FragmentManager; import android.content.BroadcastReceiver; import android.content.ComponentName; @@ -18,8 +19,6 @@ import android.os.Environment; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.design.widget.Snackbar; -import android.app.Fragment; -import android.support.v4.view.GravityCompat; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; @@ -34,13 +33,15 @@ import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; +import eu.mhutti1.utils.storage.StorageDevice; +import eu.mhutti1.utils.storage.StorageSelectDialog; import java.io.File; import java.math.BigDecimal; import java.math.MathContext; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; - +import javax.inject.Inject; import org.kiwix.kiwixmobile.database.BookDao; import org.kiwix.kiwixmobile.database.KiwixDatabase; import org.kiwix.kiwixmobile.downloader.DownloadFragment; @@ -51,26 +52,23 @@ import org.kiwix.kiwixmobile.library.entity.LibraryNetworkEntity; import org.kiwix.kiwixmobile.network.KiwixService; import org.kiwix.kiwixmobile.utils.StorageUtils; import org.kiwix.kiwixmobile.utils.StyleUtils; - -import eu.mhutti1.utils.storage.StorageDevice; -import eu.mhutti1.utils.storage.StorageSelectDialog; import rx.android.schedulers.AndroidSchedulers; import static org.kiwix.kiwixmobile.downloader.DownloadService.KIWIX_ROOT; -import static org.kiwix.kiwixmobile.library.entity.LibraryNetworkEntity.*; +import static org.kiwix.kiwixmobile.library.entity.LibraryNetworkEntity.Book; import static org.kiwix.kiwixmobile.utils.StyleUtils.dialogStyle; -public class LibraryFragment extends Fragment implements AdapterView.OnItemClickListener, StorageSelectDialog.OnSelectListener { +public class LibraryFragment extends Fragment + implements AdapterView.OnItemClickListener, StorageSelectDialog.OnSelectListener { public @BindView(R.id.library_list) ListView libraryList; + public @BindView(R.id.progressbar_layout) RelativeLayout progressBarLayout; @BindView(R.id.progressBar) ProgressBar progressBar; @BindView(R.id.progressbar_message) TextView progressBarMessage; - public @BindView(R.id.progressbar_layout) RelativeLayout progressBarLayout; @BindView(R.id.network_permission_text) TextView permissionText; @BindView(R.id.network_permission_button) Button permissionButton; - - private KiwixService kiwixService; + @Inject KiwixService kiwixService; public LinearLayout llLayout; @@ -96,9 +94,15 @@ public class LibraryFragment extends Fragment implements AdapterView.OnItemClick public static boolean isReceiverRegistered = false; + private void setupDagger() { + KiwixApplication.getInstance().getApplicationComponent().inject(this); + } + @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + setupDagger(); + faActivity = (ZimManageActivity) super.getActivity(); // Replace LinearLayout by the type of the root element of the layout you're trying to load llLayout = (LinearLayout) inflater.inflate(R.layout.activity_library, container, false); @@ -109,7 +113,6 @@ public class LibraryFragment extends Fragment implements AdapterView.OnItemClick // setContentView(R.layout.activity_layout); ButterKnife.bind(this, llLayout); DownloadService.setDownloadFragment(faActivity.mSectionsPagerAdapter.getDownloadFragment()); - kiwixService = ((KiwixApplication) super.getActivity().getApplication()).getKiwixService(); conMan = (ConnectivityManager) super.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo network = conMan.getActiveNetworkInfo(); @@ -135,8 +138,7 @@ public class LibraryFragment extends Fragment implements AdapterView.OnItemClick return llLayout; // We must return the loaded Layout } - - public void getLibraryData(){ + public void getLibraryData() { progressBar.setVisibility(View.VISIBLE); progressBarMessage.setVisibility(View.VISIBLE); progressBarLayout.setVisibility(View.VISIBLE); @@ -150,17 +152,16 @@ public class LibraryFragment extends Fragment implements AdapterView.OnItemClick libraryAdapter = new LibraryAdapter(super.getActivity(), new ArrayList<>(books)); libraryList.setAdapter(libraryAdapter); } - },error -> { + }, error -> { noNetworkConnection(); }); - libraryList.setOnItemClickListener(this); active = true; } - public void displayNetworkConfirmation(){ + public void displayNetworkConfirmation() { progressBar.setVisibility(View.GONE); progressBarMessage.setVisibility(View.GONE); permissionText.setVisibility(View.VISIBLE); @@ -195,10 +196,11 @@ public class LibraryFragment extends Fragment implements AdapterView.OnItemClick @Override public void onItemClick(AdapterView parent, View view, int position, long id) { - if (getSpaceAvailable() < Long.parseLong(((Book) (parent.getAdapter().getItem(position))).getSize()) * 1024f) { + if (getSpaceAvailable() + < Long.parseLong(((Book) (parent.getAdapter().getItem(position))).getSize()) * 1024f) { Toast.makeText(super.getActivity(), getString(R.string.download_no_space) - + "\n" + getString(R.string.space_available) + " " - + bytesToHuman(getSpaceAvailable()), Toast.LENGTH_LONG).show(); + + "\n" + getString(R.string.space_available) + " " + + bytesToHuman(getSpaceAvailable()), Toast.LENGTH_LONG).show(); Snackbar snackbar = Snackbar.make(libraryList, getString(R.string.download_change_storage), Snackbar.LENGTH_LONG) @@ -219,25 +221,28 @@ public class LibraryFragment extends Fragment implements AdapterView.OnItemClick } if (DownloadFragment.mDownloadFiles - .containsValue(KIWIX_ROOT + StorageUtils.getFileNameFromUrl(((Book) parent.getAdapter().getItem(position)).getUrl()))) { - Toast.makeText(super.getActivity(), getString(R.string.zim_already_downloading), Toast.LENGTH_LONG).show(); + .containsValue(KIWIX_ROOT + StorageUtils.getFileNameFromUrl(((Book) parent.getAdapter() + .getItem(position)).getUrl()))) { + Toast.makeText(super.getActivity(), getString(R.string.zim_already_downloading), Toast.LENGTH_LONG) + .show(); } else { NetworkInfo network = conMan.getActiveNetworkInfo(); if (network == null || !network.isConnected()) { - Toast.makeText(super.getActivity(), getString(R.string.no_network_connection), Toast.LENGTH_LONG).show(); + Toast.makeText(super.getActivity(), getString(R.string.no_network_connection), Toast.LENGTH_LONG) + .show(); return; } if (isWiFi()) { downloadFile((Book) parent.getAdapter().getItem(position)); - } else{ - mobileDownloadDialog(position, parent); + } else { + mobileDownloadDialog(position, parent); + } } } - } - public boolean isWiFi(){ + public boolean isWiFi() { if (Build.VERSION.SDK_INT >= 23) { NetworkInfo network = conMan.getActiveNetworkInfo(); return network.getType() == ConnectivityManager.TYPE_WIFI; @@ -266,13 +271,12 @@ public class LibraryFragment extends Fragment implements AdapterView.OnItemClick return "???"; } - public static String round3SF(double size){ + public static String round3SF(double size) { BigDecimal bd = new BigDecimal(size); bd = bd.round(new MathContext(3)); return String.valueOf(bd.doubleValue()); } - public void mobileDownloadDialog(int position, AdapterView parent) { new AlertDialog.Builder(super.getActivity(), dialogStyle()) .setMessage(getString(R.string.download_over_network)) @@ -293,26 +297,30 @@ public class LibraryFragment extends Fragment implements AdapterView.OnItemClick if (libraryAdapter != null) { libraryAdapter.getFilter().filter(faActivity.searchView.getQuery()); } - Toast.makeText(super.getActivity(), getString(R.string.download_started_library), Toast.LENGTH_LONG).show(); + Toast.makeText(super.getActivity(), getString(R.string.download_started_library), Toast.LENGTH_LONG) + .show(); Intent service = new Intent(super.getActivity(), DownloadService.class); service.putExtra(DownloadIntent.DOWNLOAD_URL_PARAMETER, book.getUrl()); service.putExtra(DownloadIntent.DOWNLOAD_ZIM_TITLE, book.getTitle()); service.putExtra("Book", book); super.getActivity().startService(service); mConnection = new DownloadServiceConnection(); - super.getActivity().bindService(service, mConnection.downloadServiceInterface, Context.BIND_AUTO_CREATE); + super.getActivity() + .bindService(service, mConnection.downloadServiceInterface, Context.BIND_AUTO_CREATE); ZimManageActivity manage = (ZimManageActivity) super.getActivity(); manage.displayDownloadInterface(); } public long getSpaceAvailable() { return new File(PreferenceManager.getDefaultSharedPreferences(super.getActivity()) - .getString(KiwixMobileActivity.PREF_STORAGE,Environment.getExternalStorageDirectory().getPath())).getFreeSpace(); + .getString(KiwixMobileActivity.PREF_STORAGE, Environment.getExternalStorageDirectory() + .getPath())).getFreeSpace(); } @Override public void selectionCallback(StorageDevice storageDevice) { - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); + SharedPreferences sharedPreferences = + PreferenceManager.getDefaultSharedPreferences(getActivity()); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(KiwixMobileActivity.PREF_STORAGE, storageDevice.getName()); if (storageDevice.isInternal()) { @@ -346,10 +354,9 @@ public class LibraryFragment extends Fragment implements AdapterView.OnItemClick bound = false; } } - } - public class NetworkBroadcastReceiver extends BroadcastReceiver{ + public class NetworkBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NetworkInfo network = conMan.getActiveNetworkInfo(); diff --git a/src/org/kiwix/kiwixmobile/di/PerActivity.java b/src/org/kiwix/kiwixmobile/di/PerActivity.java new file mode 100644 index 000000000..d5c4662ed --- /dev/null +++ b/src/org/kiwix/kiwixmobile/di/PerActivity.java @@ -0,0 +1,9 @@ +package org.kiwix.kiwixmobile.di; + +import java.lang.annotation.Retention; +import javax.inject.Scope; + +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Scope @Retention(RUNTIME) public @interface PerActivity { +} diff --git a/src/org/kiwix/kiwixmobile/di/components/ApplicationComponent.java b/src/org/kiwix/kiwixmobile/di/components/ApplicationComponent.java new file mode 100644 index 000000000..02452b6ce --- /dev/null +++ b/src/org/kiwix/kiwixmobile/di/components/ApplicationComponent.java @@ -0,0 +1,22 @@ +package org.kiwix.kiwixmobile.di.components; + +import dagger.Component; +import javax.inject.Singleton; +import org.kiwix.kiwixmobile.KiwixMobileActivity; +import org.kiwix.kiwixmobile.LibraryFragment; +import org.kiwix.kiwixmobile.di.modules.ApplicationModule; +import org.kiwix.kiwixmobile.di.modules.NetworkModule; +import org.kiwix.kiwixmobile.downloader.DownloadService; + +@Singleton +@Component(modules = { + ApplicationModule.class, + NetworkModule.class, +}) +public interface ApplicationComponent { + void inject(KiwixMobileActivity activity); + + void inject(DownloadService service); + + void inject(LibraryFragment libraryFragment); +} diff --git a/src/org/kiwix/kiwixmobile/di/modules/ApplicationModule.java b/src/org/kiwix/kiwixmobile/di/modules/ApplicationModule.java new file mode 100644 index 000000000..51eef4af1 --- /dev/null +++ b/src/org/kiwix/kiwixmobile/di/modules/ApplicationModule.java @@ -0,0 +1,24 @@ +package org.kiwix.kiwixmobile.di.modules; + +import android.app.NotificationManager; +import android.content.Context; +import dagger.Module; +import dagger.Provides; +import javax.inject.Singleton; +import org.kiwix.kiwixmobile.KiwixApplication; + +@Module public class ApplicationModule { + private final KiwixApplication application; + + public ApplicationModule(KiwixApplication application) { + this.application = application; + } + + @Provides @Singleton Context provideApplicationContext() { + return this.application; + } + + @Provides @Singleton NotificationManager provideNotificationManager(Context context){ + return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + } +} diff --git a/src/org/kiwix/kiwixmobile/di/modules/NetworkModule.java b/src/org/kiwix/kiwixmobile/di/modules/NetworkModule.java new file mode 100644 index 000000000..84f14f294 --- /dev/null +++ b/src/org/kiwix/kiwixmobile/di/modules/NetworkModule.java @@ -0,0 +1,28 @@ +package org.kiwix.kiwixmobile.di.modules; + +import dagger.Module; +import dagger.Provides; +import javax.inject.Singleton; +import okhttp3.OkHttpClient; +import org.kiwix.kiwixmobile.network.KiwixService; +import retrofit2.Retrofit; +import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; +import retrofit2.converter.simplexml.SimpleXmlConverterFactory; +import rx.schedulers.Schedulers; + +@Module public class NetworkModule { + @Provides @Singleton OkHttpClient provideOkHttpClient() { + return new OkHttpClient().newBuilder().followRedirects(true).followSslRedirects(true).build(); + } + + @Provides @Singleton KiwixService provideKiwixService(OkHttpClient okHttpClient) { + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("http://download.kiwix.org/") + .client(okHttpClient) + .addConverterFactory(SimpleXmlConverterFactory.create()) + .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) + .build(); + + return retrofit.create(KiwixService.class); + } +} diff --git a/src/org/kiwix/kiwixmobile/downloader/DownloadService.java b/src/org/kiwix/kiwixmobile/downloader/DownloadService.java index 534cdb7a0..5155eb311 100644 --- a/src/org/kiwix/kiwixmobile/downloader/DownloadService.java +++ b/src/org/kiwix/kiwixmobile/downloader/DownloadService.java @@ -1,10 +1,8 @@ package org.kiwix.kiwixmobile.downloader; -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.graphics.Color; import android.os.Binder; @@ -18,7 +16,16 @@ import android.util.Pair; import android.util.SparseArray; import android.util.SparseIntArray; import android.widget.Toast; - +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; +import javax.inject.Inject; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okio.BufferedSource; import org.kiwix.kiwixmobile.KiwixApplication; import org.kiwix.kiwixmobile.KiwixMobileActivity; import org.kiwix.kiwixmobile.LibraryFragment; @@ -29,25 +36,14 @@ import org.kiwix.kiwixmobile.library.entity.LibraryNetworkEntity; import org.kiwix.kiwixmobile.network.KiwixService; import org.kiwix.kiwixmobile.utils.StorageUtils; import org.kiwix.kiwixmobile.utils.files.FileUtils; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okio.BufferedSource; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; -import rx.observables.ConnectableObservable; public class DownloadService extends Service { - private KiwixService kiwixService; - private OkHttpClient client; + @Inject KiwixService kiwixService; + @Inject OkHttpClient httpClient; + @Inject NotificationManager notificationManager; private static String SD_CARD; public static String KIWIX_ROOT; @@ -63,7 +59,6 @@ public class DownloadService extends Service { public String notificationTitle; private SparseArray notification = new SparseArray<>(); - private NotificationManager notificationManager; public SparseIntArray downloadStatus = new SparseIntArray(); public SparseIntArray downloadProgress = new SparseIntArray(); public static final Object pauseLock = new Object(); @@ -75,11 +70,14 @@ public class DownloadService extends Service { downloadFragment = dFragment; } + private void setupDagger(){ + KiwixApplication.getInstance().getApplicationComponent().inject(this); + } + + @Override public void onCreate() { - kiwixService = ((KiwixApplication) getApplication()).getKiwixService(); - client = ((KiwixApplication) getApplication()).getOkHttpClient(); - notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + setupDagger(); SD_CARD = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .getString(KiwixMobileActivity.PREF_STORAGE,Environment.getExternalStorageDirectory().getPath()); @@ -87,8 +85,6 @@ public class DownloadService extends Service { KIWIX_ROOT = checkWritable(KIWIX_ROOT); - - super.onCreate(); } @@ -269,7 +265,7 @@ public class DownloadService extends Service { if (subscriber.isUnsubscribed()) return; try { Request request = new Request.Builder().url(url).head().build(); - Response response = client.newCall(request).execute(); + Response response = httpClient.newCall(request).execute(); String LengthHeader = response.headers().get("Content-Length"); long contentLength = LengthHeader == null ? 0 : Long.parseLong(LengthHeader); subscriber.onNext(new Pair<>(url, contentLength)); @@ -331,7 +327,7 @@ public class DownloadService extends Service { String rangeHeader = String.format("%d-%d", downloaded, chunk.getEndByte()); // Build request with up to date range - Response response = client.newCall( + Response response = httpClient.newCall( new Request.Builder() .url(chunk.getUrl()) .header("Range", "bytes=" + rangeHeader)