From 87d4e8d85f86dce1ce681198e88109ff4071fca0 Mon Sep 17 00:00:00 2001 From: Hermes Junior Date: Mon, 15 Jun 2020 15:24:15 +0200 Subject: Make exit animation follow slide direction on media activities. --- .../infinityforreddit/Activity/ViewGIFActivity.java | 7 ++++++- .../infinityforreddit/Activity/ViewImageActivity.java | 9 +++++++-- .../infinityforreddit/Activity/ViewImgurMediaActivity.java | 11 +++++++++-- .../infinityforreddit/Activity/ViewVideoActivity.java | 7 ++++++- 4 files changed, 28 insertions(+), 6 deletions(-) (limited to 'app/src/main/java') diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewGIFActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewGIFActivity.java index a1802a90..cc48a870 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewGIFActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewGIFActivity.java @@ -36,6 +36,7 @@ import com.bumptech.glide.load.resource.gif.GifDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.request.target.Target; +import com.thefuntasty.hauler.DragDirection; import com.thefuntasty.hauler.HaulerView; import java.io.File; @@ -117,7 +118,11 @@ public class ViewGIFActivity extends AppCompatActivity { actionBar.setHomeAsUpIndicator(upArrow); actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor))); - mHaulerView.setOnDragDismissedListener(dragDirection -> finish()); + mHaulerView.setOnDragDismissedListener(dragDirection -> { + int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down; + finish(); + overridePendingTransition(0, slide); + }); glide = Glide.with(this); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageActivity.java index 76acf253..0dacbb43 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageActivity.java @@ -43,6 +43,7 @@ import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.CustomTarget; import com.bumptech.glide.request.target.Target; import com.bumptech.glide.request.transition.Transition; +import com.thefuntasty.hauler.DragDirection; import com.thefuntasty.hauler.HaulerView; import java.io.File; @@ -139,7 +140,11 @@ public class ViewImageActivity extends AppCompatActivity implements SetAsWallpap setTitle(""); } - mHaulerView.setOnDragDismissedListener(dragDirection -> finish()); + mHaulerView.setOnDragDismissedListener(dragDirection -> { + int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down; + finish(); + overridePendingTransition(0, slide); + }); mLoadErrorLinearLayout.setOnClickListener(view -> { mProgressBar.setVisibility(View.VISIBLE); @@ -238,7 +243,7 @@ public class ViewImageActivity extends AppCompatActivity implements SetAsWallpap @Override public void saveSuccess(File imageFile) { Uri uri = FileProvider.getUriForFile(ViewImageActivity.this, - BuildConfig.APPLICATION_ID + ".provider",imageFile); + BuildConfig.APPLICATION_ID + ".provider", imageFile); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uri); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImgurMediaActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImgurMediaActivity.java index c4b0e38d..bae1fdf3 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImgurMediaActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImgurMediaActivity.java @@ -32,6 +32,7 @@ import androidx.viewpager.widget.ViewPager; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.CustomTarget; import com.bumptech.glide.request.transition.Transition; +import com.thefuntasty.hauler.DragDirection; import com.thefuntasty.hauler.HaulerView; import org.json.JSONArray; @@ -140,7 +141,11 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa images = savedInstanceState.getParcelableArrayList(IMGUR_IMAGES_STATE); } - haulerView.setOnDragDismissedListener(dragDirection -> finish()); + haulerView.setOnDragDismissedListener(dragDirection -> { + int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down; + finish(); + overridePendingTransition(0, slide); + }); if (images == null) { fetchImgurMedia(imgurId); @@ -439,6 +444,7 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa interface ParseImgurImagesAsyncTaskListener { void success(ArrayList images); + void failed(); } @@ -493,6 +499,7 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa interface ParseImgurImageAsyncTaskListener { void success(ImgurMedia image); + void failed(); } @@ -533,4 +540,4 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewVideoActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewVideoActivity.java index 1bccf67b..dad6ff0c 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewVideoActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewVideoActivity.java @@ -47,6 +47,7 @@ import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; import com.google.android.exoplayer2.util.Util; +import com.thefuntasty.hauler.DragDirection; import com.thefuntasty.hauler.HaulerView; import java.io.File; @@ -160,7 +161,11 @@ public class ViewVideoActivity extends AppCompatActivity { params.rightMargin = getResources().getDimensionPixelSize(resourceId); } - haulerView.setOnDragDismissedListener(dragDirection -> finish()); + haulerView.setOnDragDismissedListener(dragDirection -> { + int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down; + finish(); + overridePendingTransition(0, slide); + }); Intent intent = getIntent(); mVideoUri = intent.getData(); -- cgit v1.2.3 From 34b6ec90aa7976b8cccd180d6a7ef8a435bc883d Mon Sep 17 00:00:00 2001 From: Hermes Junior Date: Mon, 15 Jun 2020 17:18:50 +0200 Subject: Remove SidebarActivity, use sidebar page in SubredditDetailActivity. --- .../Activity/LinkResolverActivity.java | 5 +- .../Activity/ViewSidebarActivity.java | 251 --------------------- .../Activity/ViewSubredditDetailActivity.java | 12 +- .../infinityforreddit/AppComponent.java | 3 - .../Fragment/SidebarFragment.java | 5 +- 5 files changed, 11 insertions(+), 265 deletions(-) delete mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSidebarActivity.java (limited to 'app/src/main/java') diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/LinkResolverActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/LinkResolverActivity.java index 0b7cf47f..1ea32f2b 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/LinkResolverActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/LinkResolverActivity.java @@ -159,8 +159,9 @@ public class LinkResolverActivity extends AppCompatActivity { intent.putExtra(ViewUserDetailActivity.EXTRA_NEW_ACCOUNT_NAME, newAccountName); startActivity(intent); } else if (path.matches(SIDEBAR_PATTERN)) { - Intent intent = new Intent(this, ViewSidebarActivity.class); - intent.putExtra(ViewSidebarActivity.EXTRA_SUBREDDIT_NAME, path.substring(3, path.length() - 14)); + Intent intent = new Intent(this, ViewSubredditDetailActivity.class); + intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, path.substring(3, path.length() - 14)); + intent.putExtra(ViewSubredditDetailActivity.EXTRA_VIEW_SIDEBAR, true); startActivity(intent); } else if (path.matches(MULTIREDDIT_PATTERN)) { Intent intent = new Intent(this, ViewMultiRedditDetailActivity.class); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSidebarActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSidebarActivity.java deleted file mode 100644 index 826ba33d..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSidebarActivity.java +++ /dev/null @@ -1,251 +0,0 @@ -package ml.docilealligator.infinityforreddit.Activity; - -import android.content.Intent; -import android.content.SharedPreferences; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.text.Spanned; -import android.text.style.SuperscriptSpan; -import android.text.util.Linkify; -import android.util.TypedValue; -import android.view.Menu; -import android.view.MenuItem; -import android.view.Window; -import android.view.WindowManager; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.appcompat.widget.Toolbar; -import androidx.coordinatorlayout.widget.CoordinatorLayout; -import androidx.lifecycle.ViewModelProvider; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; - -import com.google.android.material.appbar.AppBarLayout; - -import org.commonmark.ext.gfm.tables.TableBlock; - -import javax.inject.Inject; -import javax.inject.Named; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.noties.markwon.AbstractMarkwonPlugin; -import io.noties.markwon.Markwon; -import io.noties.markwon.MarkwonConfiguration; -import io.noties.markwon.ext.strikethrough.StrikethroughPlugin; -import io.noties.markwon.linkify.LinkifyPlugin; -import io.noties.markwon.recycler.MarkwonAdapter; -import io.noties.markwon.recycler.table.TableEntry; -import io.noties.markwon.recycler.table.TableEntryPlugin; -import io.noties.markwon.simple.ext.SimpleExtPlugin; -import io.noties.markwon.urlprocessor.UrlProcessorRelativeToAbsolute; -import ml.docilealligator.infinityforreddit.ActivityToolbarInterface; -import ml.docilealligator.infinityforreddit.AsyncTask.InsertSubredditDataAsyncTask; -import ml.docilealligator.infinityforreddit.CustomTheme.CustomThemeWrapper; -import ml.docilealligator.infinityforreddit.FetchSubredditData; -import ml.docilealligator.infinityforreddit.Infinity; -import ml.docilealligator.infinityforreddit.R; -import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase; -import ml.docilealligator.infinityforreddit.SubredditDatabase.SubredditData; -import ml.docilealligator.infinityforreddit.SubredditDatabase.SubredditViewModel; -import retrofit2.Retrofit; - -public class ViewSidebarActivity extends BaseActivity implements ActivityToolbarInterface { - - public static final String EXTRA_SUBREDDIT_NAME = "ESN"; - @BindView(R.id.coordinator_layout_view_sidebar_activity) - CoordinatorLayout coordinatorLayout; - @BindView(R.id.appbar_layout_view_sidebar_activity) - AppBarLayout appBarLayout; - @BindView(R.id.toolbar_view_sidebar_activity) - Toolbar toolbar; - @BindView(R.id.swipe_refresh_layout_view_sidebar_activity) - SwipeRefreshLayout swipeRefreshLayout; - @BindView(R.id.markdown_recycler_view_view_sidebar_activity) - RecyclerView markdownRecyclerView; - @Inject - @Named("no_oauth") - Retrofit mRetrofit; - @Inject - RedditDataRoomDatabase mRedditDataRoomDatabase; - @Inject - @Named("default") - SharedPreferences mSharedPreferences; - @Inject - CustomThemeWrapper mCustomThemeWrapper; - public SubredditViewModel mSubredditViewModel; - private LinearLayoutManager mLinearLayoutManager; - private String subredditName; - private int markdownColor; - - @Override - protected void onCreate(Bundle savedInstanceState) { - ((Infinity) getApplication()).getAppComponent().inject(this); - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_view_sidebar); - - ButterKnife.bind(this); - - applyCustomTheme(); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - Window window = getWindow(); - - if (isChangeStatusBarIconColor()) { - addOnOffsetChangedListener(appBarLayout); - } - - if (isImmersiveInterface()) { - window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); - adjustToolbar(toolbar); - - int navBarHeight = getNavBarHeight(); - if (navBarHeight > 0) { - int px = (int) TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, - 16, - getResources().getDisplayMetrics() - ); - markdownRecyclerView.setPadding(px, px, px, navBarHeight); - } - } - } - - subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME); - if (subredditName == null) { - Toast.makeText(this, R.string.error_getting_subreddit_name, Toast.LENGTH_SHORT).show(); - finish(); - return; - } - - toolbar.setTitle("r/" + subredditName); - setSupportActionBar(toolbar); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - setToolbarGoToTop(toolbar); - - Markwon markwon = Markwon.builder(this) - .usePlugin(new AbstractMarkwonPlugin() { - @Override - public void beforeSetText(@NonNull TextView textView, @NonNull Spanned markdown) { - textView.setTextColor(markdownColor); - } - - @Override - public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) { - builder.linkResolver((view, link) -> { - Intent intent = new Intent(ViewSidebarActivity.this, LinkResolverActivity.class); - Uri uri = Uri.parse(link); - if (uri.getScheme() == null && uri.getHost() == null) { - intent.setData(LinkResolverActivity.getRedditUriByPath(link)); - } else { - intent.setData(uri); - } - ViewSidebarActivity.this.startActivity(intent); - }).urlProcessor(new UrlProcessorRelativeToAbsolute("https://www.reddit.com")); - } - }) - .usePlugin(StrikethroughPlugin.create()) - .usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS)) - .usePlugin(SimpleExtPlugin.create(plugin -> - plugin.addExtension(1, '^', (configuration, props) -> { - return new SuperscriptSpan(); - }) - ) - ) - .usePlugin(TableEntryPlugin.create(this)) - .build(); - MarkwonAdapter markwonAdapter = MarkwonAdapter.builder(R.layout.adapter_default_entry, R.id.text) - .include(TableBlock.class, TableEntry.create(builder -> builder - .tableLayout(R.layout.adapter_table_block, R.id.table_layout) - .textLayoutIsRoot(R.layout.view_table_entry_cell))) - .build(); - - mLinearLayoutManager = new LinearLayoutManager(this); - markdownRecyclerView.setLayoutManager(mLinearLayoutManager); - markdownRecyclerView.setAdapter(markwonAdapter); - - mSubredditViewModel = new ViewModelProvider(this, - new SubredditViewModel.Factory(getApplication(), mRedditDataRoomDatabase, subredditName)) - .get(SubredditViewModel.class); - mSubredditViewModel.getSubredditLiveData().observe(this, subredditData -> { - if (subredditData != null) { - if (subredditData.getSidebarDescription() != null && !subredditData.getSidebarDescription().equals("")) { - markwonAdapter.setMarkdown(markwon, subredditData.getSidebarDescription()); - markwonAdapter.notifyDataSetChanged(); - } - } else { - fetchSubredditData(); - } - }); - - swipeRefreshLayout.setOnRefreshListener(this::fetchSubredditData); - } - - private void fetchSubredditData() { - swipeRefreshLayout.setRefreshing(true); - FetchSubredditData.fetchSubredditData(mRetrofit, subredditName, new FetchSubredditData.FetchSubredditDataListener() { - @Override - public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { - swipeRefreshLayout.setRefreshing(false); - new InsertSubredditDataAsyncTask(mRedditDataRoomDatabase, subredditData, () -> swipeRefreshLayout.setRefreshing(false)).execute(); - } - - @Override - public void onFetchSubredditDataFail() { - swipeRefreshLayout.setRefreshing(false); - Toast.makeText(ViewSidebarActivity.this, R.string.cannot_fetch_sidebar, Toast.LENGTH_SHORT).show(); - } - }); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.view_sidebar_activity, menu); - applyMenuItemTheme(menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(@NonNull MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - return true; - } else if (item.getItemId() == R.id.action_refresh_view_sidebar_activity) { - if (!swipeRefreshLayout.isRefreshing()) { - fetchSubredditData(); - } - return true; - } - return false; - } - - @Override - public SharedPreferences getSharedPreferences() { - return mSharedPreferences; - } - - @Override - protected CustomThemeWrapper getCustomThemeWrapper() { - return mCustomThemeWrapper; - } - - @Override - protected void applyCustomTheme() { - coordinatorLayout.setBackgroundColor(mCustomThemeWrapper.getBackgroundColor()); - applyAppBarLayoutAndToolbarTheme(appBarLayout, toolbar); - swipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground()); - swipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent()); - markdownColor = mCustomThemeWrapper.getSecondaryTextColor(); - } - - @Override - public void onLongPress() { - if (mLinearLayoutManager != null) { - mLinearLayoutManager.scrollToPositionWithOffset(0, 0); - } - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSubredditDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSubredditDetailActivity.java index 0ec10e46..b8935842 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSubredditDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSubredditDetailActivity.java @@ -90,6 +90,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp public static final String EXTRA_SUBREDDIT_NAME_KEY = "ESN"; public static final String EXTRA_MESSAGE_FULLNAME = "ENF"; public static final String EXTRA_NEW_ACCOUNT_NAME = "ENAN"; + public static final String EXTRA_VIEW_SIDEBAR = "EVSB"; private static final String FETCH_SUBREDDIT_INFO_STATE = "FSIS"; private static final String CURRENT_ONLINE_SUBSCRIBERS_STATE = "COSS"; @@ -627,6 +628,12 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp viewPager.setOffscreenPageLimit(2); tabLayout.setupWithViewPager(viewPager); + + boolean viewSidebar = getIntent().getBooleanExtra(EXTRA_VIEW_SIDEBAR, false); + if (viewSidebar) { + viewPager.setCurrentItem(1, false); + } + viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { @@ -724,11 +731,6 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp case R.id.action_change_post_layout_view_subreddit_detail_activity: postLayoutBottomSheetFragment.show(getSupportFragmentManager(), postLayoutBottomSheetFragment.getTag()); return true; - case R.id.action_view_side_bar_view_subreddit_detail_activity: - Intent sidebarIntent = new Intent(this, ViewSidebarActivity.class); - sidebarIntent.putExtra(ViewSidebarActivity.EXTRA_SUBREDDIT_NAME, subredditName); - startActivity(sidebarIntent); - return true; case R.id.action_share_view_subreddit_detail_activity: Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java b/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java index 651b09b7..74c850b6 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/AppComponent.java @@ -38,7 +38,6 @@ import ml.docilealligator.infinityforreddit.Activity.ViewImgurMediaActivity; import ml.docilealligator.infinityforreddit.Activity.ViewMessageActivity; import ml.docilealligator.infinityforreddit.Activity.ViewMultiRedditDetailActivity; import ml.docilealligator.infinityforreddit.Activity.ViewPostDetailActivity; -import ml.docilealligator.infinityforreddit.Activity.ViewSidebarActivity; import ml.docilealligator.infinityforreddit.Activity.ViewSubredditDetailActivity; import ml.docilealligator.infinityforreddit.Activity.ViewUserDetailActivity; import ml.docilealligator.infinityforreddit.Activity.ViewVideoActivity; @@ -142,8 +141,6 @@ public interface AppComponent { void inject(ViewMultiRedditDetailActivity viewMultiRedditDetailActivity); - void inject(ViewSidebarActivity viewSidebarActivity); - void inject(ViewVideoActivity viewVideoActivity); void inject(GesturesAndButtonsPreferenceFragment gesturesAndButtonsPreferenceFragment); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/SidebarFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/SidebarFragment.java index dbafed2d..9d9aa9b7 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/SidebarFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/SidebarFragment.java @@ -50,9 +50,6 @@ import ml.docilealligator.infinityforreddit.SubredditDatabase.SubredditData; import ml.docilealligator.infinityforreddit.SubredditDatabase.SubredditViewModel; import retrofit2.Retrofit; -/** - * A simple {@link Fragment} subclass. - */ public class SidebarFragment extends Fragment { public static final String EXTRA_SUBREDDIT_NAME = "ESN"; @@ -152,7 +149,7 @@ public class SidebarFragment extends Fragment { mSubredditViewModel = new ViewModelProvider(this, new SubredditViewModel.Factory(activity.getApplication(), mRedditDataRoomDatabase, subredditName)) .get(SubredditViewModel.class); - mSubredditViewModel.getSubredditLiveData().observe(this, subredditData -> { + mSubredditViewModel.getSubredditLiveData().observe(getViewLifecycleOwner(), subredditData -> { if (subredditData != null) { if (subredditData.getSidebarDescription() != null && !subredditData.getSidebarDescription().equals("")) { markwonAdapter.setMarkdown(markwon, subredditData.getSidebarDescription()); -- cgit v1.2.3 From 88a21195860bb99ab3cbc4b992b1d57bc016fcb4 Mon Sep 17 00:00:00 2001 From: Alex Ning Date: Tue, 16 Jun 2020 15:17:00 +0800 Subject: Resolve conflicts: Some refactors on media activities. --- .../Activity/LinkResolverActivity.java | 16 +- .../Activity/ViewGIFActivity.java | 324 ---------------- .../Activity/ViewImageActivity.java | 421 --------------------- .../Activity/ViewImageOrGifActivity.java | 374 ++++++++++++++++++ .../Activity/ViewImgurMediaActivity.java | 93 +---- .../Activity/ViewSubredditDetailActivity.java | 12 +- .../Activity/ViewUserDetailActivity.java | 12 +- .../Activity/ViewVideoActivity.java | 53 +-- .../Adapter/CommentAndPostRecyclerViewAdapter.java | 35 +- .../Adapter/PostRecyclerViewAdapter.java | 65 ++-- .../infinityforreddit/AppComponent.java | 7 +- .../AsyncTask/SetAsWallpaperAsyncTask.java | 98 +++++ .../Fragment/ViewImgurImageFragment.java | 61 +-- .../Fragment/ViewImgurVideoFragment.java | 51 +-- .../infinityforreddit/MediaDownloader.java | 7 + .../infinityforreddit/MediaDownloaderImpl.java | 58 +++ .../infinityforreddit/WallpaperSetter.java | 92 +++++ 17 files changed, 731 insertions(+), 1048 deletions(-) delete mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewGIFActivity.java delete mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageActivity.java create mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageOrGifActivity.java create mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/AsyncTask/SetAsWallpaperAsyncTask.java create mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/MediaDownloader.java create mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/MediaDownloaderImpl.java create mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/WallpaperSetter.java (limited to 'app/src/main/java') diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/LinkResolverActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/LinkResolverActivity.java index 1ea32f2b..45c310c0 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/LinkResolverActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/LinkResolverActivity.java @@ -79,20 +79,20 @@ public class LinkResolverActivity extends AppCompatActivity { } if (path.endsWith("jpg") || path.endsWith("png")) { - Intent intent = new Intent(this, ViewImageActivity.class); + Intent intent = new Intent(this, ViewImageOrGifActivity.class); String url = uri.toString(); String fileName = url.substring(url.lastIndexOf('/') + 1); - intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, url); - intent.putExtra(ViewImageActivity.FILE_NAME_KEY, fileName); - intent.putExtra(ViewImageActivity.POST_TITLE_KEY, fileName); + intent.putExtra(ViewImageOrGifActivity.IMAGE_URL_KEY, url); + intent.putExtra(ViewImageOrGifActivity.FILE_NAME_KEY, fileName); + intent.putExtra(ViewImageOrGifActivity.POST_TITLE_KEY, fileName); startActivity(intent); } else if (path.endsWith("gif")) { - Intent intent = new Intent(this, ViewGIFActivity.class); + Intent intent = new Intent(this, ViewImageOrGifActivity.class); String url = uri.toString(); String fileName = url.substring(url.lastIndexOf('/') + 1); - intent.putExtra(ViewGIFActivity.GIF_URL_KEY, url); - intent.putExtra(ViewGIFActivity.FILE_NAME_KEY, fileName); - intent.putExtra(ViewGIFActivity.POST_TITLE_KEY, fileName); + intent.putExtra(ViewImageOrGifActivity.GIF_URL_KEY, url); + intent.putExtra(ViewImageOrGifActivity.FILE_NAME_KEY, fileName); + intent.putExtra(ViewImageOrGifActivity.POST_TITLE_KEY, fileName); startActivity(intent); } else if (path.endsWith("mp4")) { Intent intent = new Intent(this, ViewVideoActivity.class); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewGIFActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewGIFActivity.java deleted file mode 100644 index cc48a870..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewGIFActivity.java +++ /dev/null @@ -1,324 +0,0 @@ -package ml.docilealligator.infinityforreddit.Activity; - -import android.Manifest; -import android.app.DownloadManager; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.os.Environment; -import android.text.Html; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.LinearLayout; -import android.widget.ProgressBar; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; -import androidx.core.content.FileProvider; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.RequestManager; -import com.bumptech.glide.load.DataSource; -import com.bumptech.glide.load.engine.GlideException; -import com.bumptech.glide.load.resource.gif.GifDrawable; -import com.bumptech.glide.request.RequestListener; -import com.bumptech.glide.request.RequestOptions; -import com.bumptech.glide.request.target.Target; -import com.thefuntasty.hauler.DragDirection; -import com.thefuntasty.hauler.HaulerView; - -import java.io.File; - -import javax.inject.Inject; -import javax.inject.Named; - -import butterknife.BindView; -import butterknife.ButterKnife; -import ml.docilealligator.infinityforreddit.AsyncTask.SaveGIFToFileAsyncTask; -import ml.docilealligator.infinityforreddit.BuildConfig; -import ml.docilealligator.infinityforreddit.Font.ContentFontFamily; -import ml.docilealligator.infinityforreddit.Font.ContentFontStyle; -import ml.docilealligator.infinityforreddit.Font.FontFamily; -import ml.docilealligator.infinityforreddit.Font.FontStyle; -import ml.docilealligator.infinityforreddit.Font.TitleFontFamily; -import ml.docilealligator.infinityforreddit.Font.TitleFontStyle; -import ml.docilealligator.infinityforreddit.Infinity; -import ml.docilealligator.infinityforreddit.R; -import ml.docilealligator.infinityforreddit.Utils.SharedPreferencesUtils; -import pl.droidsonroids.gif.GifImageView; - -public class ViewGIFActivity extends AppCompatActivity { - - public static final String GIF_URL_KEY = "GUK"; - public static final String FILE_NAME_KEY = "FNK"; - public static final String POST_TITLE_KEY = "PTK"; - private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0; - @BindView(R.id.hauler_view_view_gif_activity) - HaulerView mHaulerView; - @BindView(R.id.progress_bar_view_gif_activity) - ProgressBar mProgressBar; - @BindView(R.id.image_view_view_gif_activity) - GifImageView mImageView; - @BindView(R.id.load_image_error_linear_layout_view_gif_activity) - LinearLayout mLoadErrorLinearLayout; - @Inject - @Named("default") - SharedPreferences mSharedPreferences; - private boolean isActionBarHidden = false; - private boolean isDownloading = false; - private RequestManager glide; - private String mImageUrl; - private String mImageFileName; - private boolean isSwiping = false; - private String postTitle; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ((Infinity) getApplication()).getAppComponent().inject(this); - - getTheme().applyStyle(R.style.Theme_Normal, true); - - getTheme().applyStyle(FontStyle.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.FONT_SIZE_KEY, FontStyle.Normal.name())).getResId(), true); - - getTheme().applyStyle(TitleFontStyle.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.TITLE_FONT_SIZE_KEY, TitleFontStyle.Normal.name())).getResId(), true); - - getTheme().applyStyle(ContentFontStyle.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.CONTENT_FONT_SIZE_KEY, ContentFontStyle.Normal.name())).getResId(), true); - - getTheme().applyStyle(FontFamily.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.FONT_FAMILY_KEY, FontFamily.Default.name())).getResId(), true); - - getTheme().applyStyle(TitleFontFamily.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.TITLE_FONT_FAMILY_KEY, TitleFontFamily.Default.name())).getResId(), true); - - getTheme().applyStyle(ContentFontFamily.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.CONTENT_FONT_FAMILY_KEY, ContentFontFamily.Default.name())).getResId(), true); - - setContentView(R.layout.activity_view_gif); - - ButterKnife.bind(this); - - ActionBar actionBar = getSupportActionBar(); - Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp); - actionBar.setHomeAsUpIndicator(upArrow); - actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor))); - - mHaulerView.setOnDragDismissedListener(dragDirection -> { - int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down; - finish(); - overridePendingTransition(0, slide); - }); - - glide = Glide.with(this); - - Intent intent = getIntent(); - mImageUrl = intent.getStringExtra(GIF_URL_KEY); - mImageFileName = intent.getStringExtra(FILE_NAME_KEY); - postTitle = intent.getStringExtra(POST_TITLE_KEY); - - if (postTitle != null) { - setTitle(Html.fromHtml(String.format("%s", postTitle))); - } else { - setTitle(""); - } - - mLoadErrorLinearLayout.setOnClickListener(view -> { - if (!isSwiping) { - mProgressBar.setVisibility(View.VISIBLE); - mLoadErrorLinearLayout.setVisibility(View.GONE); - loadImage(); - } - }); - - loadImage(); - - mImageView.setOnClickListener(view -> { - if (isActionBarHidden) { - getWindow().getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); - isActionBarHidden = false; - } else { - getWindow().getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE); - isActionBarHidden = true; - } - }); - } - - private void loadImage() { - glide.load(mImageUrl).listener(new RequestListener() { - @Override - public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - mProgressBar.setVisibility(View.GONE); - mLoadErrorLinearLayout.setVisibility(View.VISIBLE); - return false; - } - - @Override - public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { - mProgressBar.setVisibility(View.GONE); - return false; - } - }).apply(new RequestOptions().fitCenter()).into(mImageView); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.view_gif_activity, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - finish(); - return true; - case R.id.action_download_view_gif_activity: - if (isDownloading) { - return false; - } - - isDownloading = true; - - if (Build.VERSION.SDK_INT >= 23) { - if (ContextCompat.checkSelfPermission(this, - Manifest.permission.WRITE_EXTERNAL_STORAGE) - != PackageManager.PERMISSION_GRANTED) { - - // Permission is not granted - // No explanation needed; request the permission - ActivityCompat.requestPermissions(this, - new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, - PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); - } else { - // Permission has already been granted - download(); - } - } else { - download(); - } - - return true; - case R.id.action_share_view_gif_activity: - Toast.makeText(ViewGIFActivity.this, R.string.save_gif_first, Toast.LENGTH_SHORT).show(); - glide.asGif().load(mImageUrl).listener(new RequestListener() { - @Override - public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - return false; - } - - @Override - public boolean onResourceReady(GifDrawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { - if (getExternalCacheDir() != null) { - new SaveGIFToFileAsyncTask(resource, getExternalCacheDir().getPath(), mImageFileName, - new SaveGIFToFileAsyncTask.SaveGIFToFileAsyncTaskListener() { - @Override - public void saveSuccess(File imageFile) { - Uri uri = FileProvider.getUriForFile(ViewGIFActivity.this, - BuildConfig.APPLICATION_ID + ".provider", imageFile); - Intent shareIntent = new Intent(); - shareIntent.setAction(Intent.ACTION_SEND); - shareIntent.putExtra(Intent.EXTRA_STREAM, uri); - shareIntent.setType("image/*"); - shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - startActivity(Intent.createChooser(shareIntent, getString(R.string.share))); - } - - @Override - public void saveFailed() { - Toast.makeText(ViewGIFActivity.this, - R.string.cannot_save_gif, Toast.LENGTH_SHORT).show(); - } - }).execute(); - } else { - Toast.makeText(ViewGIFActivity.this, - R.string.cannot_get_storage, Toast.LENGTH_SHORT).show(); - } - return false; - } - }).submit(); - return true; - } - - return false; - } - - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { - if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) { - if (grantResults[0] == PackageManager.PERMISSION_DENIED) { - Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show(); - } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED && isDownloading) { - download(); - } - isDownloading = false; - } - } - - private void download() { - DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mImageUrl)); - request.setTitle(mImageFileName); - - request.allowScanningByMediaScanner(); - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - - //Android Q support - if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, mImageFileName); - } else { - String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString(); - File directory = new File(path + "/Infinity/"); - boolean saveToInfinityFolder = true; - if (!directory.exists()) { - if (!directory.mkdir()) { - saveToInfinityFolder = false; - } - } else { - if (directory.isFile()) { - if (!(directory.delete() && directory.mkdir())) { - saveToInfinityFolder = false; - } - } - } - - if (saveToInfinityFolder) { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES + "/Infinity/", mImageFileName); - } else { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, mImageFileName); - } - } - - DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); - - if (manager == null) { - Toast.makeText(this, R.string.download_failed, Toast.LENGTH_SHORT).show(); - return; - } - - manager.enqueue(request); - Toast.makeText(this, R.string.download_started, Toast.LENGTH_SHORT).show(); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageActivity.java deleted file mode 100644 index 670a89d9..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageActivity.java +++ /dev/null @@ -1,421 +0,0 @@ -package ml.docilealligator.infinityforreddit.Activity; - -import android.Manifest; -import android.app.DownloadManager; -import android.app.WallpaperManager; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.graphics.Bitmap; -import android.graphics.Rect; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.Drawable; -import android.media.ThumbnailUtils; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.os.Environment; -import android.text.Html; -import android.util.DisplayMetrics; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.WindowManager; -import android.widget.LinearLayout; -import android.widget.ProgressBar; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; -import androidx.core.content.FileProvider; - -import com.alexvasilkov.gestures.views.GestureImageView; -import com.bumptech.glide.Glide; -import com.bumptech.glide.RequestManager; -import com.bumptech.glide.load.DataSource; -import com.bumptech.glide.load.engine.GlideException; -import com.bumptech.glide.request.RequestListener; -import com.bumptech.glide.request.target.CustomTarget; -import com.bumptech.glide.request.target.Target; -import com.bumptech.glide.request.transition.Transition; -import com.thefuntasty.hauler.DragDirection; -import com.thefuntasty.hauler.HaulerView; - -import java.io.File; -import java.io.IOException; - -import javax.inject.Inject; -import javax.inject.Named; - -import butterknife.BindView; -import butterknife.ButterKnife; -import ml.docilealligator.infinityforreddit.AsyncTask.SaveImageToFileAsyncTask; -import ml.docilealligator.infinityforreddit.BottomSheetFragment.SetAsWallpaperBottomSheetFragment; -import ml.docilealligator.infinityforreddit.BuildConfig; -import ml.docilealligator.infinityforreddit.Font.ContentFontFamily; -import ml.docilealligator.infinityforreddit.Font.ContentFontStyle; -import ml.docilealligator.infinityforreddit.Font.FontFamily; -import ml.docilealligator.infinityforreddit.Font.FontStyle; -import ml.docilealligator.infinityforreddit.Font.TitleFontFamily; -import ml.docilealligator.infinityforreddit.Font.TitleFontStyle; -import ml.docilealligator.infinityforreddit.Infinity; -import ml.docilealligator.infinityforreddit.R; -import ml.docilealligator.infinityforreddit.SetAsWallpaperCallback; -import ml.docilealligator.infinityforreddit.Utils.SharedPreferencesUtils; - -public class ViewImageActivity extends AppCompatActivity implements SetAsWallpaperCallback { - - public static final String IMAGE_URL_KEY = "IUK"; - public static final String FILE_NAME_KEY = "FNK"; - public static final String POST_TITLE_KEY = "PTK"; - private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0; - @BindView(R.id.hauler_view_view_image_activity) - HaulerView mHaulerView; - @BindView(R.id.progress_bar_view_image_activity) - ProgressBar mProgressBar; - @BindView(R.id.image_view_view_image_activity) - GestureImageView mImageView; - @BindView(R.id.load_image_error_linear_layout_view_image_activity) - LinearLayout mLoadErrorLinearLayout; - @Inject - @Named("default") - SharedPreferences mSharedPreferences; - private boolean isActionBarHidden = false; - private boolean isDownloading = false; - private String mImageUrl; - private String mImageFileName; - private RequestManager glide; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - ((Infinity) getApplication()).getAppComponent().inject(this); - - getTheme().applyStyle(R.style.Theme_Normal, true); - - getTheme().applyStyle(FontStyle.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.FONT_SIZE_KEY, FontStyle.Normal.name())).getResId(), true); - - getTheme().applyStyle(TitleFontStyle.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.TITLE_FONT_SIZE_KEY, TitleFontStyle.Normal.name())).getResId(), true); - - getTheme().applyStyle(ContentFontStyle.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.CONTENT_FONT_SIZE_KEY, ContentFontStyle.Normal.name())).getResId(), true); - - getTheme().applyStyle(FontFamily.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.FONT_FAMILY_KEY, FontFamily.Default.name())).getResId(), true); - - getTheme().applyStyle(TitleFontFamily.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.TITLE_FONT_FAMILY_KEY, TitleFontFamily.Default.name())).getResId(), true); - - getTheme().applyStyle(ContentFontFamily.valueOf(mSharedPreferences - .getString(SharedPreferencesUtils.CONTENT_FONT_FAMILY_KEY, ContentFontFamily.Default.name())).getResId(), true); - - setContentView(R.layout.activity_view_image); - - ButterKnife.bind(this); - - ActionBar actionBar = getSupportActionBar(); - Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp); - actionBar.setHomeAsUpIndicator(upArrow); - actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor))); - - glide = Glide.with(this); - - Intent intent = getIntent(); - mImageUrl = intent.getStringExtra(IMAGE_URL_KEY); - mImageFileName = intent.getStringExtra(FILE_NAME_KEY); - String postTitle = intent.getStringExtra(POST_TITLE_KEY); - - if (postTitle != null) { - setTitle(Html.fromHtml(String.format("%s", postTitle))); - } else { - setTitle(""); - } - - mHaulerView.setOnDragDismissedListener(dragDirection -> { - int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down; - finish(); - overridePendingTransition(0, slide); - }); - - mLoadErrorLinearLayout.setOnClickListener(view -> { - mProgressBar.setVisibility(View.VISIBLE); - mLoadErrorLinearLayout.setVisibility(View.GONE); - loadImage(); - }); - - loadImage(); - - mImageView.getController().getSettings().setMaxZoom(10f).setDoubleTapZoom(2f).setPanEnabled(true); - - mImageView.setOnClickListener(view -> { - if (isActionBarHidden) { - getWindow().getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); - isActionBarHidden = false; - } else { - getWindow().getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE); - isActionBarHidden = true; - } - }); - } - - private void loadImage() { - glide.load(mImageUrl).listener(new RequestListener() { - @Override - public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - mProgressBar.setVisibility(View.GONE); - mLoadErrorLinearLayout.setVisibility(View.VISIBLE); - return false; - } - - @Override - public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { - mProgressBar.setVisibility(View.GONE); - return false; - } - }).override(Target.SIZE_ORIGINAL).into(mImageView); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.view_image_activity, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - finish(); - return true; - case R.id.action_download_view_image_activity: - if (isDownloading) { - return false; - } - - isDownloading = true; - - if (Build.VERSION.SDK_INT >= 23) { - if (ContextCompat.checkSelfPermission(this, - Manifest.permission.WRITE_EXTERNAL_STORAGE) - != PackageManager.PERMISSION_GRANTED) { - - // Permission is not granted - // No explanation needed; request the permission - ActivityCompat.requestPermissions(this, - new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, - PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); - } else { - // Permission has already been granted - download(); - } - } else { - download(); - } - - return true; - case R.id.action_share_view_image_activity: - glide.asBitmap().load(mImageUrl).into(new CustomTarget() { - - @Override - public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) { - if (getExternalCacheDir() != null) { - Toast.makeText(ViewImageActivity.this, R.string.save_image_first, Toast.LENGTH_SHORT).show(); - new SaveImageToFileAsyncTask(resource, getExternalCacheDir().getPath(), mImageFileName, - new SaveImageToFileAsyncTask.SaveImageToFileAsyncTaskListener() { - @Override - public void saveSuccess(File imageFile) { - Uri uri = FileProvider.getUriForFile(ViewImageActivity.this, - BuildConfig.APPLICATION_ID + ".provider", imageFile); - Intent shareIntent = new Intent(); - shareIntent.setAction(Intent.ACTION_SEND); - shareIntent.putExtra(Intent.EXTRA_STREAM, uri); - shareIntent.setType("image/*"); - shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - startActivity(Intent.createChooser(shareIntent, getString(R.string.share))); - } - - @Override - public void saveFailed() { - Toast.makeText(ViewImageActivity.this, - R.string.cannot_save_image, Toast.LENGTH_SHORT).show(); - } - }).execute(); - } else { - Toast.makeText(ViewImageActivity.this, - R.string.cannot_get_storage, Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void onLoadCleared(@Nullable Drawable placeholder) { - - } - }); - return true; - - case R.id.action_set_wallpaper_view_image_activity: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - SetAsWallpaperBottomSheetFragment setAsWallpaperBottomSheetFragment = new SetAsWallpaperBottomSheetFragment(); - setAsWallpaperBottomSheetFragment.show(getSupportFragmentManager(), setAsWallpaperBottomSheetFragment.getTag()); - } else { - setAsWallpaper(2); - } - return true; - } - - return false; - } - - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { - if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) { - if (grantResults[0] == PackageManager.PERMISSION_DENIED) { - Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show(); - } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED && isDownloading) { - download(); - } - isDownloading = false; - } - } - - private void download() { - DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mImageUrl)); - request.setTitle(mImageFileName); - - request.allowScanningByMediaScanner(); - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - - //Android Q support - if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, mImageFileName); - } else { - String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString(); - File directory = new File(path + "/Infinity/"); - boolean saveToInfinityFolder = true; - if (!directory.exists()) { - if (!directory.mkdir()) { - saveToInfinityFolder = false; - } - } else { - if (directory.isFile()) { - if (!(directory.delete() && directory.mkdir())) { - saveToInfinityFolder = false; - } - } - } - - if (saveToInfinityFolder) { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES + "/Infinity/", mImageFileName); - } else { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, mImageFileName); - } - } - - DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); - - if (manager == null) { - Toast.makeText(this, R.string.download_failed, Toast.LENGTH_SHORT).show(); - return; - } - - manager.enqueue(request); - Toast.makeText(this, R.string.download_started, Toast.LENGTH_SHORT).show(); - } - - private void setAsWallpaper(int setTo) { - Toast.makeText(ViewImageActivity.this, R.string.save_image_first, Toast.LENGTH_SHORT).show(); - glide.asBitmap().load(mImageUrl).into(new CustomTarget() { - @Override - public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) { - WallpaperManager manager = WallpaperManager.getInstance(ViewImageActivity.this); - - DisplayMetrics metrics = new DisplayMetrics(); - WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); - - Rect rect = null; - - if (windowManager != null) { - windowManager.getDefaultDisplay().getMetrics(metrics); - int height = metrics.heightPixels; - int width = metrics.widthPixels; - - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { - resource = ThumbnailUtils.extractThumbnail(resource, width, height); - } - - float imageAR = (float) resource.getWidth() / (float) resource.getHeight(); - float screenAR = (float) width / (float) height; - - if (imageAR > screenAR) { - int desiredWidth = (int) (resource.getHeight() * screenAR); - rect = new Rect((resource.getWidth() - desiredWidth) / 2, 0, resource.getWidth(), resource.getHeight()); - } else { - int desiredHeight = (int) (resource.getWidth() / screenAR); - rect = new Rect(0, (resource.getHeight() - desiredHeight) / 2, resource.getWidth(), (resource.getHeight() + desiredHeight) / 2); - } - } - try { - switch (setTo) { - case 0: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - manager.setBitmap(resource, rect, true, WallpaperManager.FLAG_SYSTEM); - } - break; - case 1: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - manager.setBitmap(resource, rect, true, WallpaperManager.FLAG_LOCK); - } - break; - case 2: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - manager.setBitmap(resource, rect, true, WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK); - } else { - manager.setBitmap(resource); - } - break; - } - Toast.makeText(ViewImageActivity.this, R.string.wallpaper_set, Toast.LENGTH_SHORT).show(); - } catch (IOException e) { - Toast.makeText(ViewImageActivity.this, R.string.error_set_wallpaper, Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void onLoadCleared(@Nullable Drawable placeholder) { - - } - }); - } - - @Override - public void setToHomeScreen(int viewPagerPosition) { - setAsWallpaper(0); - } - - @Override - public void setToLockScreen(int viewPagerPosition) { - setAsWallpaper(1); - } - - @Override - public void setToBoth(int viewPagerPosition) { - setAsWallpaper(2); - } -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageOrGifActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageOrGifActivity.java new file mode 100644 index 00000000..ee4ecb8d --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImageOrGifActivity.java @@ -0,0 +1,374 @@ +package ml.docilealligator.infinityforreddit.Activity; + +import android.Manifest; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.Drawable; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.text.Html; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.core.content.FileProvider; + +import com.alexvasilkov.gestures.views.GestureFrameLayout; +import com.bumptech.glide.Glide; +import com.bumptech.glide.RequestManager; +import com.bumptech.glide.load.DataSource; +import com.bumptech.glide.load.engine.GlideException; +import com.bumptech.glide.load.resource.gif.GifDrawable; +import com.bumptech.glide.request.RequestListener; +import com.bumptech.glide.request.target.CustomTarget; +import com.bumptech.glide.request.target.Target; +import com.bumptech.glide.request.transition.Transition; +import com.thefuntasty.hauler.DragDirection; +import com.thefuntasty.hauler.HaulerView; + +import java.io.File; + +import javax.inject.Inject; +import javax.inject.Named; + +import butterknife.BindView; +import butterknife.ButterKnife; +import ml.docilealligator.infinityforreddit.AsyncTask.SaveGIFToFileAsyncTask; +import ml.docilealligator.infinityforreddit.AsyncTask.SaveImageToFileAsyncTask; +import ml.docilealligator.infinityforreddit.BottomSheetFragment.SetAsWallpaperBottomSheetFragment; +import ml.docilealligator.infinityforreddit.BuildConfig; +import ml.docilealligator.infinityforreddit.Font.ContentFontFamily; +import ml.docilealligator.infinityforreddit.Font.ContentFontStyle; +import ml.docilealligator.infinityforreddit.Font.FontFamily; +import ml.docilealligator.infinityforreddit.Font.FontStyle; +import ml.docilealligator.infinityforreddit.Font.TitleFontFamily; +import ml.docilealligator.infinityforreddit.Font.TitleFontStyle; +import ml.docilealligator.infinityforreddit.Infinity; +import ml.docilealligator.infinityforreddit.MediaDownloader; +import ml.docilealligator.infinityforreddit.MediaDownloaderImpl; +import ml.docilealligator.infinityforreddit.R; +import ml.docilealligator.infinityforreddit.SetAsWallpaperCallback; +import ml.docilealligator.infinityforreddit.Utils.SharedPreferencesUtils; +import ml.docilealligator.infinityforreddit.WallpaperSetter; +import pl.droidsonroids.gif.GifImageView; + +public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWallpaperCallback { + + public static final String IMAGE_URL_KEY = "IUK"; + public static final String GIF_URL_KEY = "GUK"; + public static final String FILE_NAME_KEY = "FNK"; + public static final String POST_TITLE_KEY = "PTK"; + private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0; + @BindView(R.id.hauler_view_view_image_or_gif_activity) + HaulerView mHaulerView; + @BindView(R.id.progress_bar_view_image_or_gif_activity) + ProgressBar mProgressBar; + @BindView(R.id.image_view_view_image_or_gif_activity) + GifImageView mImageView; + @BindView(R.id.gesture_layout_view_image_or_gif_activity) + GestureFrameLayout gestureLayout; + @BindView(R.id.load_image_error_linear_layout_view_image_or_gif_activity) + LinearLayout mLoadErrorLinearLayout; + @Inject + @Named("default") + SharedPreferences mSharedPreferences; + private MediaDownloader mediaDownloader; + private WallpaperSetter wallpaperSetter; + private boolean isActionBarHidden = false; + private boolean isDownloading = false; + private RequestManager glide; + private String mImageUrl; + private String mImageFileName; + private boolean isGif = true; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + ((Infinity) getApplication()).getAppComponent().inject(this); + + getTheme().applyStyle(R.style.Theme_Normal, true); + + getTheme().applyStyle(FontStyle.valueOf(mSharedPreferences + .getString(SharedPreferencesUtils.FONT_SIZE_KEY, FontStyle.Normal.name())).getResId(), true); + + getTheme().applyStyle(TitleFontStyle.valueOf(mSharedPreferences + .getString(SharedPreferencesUtils.TITLE_FONT_SIZE_KEY, TitleFontStyle.Normal.name())).getResId(), true); + + getTheme().applyStyle(ContentFontStyle.valueOf(mSharedPreferences + .getString(SharedPreferencesUtils.CONTENT_FONT_SIZE_KEY, ContentFontStyle.Normal.name())).getResId(), true); + + getTheme().applyStyle(FontFamily.valueOf(mSharedPreferences + .getString(SharedPreferencesUtils.FONT_FAMILY_KEY, FontFamily.Default.name())).getResId(), true); + + getTheme().applyStyle(TitleFontFamily.valueOf(mSharedPreferences + .getString(SharedPreferencesUtils.TITLE_FONT_FAMILY_KEY, TitleFontFamily.Default.name())).getResId(), true); + + getTheme().applyStyle(ContentFontFamily.valueOf(mSharedPreferences + .getString(SharedPreferencesUtils.CONTENT_FONT_FAMILY_KEY, ContentFontFamily.Default.name())).getResId(), true); + + setContentView(R.layout.activity_view_image_or_gif); + + ButterKnife.bind(this); + + ActionBar actionBar = getSupportActionBar(); + Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp); + actionBar.setHomeAsUpIndicator(upArrow); + actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor))); + + mHaulerView.setOnDragDismissedListener(dragDirection -> finish()); + + mediaDownloader = new MediaDownloaderImpl(); + wallpaperSetter = new WallpaperSetter(); + + glide = Glide.with(this); + + Intent intent = getIntent(); + mImageUrl = intent.getStringExtra(GIF_URL_KEY); + if (mImageUrl == null) { + isGif = false; + mImageUrl = intent.getStringExtra(IMAGE_URL_KEY); + } + mImageFileName = intent.getStringExtra(FILE_NAME_KEY); + String postTitle = intent.getStringExtra(POST_TITLE_KEY); + + if (postTitle != null) { + setTitle(Html.fromHtml(String.format("%s", postTitle))); + } else { + setTitle(""); + } + + mHaulerView.setOnDragDismissedListener(dragDirection -> { + int slide = dragDirection == DragDirection.UP ? R.anim.slide_out_up : R.anim.slide_out_down; + finish(); + overridePendingTransition(0, slide); + }); + + mLoadErrorLinearLayout.setOnClickListener(view -> { + mProgressBar.setVisibility(View.VISIBLE); + mLoadErrorLinearLayout.setVisibility(View.GONE); + loadImage(); + }); + + loadImage(); + + gestureLayout.getController().getSettings().setMaxZoom(10f).setDoubleTapZoom(2f).setPanEnabled(true); + + mImageView.setOnClickListener(view -> { + if (isActionBarHidden) { + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); + isActionBarHidden = false; + } else { + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN + | View.SYSTEM_UI_FLAG_IMMERSIVE); + isActionBarHidden = true; + } + }); + } + + private void loadImage() { + glide.load(mImageUrl).listener(new RequestListener() { + @Override + public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { + mProgressBar.setVisibility(View.GONE); + mLoadErrorLinearLayout.setVisibility(View.VISIBLE); + return false; + } + + @Override + public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { + mProgressBar.setVisibility(View.GONE); + return false; + } + }).override(Target.SIZE_ORIGINAL).into(mImageView); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.view_image_or_gif_activity, menu); + if (!isGif) + menu.findItem(R.id.action_set_wallpaper_view_image_or_gif_activity).setVisible(true); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + finish(); + return true; + case R.id.action_download_view_image_or_gif_activity: + if (isDownloading) { + return false; + } + + isDownloading = true; + + if (Build.VERSION.SDK_INT >= 23) { + if (ContextCompat.checkSelfPermission(this, + Manifest.permission.WRITE_EXTERNAL_STORAGE) + != PackageManager.PERMISSION_GRANTED) { + + // Permission is not granted + // No explanation needed; request the permission + ActivityCompat.requestPermissions(this, + new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, + PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); + } else { + // Permission has already been granted + mediaDownloader.download(mImageUrl, mImageFileName, this); + } + } else { + mediaDownloader.download(mImageUrl, mImageFileName, this); + } + + return true; + case R.id.action_share_view_image_or_gif_activity: + if (isGif) + shareGif(); + else + shareImage(); + return true; + case R.id.action_set_wallpaper_view_image_or_gif_activity: + if (!isGif) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + SetAsWallpaperBottomSheetFragment setAsWallpaperBottomSheetFragment = new SetAsWallpaperBottomSheetFragment(); + setAsWallpaperBottomSheetFragment.show(getSupportFragmentManager(), setAsWallpaperBottomSheetFragment.getTag()); + } else { + wallpaperSetter.set(mImageUrl, WallpaperSetter.BOTH_SCREENS, this); + } + } + return true; + } + + return false; + } + + private void shareImage() { + glide.asBitmap().load(mImageUrl).into(new CustomTarget() { + + @Override + public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) { + if (getExternalCacheDir() != null) { + Toast.makeText(ViewImageOrGifActivity.this, R.string.save_image_first, Toast.LENGTH_SHORT).show(); + new SaveImageToFileAsyncTask(resource, getExternalCacheDir().getPath(), mImageFileName, + new SaveImageToFileAsyncTask.SaveImageToFileAsyncTaskListener() { + @Override + public void saveSuccess(File imageFile) { + Uri uri = FileProvider.getUriForFile(ViewImageOrGifActivity.this, + BuildConfig.APPLICATION_ID + ".provider", imageFile); + Intent shareIntent = new Intent(); + shareIntent.setAction(Intent.ACTION_SEND); + shareIntent.putExtra(Intent.EXTRA_STREAM, uri); + shareIntent.setType("image/*"); + shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + startActivity(Intent.createChooser(shareIntent, getString(R.string.share))); + } + + @Override + public void saveFailed() { + Toast.makeText(ViewImageOrGifActivity.this, + R.string.cannot_save_image, Toast.LENGTH_SHORT).show(); + } + }).execute(); + } else { + Toast.makeText(ViewImageOrGifActivity.this, + R.string.cannot_get_storage, Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onLoadCleared(@Nullable Drawable placeholder) { + + } + }); + } + + private void shareGif() { + Toast.makeText(ViewImageOrGifActivity.this, R.string.save_gif_first, Toast.LENGTH_SHORT).show(); + glide.asGif().load(mImageUrl).listener(new RequestListener() { + @Override + public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { + return false; + } + + @Override + public boolean onResourceReady(GifDrawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { + if (getExternalCacheDir() != null) { + new SaveGIFToFileAsyncTask(resource, getExternalCacheDir().getPath(), mImageFileName, + new SaveGIFToFileAsyncTask.SaveGIFToFileAsyncTaskListener() { + @Override + public void saveSuccess(File imageFile) { + Uri uri = FileProvider.getUriForFile(ViewImageOrGifActivity.this, + BuildConfig.APPLICATION_ID + ".provider", imageFile); + Intent shareIntent = new Intent(); + shareIntent.setAction(Intent.ACTION_SEND); + shareIntent.putExtra(Intent.EXTRA_STREAM, uri); + shareIntent.setType("image/*"); + shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + startActivity(Intent.createChooser(shareIntent, getString(R.string.share))); + } + + @Override + public void saveFailed() { + Toast.makeText(ViewImageOrGifActivity.this, + R.string.cannot_save_gif, Toast.LENGTH_SHORT).show(); + } + }).execute(); + } else { + Toast.makeText(ViewImageOrGifActivity.this, + R.string.cannot_get_storage, Toast.LENGTH_SHORT).show(); + } + return false; + } + }).submit(); + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) { + if (grantResults[0] == PackageManager.PERMISSION_DENIED) { + Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show(); + } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED && isDownloading) { + mediaDownloader.download(mImageUrl, mImageFileName, this); + } + isDownloading = false; + } + } + + @Override + public void setToHomeScreen(int viewPagerPosition) { + wallpaperSetter.set(mImageUrl, WallpaperSetter.HOME_SCREEN, this); + } + + @Override + public void setToLockScreen(int viewPagerPosition) { + wallpaperSetter.set(mImageUrl, WallpaperSetter.LOCK_SCREEN, this); + } + + @Override + public void setToBoth(int viewPagerPosition) { + wallpaperSetter.set(mImageUrl, WallpaperSetter.BOTH_SCREENS, this); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImgurMediaActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImgurMediaActivity.java index e5fba668..bf56ffac 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImgurMediaActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewImgurMediaActivity.java @@ -1,27 +1,17 @@ package ml.docilealligator.infinityforreddit.Activity; -import android.app.WallpaperManager; -import android.content.Context; import android.content.SharedPreferences; -import android.graphics.Bitmap; -import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; -import android.media.ThumbnailUtils; import android.os.AsyncTask; -import android.os.Build; import android.os.Bundle; -import android.util.DisplayMetrics; import android.view.Menu; import android.view.MenuItem; import android.view.View; -import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.ProgressBar; -import android.widget.Toast; import androidx.annotation.NonNull; -import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; @@ -29,9 +19,6 @@ import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.viewpager.widget.ViewPager; -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.target.CustomTarget; -import com.bumptech.glide.request.transition.Transition; import com.thefuntasty.hauler.DragDirection; import com.thefuntasty.hauler.HaulerView; @@ -39,7 +26,6 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import java.io.IOException; import java.util.ArrayList; import javax.inject.Inject; @@ -63,6 +49,7 @@ import ml.docilealligator.infinityforreddit.SetAsWallpaperCallback; import ml.docilealligator.infinityforreddit.Utils.APIUtils; import ml.docilealligator.infinityforreddit.Utils.JSONUtils; import ml.docilealligator.infinityforreddit.Utils.SharedPreferencesUtils; +import ml.docilealligator.infinityforreddit.WallpaperSetter; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; @@ -93,6 +80,7 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa @Inject @Named("default") SharedPreferences sharedPreferences; + private WallpaperSetter wallpaperSetter; @Override protected void onCreate(Bundle savedInstanceState) { @@ -129,6 +117,8 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa actionBar.setHomeAsUpIndicator(upArrow); actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparentActionBarAndExoPlayerControllerColor))); + wallpaperSetter = new WallpaperSetter(); + setTitle(" "); String imgurId = getIntent().getStringExtra(EXTRA_IMGUR_ID); @@ -154,9 +144,7 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa setupViewPager(); } - errorLinearLayout.setOnClickListener(view -> { - fetchImgurMedia(imgurId); - }); + errorLinearLayout.setOnClickListener(view -> fetchImgurMedia(imgurId)); } private void fetchImgurMedia(String imgurId) { @@ -322,89 +310,24 @@ public class ViewImgurMediaActivity extends AppCompatActivity implements SetAsWa outState.putParcelableArrayList(IMGUR_IMAGES_STATE, images); } - public void setAsWallpaper(String link, int setTo) { - Toast.makeText(ViewImgurMediaActivity.this, R.string.save_image_first, Toast.LENGTH_SHORT).show(); - Glide.with(this).asBitmap().load(link).into(new CustomTarget() { - @Override - public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) { - WallpaperManager manager = WallpaperManager.getInstance(ViewImgurMediaActivity.this); - - DisplayMetrics metrics = new DisplayMetrics(); - WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); - - Rect rect = null; - - if (windowManager != null) { - windowManager.getDefaultDisplay().getMetrics(metrics); - int height = metrics.heightPixels; - int width = metrics.widthPixels; - - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { - resource = ThumbnailUtils.extractThumbnail(resource, width, height); - } - - float imageAR = (float) resource.getWidth() / (float) resource.getHeight(); - float screenAR = (float) width / (float) height; - - if (imageAR > screenAR) { - int desiredWidth = (int) (resource.getHeight() * screenAR); - rect = new Rect((resource.getWidth() - desiredWidth) / 2, 0, resource.getWidth(), resource.getHeight()); - } else { - int desiredHeight = (int) (resource.getWidth() / screenAR); - rect = new Rect(0, (resource.getHeight() - desiredHeight) / 2, resource.getWidth(), (resource.getHeight() + desiredHeight) / 2); - } - } - try { - switch (setTo) { - case 0: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - manager.setBitmap(resource, rect, true, WallpaperManager.FLAG_SYSTEM); - } - break; - case 1: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - manager.setBitmap(resource, rect, true, WallpaperManager.FLAG_LOCK); - } - break; - case 2: - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - manager.setBitmap(resource, rect, true, WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK); - } else { - manager.setBitmap(resource); - } - break; - } - Toast.makeText(ViewImgurMediaActivity.this, R.string.wallpaper_set, Toast.LENGTH_SHORT).show(); - } catch (IOException e) { - Toast.makeText(ViewImgurMediaActivity.this, R.string.error_set_wallpaper, Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void onLoadCleared(@Nullable Drawable placeholder) { - - } - }); - } - @Override public void setToHomeScreen(int viewPagerPosition) { if (images != null && viewPagerPosition >= 0 && viewPagerPosition < images.size()) { - setAsWallpaper(images.get(viewPagerPosition).getLink(), 0); + wallpaperSetter.set(images.get(viewPagerPosition).getLink(), WallpaperSetter.HOME_SCREEN, this); } } @Override public void setToLockScreen(int viewPagerPosition) { if (images != null && viewPagerPosition >= 0 && viewPagerPosition < images.size()) { - setAsWallpaper(images.get(viewPagerPosition).getLink(), 1); + wallpaperSetter.set(images.get(viewPagerPosition).getLink(), WallpaperSetter.LOCK_SCREEN, this); } } @Override public void setToBoth(int viewPagerPosition) { if (images != null && viewPagerPosition >= 0 && viewPagerPosition < images.size()) { - setAsWallpaper(images.get(viewPagerPosition).getLink(), 2); + wallpaperSetter.set(images.get(viewPagerPosition).getLink(), WallpaperSetter.BOTH_SCREENS, this); } } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSubredditDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSubredditDetailActivity.java index d1b34c1c..1accdeec 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSubredditDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewSubredditDetailActivity.java @@ -349,9 +349,9 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp } else { glide.load(subredditData.getBannerUrl()).into(bannerImageView); bannerImageView.setOnClickListener(view -> { - Intent intent = new Intent(ViewSubredditDetailActivity.this, ViewImageActivity.class); - intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, subredditData.getBannerUrl()); - intent.putExtra(ViewImageActivity.FILE_NAME_KEY, subredditName + "-banner.jpg"); + Intent intent = new Intent(ViewSubredditDetailActivity.this, ViewImageOrGifActivity.class); + intent.putExtra(ViewImageOrGifActivity.IMAGE_URL_KEY, subredditData.getBannerUrl()); + intent.putExtra(ViewImageOrGifActivity.FILE_NAME_KEY, subredditName + "-banner.jpg"); startActivity(intent); }); } @@ -370,9 +370,9 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(216, 0)))) .into(iconGifImageView); iconGifImageView.setOnClickListener(view -> { - Intent intent = new Intent(ViewSubredditDetailActivity.this, ViewImageActivity.class); - intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, subredditData.getIconUrl()); - intent.putExtra(ViewImageActivity.FILE_NAME_KEY, subredditName + "-icon.jpg"); + Intent intent = new Intent(ViewSubredditDetailActivity.this, ViewImageOrGifActivity.class); + intent.putExtra(ViewImageOrGifActivity.IMAGE_URL_KEY, subredditData.getIconUrl()); + intent.putExtra(ViewImageOrGifActivity.FILE_NAME_KEY, subredditName + "-icon.jpg"); startActivity(intent); }); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewUserDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewUserDetailActivity.java index a72c7389..fd120df2 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewUserDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewUserDetailActivity.java @@ -295,9 +295,9 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele } else { glide.load(userData.getBanner()).into(bannerImageView); bannerImageView.setOnClickListener(view -> { - Intent intent = new Intent(this, ViewImageActivity.class); - intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, userData.getBanner()); - intent.putExtra(ViewImageActivity.FILE_NAME_KEY, username + "-banner.jpg"); + Intent intent = new Intent(this, ViewImageOrGifActivity.class); + intent.putExtra(ViewImageOrGifActivity.IMAGE_URL_KEY, userData.getBanner()); + intent.putExtra(ViewImageOrGifActivity.FILE_NAME_KEY, username + "-banner.jpg"); startActivity(intent); }); } @@ -315,9 +315,9 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele .into(iconGifImageView); iconGifImageView.setOnClickListener(view -> { - Intent intent = new Intent(this, ViewImageActivity.class); - intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, userData.getIconUrl()); - intent.putExtra(ViewImageActivity.FILE_NAME_KEY, username + "-icon.jpg"); + Intent intent = new Intent(this, ViewImageOrGifActivity.class); + intent.putExtra(ViewImageOrGifActivity.IMAGE_URL_KEY, userData.getIconUrl()); + intent.putExtra(ViewImageOrGifActivity.FILE_NAME_KEY, username + "-icon.jpg"); startActivity(intent); }); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewVideoActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewVideoActivity.java index dad6ff0c..601920d4 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewVideoActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Activity/ViewVideoActivity.java @@ -1,8 +1,6 @@ package ml.docilealligator.infinityforreddit.Activity; import android.Manifest; -import android.app.DownloadManager; -import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; @@ -13,7 +11,6 @@ import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; -import android.os.Environment; import android.text.Html; import android.view.Menu; import android.view.MenuItem; @@ -50,8 +47,6 @@ import com.google.android.exoplayer2.util.Util; import com.thefuntasty.hauler.DragDirection; import com.thefuntasty.hauler.HaulerView; -import java.io.File; - import javax.inject.Inject; import javax.inject.Named; @@ -62,6 +57,8 @@ import ml.docilealligator.infinityforreddit.Font.ContentFontFamily; import ml.docilealligator.infinityforreddit.Font.FontFamily; import ml.docilealligator.infinityforreddit.Font.TitleFontFamily; import ml.docilealligator.infinityforreddit.Infinity; +import ml.docilealligator.infinityforreddit.MediaDownloader; +import ml.docilealligator.infinityforreddit.MediaDownloaderImpl; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.Service.DownloadRedditVideoService; import ml.docilealligator.infinityforreddit.Utils.SharedPreferencesUtils; @@ -96,6 +93,7 @@ public class ViewVideoActivity extends AppCompatActivity { private Uri mVideoUri; private SimpleExoPlayer player; private DataSource.Factory dataSourceFactory; + private MediaDownloader mediaDownloader; private String videoDownloadUrl; private String videoFileName; @@ -167,6 +165,8 @@ public class ViewVideoActivity extends AppCompatActivity { overridePendingTransition(0, slide); }); + mediaDownloader = new MediaDownloaderImpl(); + Intent intent = getIntent(); mVideoUri = intent.getData(); postTitle = intent.getStringExtra(EXTRA_POST_TITLE); @@ -412,46 +412,7 @@ public class ViewVideoActivity extends AppCompatActivity { isDownloading = false; if (videoType != VIDEO_TYPE_NORMAL) { - DownloadManager.Request request = new DownloadManager.Request(Uri.parse(videoDownloadUrl)); - request.setTitle(videoFileName); - - request.allowScanningByMediaScanner(); - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - - //Android Q support - if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, videoFileName); - } else { - String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString(); - File directory = new File(path + "/Infinity/"); - boolean saveToInfinityFolder = true; - if (!directory.exists()) { - if (!directory.mkdir()) { - saveToInfinityFolder = false; - } - } else { - if (directory.isFile()) { - if (!(directory.delete() && directory.mkdir())) { - saveToInfinityFolder = false; - } - } - } - - if (saveToInfinityFolder) { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES + "/Infinity/", videoFileName); - } else { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, videoFileName); - } - } - - DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); - - if (manager == null) { - Toast.makeText(this, R.string.download_failed, Toast.LENGTH_SHORT).show(); - return; - } - - manager.enqueue(request); + mediaDownloader.download(videoDownloadUrl, videoFileName, this); } else { Intent intent = new Intent(this, DownloadRedditVideoService.class); intent.putExtra(DownloadRedditVideoService.EXTRA_VIDEO_URL, videoDownloadUrl); @@ -463,8 +424,8 @@ public class ViewVideoActivity extends AppCompatActivity { } else { startService(intent); } + Toast.makeText(this, R.string.download_started, Toast.LENGTH_SHORT).show(); } - Toast.makeText(this, R.string.download_started, Toast.LENGTH_SHORT).show(); } @Override diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Adapter/CommentAndPostRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Adapter/CommentAndPostRecyclerViewAdapter.java index c7984bfb..0510fae6 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Adapter/CommentAndPostRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Adapter/CommentAndPostRecyclerViewAdapter.java @@ -81,8 +81,7 @@ import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import ml.docilealligator.infinityforreddit.Activity.CommentActivity; import ml.docilealligator.infinityforreddit.Activity.FilteredThingActivity; import ml.docilealligator.infinityforreddit.Activity.LinkResolverActivity; -import ml.docilealligator.infinityforreddit.Activity.ViewGIFActivity; -import ml.docilealligator.infinityforreddit.Activity.ViewImageActivity; +import ml.docilealligator.infinityforreddit.Activity.ViewImageOrGifActivity; import ml.docilealligator.infinityforreddit.Activity.ViewPostDetailActivity; import ml.docilealligator.infinityforreddit.Activity.ViewSubredditDetailActivity; import ml.docilealligator.infinityforreddit.Activity.ViewUserDetailActivity; @@ -307,7 +306,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter { int commentPosition = mIsSingleCommentThreadMode ? holder.getAdapterPosition() - 2 : holder.getAdapterPosition() - 1; int parentPosition = getParentPosition(commentPosition); - if(parentPosition >= 0) { + if (parentPosition >= 0) { CommentData parentComment = mVisibleComments.get(parentPosition); mVisibleComments.get(commentPosition).setLoadingMoreChildren(true); @@ -1172,7 +1171,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter imageRequestBuilder = mGlide.load(mPost.getPreviewUrl()) .listener(new RequestListener() { @Override @@ -2255,11 +2254,11 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter { if (mPost.getPostType() == Post.IMAGE_TYPE) { - Intent intent = new Intent(mActivity, ViewImageActivity.class); - intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, mPost.getUrl()); - intent.putExtra(ViewImageActivity.FILE_NAME_KEY, mPost.getSubredditNamePrefixed().substring(2) + Intent intent = new Intent(mActivity, ViewImageOrGifActivity.class); + intent.putExtra(ViewImageOrGifActivity.IMAGE_URL_KEY, mPost.getUrl()); + intent.putExtra(ViewImageOrGifActivity.FILE_NAME_KEY, mPost.getSubredditNamePrefixed().substring(2) + "-" + mPost.getId().substring(3) + ".jpg"); - intent.putExtra(ViewImageActivity.POST_TITLE_KEY, mPost.getTitle()); + intent.putExtra(ViewImageOrGifActivity.POST_TITLE_KEY, mPost.getTitle()); mActivity.startActivity(intent); } else if (mPost.getPostType() == Post.GIF_TYPE) { - Intent intent = new Intent(mActivity, ViewGIFActivity.class); - intent.putExtra(ViewGIFActivity.FILE_NAME_KEY, mPost.getSubredditName() + Intent intent = new Intent(mActivity, ViewImageOrGifActivity.class); + intent.putExtra(ViewImageOrGifActivity.FILE_NAME_KEY, mPost.getSubredditName() + "-" + mPost.getId() + ".gif"); - intent.putExtra(ViewGIFActivity.GIF_URL_KEY, mPost.getVideoUrl()); - intent.putExtra(ViewImageActivity.POST_TITLE_KEY, mPost.getTitle()); + intent.putExtra(ViewImageOrGifActivity.GIF_URL_KEY, mPost.getVideoUrl()); + intent.putExtra(ViewImageOrGifActivity.POST_TITLE_KEY, mPost.getTitle()); mActivity.startActivity(intent); } }); @@ -2934,7 +2933,7 @@ public class CommentAndPostRecyclerViewAdapter extends RecyclerView.Adapter { if (expandButton.getVisibility() == View.VISIBLE) { int commentPosition = mIsSingleCommentThreadMode ? getAdapterPosition() - 2 : getAdapterPosition() - 1; - if(commentPosition >= 0 && commentPosition < mVisibleComments.size()) { + if (commentPosition >= 0 && commentPosition < mVisibleComments.size()) { CommentData comment = getCurrentComment(); if (mVisibleComments.get(commentPosition).isExpanded()) { collapseChildren(commentPosition); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Adapter/PostRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Adapter/PostRecyclerViewAdapter.java index e54a0eea..a7af4e11 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Adapter/PostRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Adapter/PostRecyclerViewAdapter.java @@ -65,8 +65,7 @@ import jp.wasabeef.glide.transformations.BlurTransformation; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import ml.docilealligator.infinityforreddit.Activity.FilteredThingActivity; import ml.docilealligator.infinityforreddit.Activity.LinkResolverActivity; -import ml.docilealligator.infinityforreddit.Activity.ViewGIFActivity; -import ml.docilealligator.infinityforreddit.Activity.ViewImageActivity; +import ml.docilealligator.infinityforreddit.Activity.ViewImageOrGifActivity; import ml.docilealligator.infinityforreddit.Activity.ViewPostDetailActivity; import ml.docilealligator.infinityforreddit.Activity.ViewSubredditDetailActivity; import ml.docilealligator.infinityforreddit.Activity.ViewUserDetailActivity; @@ -836,9 +835,9 @@ public class PostRecyclerViewAdapter extends PagedListAdapter { - Intent intent = new Intent(mActivity, ViewImageActivity.class); - intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, imageUrl); - intent.putExtra(ViewImageActivity.FILE_NAME_KEY, subredditName + Intent intent = new Intent(mActivity, ViewImageOrGifActivity.class); + intent.putExtra(ViewImageOrGifActivity.IMAGE_URL_KEY, imageUrl); + intent.putExtra(ViewImageOrGifActivity.FILE_NAME_KEY, subredditName + "-" + id + ".jpg"); mActivity.startActivity(intent); }); @@ -866,11 +865,11 @@ public class PostRecyclerViewAdapter extends PagedListAdapter { - Intent intent = new Intent(mActivity, ViewGIFActivity.class); + Intent intent = new Intent(mActivity, ViewImageOrGifActivity.class); intent.setData(gifVideoUri); - intent.putExtra(ViewGIFActivity.FILE_NAME_KEY, subredditName + intent.putExtra(ViewImageOrGifActivity.FILE_NAME_KEY, subredditName + "-" + id + ".gif"); - intent.putExtra(ViewGIFActivity.GIF_URL_KEY, post.getVideoUrl()); + intent.putExtra(ViewImageOrGifActivity.GIF_URL_KEY, post.getVideoUrl()); mActivity.startActivity(intent); }); @@ -1209,18 +1208,18 @@ public class PostRecyclerViewAdapter extends PagedListAdapter imageRequestBuilder = mGlide.load(previewUrl) .error(R.drawable.ic_error_outline_black_24dp).listener(new RequestListener() { - @Override - public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - ((PostCompactViewHolder) holder).progressBar.setVisibility(View.GONE); - return false; - } + @Override + public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { + ((PostCompactViewHolder) holder).progressBar.setVisibility(View.GONE); + return false; + } - @Override - public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { - ((PostCompactViewHolder) holder).progressBar.setVisibility(View.GONE); - return false; - } - }); + @Override + public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { + ((PostCompactViewHolder) holder).progressBar.setVisibility(View.GONE); + return false; + } + }); if ((post.isNSFW() && mNeedBlurNSFW) || post.isSpoiler() && mNeedBlurSpoiler) { imageRequestBuilder .transform(new BlurTransformation(50, 2)) @@ -1310,7 +1309,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter { + + private Bitmap bitmap; + private int setTo; + private WallpaperManager manager; + private WindowManager windowManager; + private SetAsWallpaperAsyncTaskListener setAsWallpaperAsyncTaskListener; + private boolean success = true; + + public SetAsWallpaperAsyncTask(Bitmap bitmap, int setTo, WallpaperManager manager, WindowManager windowManager, + SetAsWallpaperAsyncTaskListener setAsWallpaperAsyncTaskListener) { + this.bitmap = bitmap; + this.setTo = setTo; + this.manager = manager; + this.windowManager = windowManager; + this.setAsWallpaperAsyncTaskListener = setAsWallpaperAsyncTaskListener; + } + + public interface SetAsWallpaperAsyncTaskListener { + void success(); + void failed(); + } + + @Override + protected Void doInBackground(Void... voids) { + DisplayMetrics metrics = new DisplayMetrics(); + Rect rect = null; + + if (windowManager != null) { + windowManager.getDefaultDisplay().getMetrics(metrics); + int height = metrics.heightPixels; + int width = metrics.widthPixels; + + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { + bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height); + } + + float imageAR = (float) bitmap.getWidth() / (float) bitmap.getHeight(); + float screenAR = (float) width / (float) height; + + if (imageAR > screenAR) { + int desiredWidth = (int) (bitmap.getHeight() * screenAR); + rect = new Rect((bitmap.getWidth() - desiredWidth) / 2, 0, bitmap.getWidth(), bitmap.getHeight()); + } else { + int desiredHeight = (int) (bitmap.getWidth() / screenAR); + rect = new Rect(0, (bitmap.getHeight() - desiredHeight) / 2, bitmap.getWidth(), (bitmap.getHeight() + desiredHeight) / 2); + } + } + try { + switch (setTo) { + case 0: + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + manager.setBitmap(bitmap, rect, true, WallpaperManager.FLAG_SYSTEM); + } + break; + case 1: + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + manager.setBitmap(bitmap, rect, true, WallpaperManager.FLAG_LOCK); + } + break; + case 2: + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + manager.setBitmap(bitmap, rect, true, WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK); + } else { + manager.setBitmap(bitmap); + } + break; + } + } catch (IOException e) { + success = false; + } + + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + if (success) { + setAsWallpaperAsyncTaskListener.success(); + } else { + setAsWallpaperAsyncTaskListener.failed(); + } + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/ViewImgurImageFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/ViewImgurImageFragment.java index 99ebd248..8d761757 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/ViewImgurImageFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/ViewImgurImageFragment.java @@ -1,7 +1,6 @@ package ml.docilealligator.infinityforreddit.Fragment; import android.Manifest; -import android.app.DownloadManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; @@ -10,7 +9,6 @@ import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; -import android.os.Environment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; @@ -47,7 +45,10 @@ import ml.docilealligator.infinityforreddit.AsyncTask.SaveImageToFileAsyncTask; import ml.docilealligator.infinityforreddit.BottomSheetFragment.SetAsWallpaperBottomSheetFragment; import ml.docilealligator.infinityforreddit.BuildConfig; import ml.docilealligator.infinityforreddit.ImgurMedia; +import ml.docilealligator.infinityforreddit.MediaDownloader; +import ml.docilealligator.infinityforreddit.MediaDownloaderImpl; import ml.docilealligator.infinityforreddit.R; +import ml.docilealligator.infinityforreddit.SetAsWallpaperCallback; public class ViewImgurImageFragment extends Fragment { @@ -63,6 +64,7 @@ public class ViewImgurImageFragment extends Fragment { private ViewImgurMediaActivity activity; private RequestManager glide; + private MediaDownloader mediaDownloader; private ImgurMedia imgurMedia; private boolean isDownloading = false; @@ -81,6 +83,7 @@ public class ViewImgurImageFragment extends Fragment { imgurMedia = getArguments().getParcelable(EXTRA_IMGUR_IMAGES); glide = Glide.with(activity); + mediaDownloader = new MediaDownloaderImpl(); loadImage(); return rootView; @@ -131,10 +134,10 @@ public class ViewImgurImageFragment extends Fragment { PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); } else { // Permission has already been granted - download(); + mediaDownloader.download(imgurMedia.getLink(), imgurMedia.getFileName(), getContext()); } } else { - download(); + mediaDownloader.download(imgurMedia.getLink(), imgurMedia.getFileName(), getContext()); } return true; @@ -151,7 +154,7 @@ public class ViewImgurImageFragment extends Fragment { @Override public void saveSuccess(File imageFile) { Uri uri = FileProvider.getUriForFile(activity, - BuildConfig.APPLICATION_ID + ".provider",imageFile); + BuildConfig.APPLICATION_ID + ".provider", imageFile); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uri); @@ -186,7 +189,7 @@ public class ViewImgurImageFragment extends Fragment { setAsWallpaperBottomSheetFragment.setArguments(bundle); setAsWallpaperBottomSheetFragment.show(activity.getSupportFragmentManager(), setAsWallpaperBottomSheetFragment.getTag()); } else { - activity.setAsWallpaper(imgurMedia.getLink(), 2); + ((SetAsWallpaperCallback) activity).setToBoth(activity.getCurrentPagePosition()); } return true; } @@ -200,56 +203,12 @@ public class ViewImgurImageFragment extends Fragment { if (grantResults[0] == PackageManager.PERMISSION_DENIED) { Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show(); } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED && isDownloading) { - download(); + mediaDownloader.download(imgurMedia.getLink(), imgurMedia.getFileName(), getContext()); } isDownloading = false; } } - private void download() { - DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imgurMedia.getLink())); - request.setTitle(imgurMedia.getFileName()); - - request.allowScanningByMediaScanner(); - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - - //Android Q support - if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, imgurMedia.getFileName()); - } else { - String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString(); - File directory = new File(path + "/Infinity/"); - boolean saveToInfinityFolder = true; - if (!directory.exists()) { - if (!directory.mkdir()) { - saveToInfinityFolder = false; - } - } else { - if (directory.isFile()) { - if (!(directory.delete() && directory.mkdir())) { - saveToInfinityFolder = false; - } - } - } - - if (saveToInfinityFolder) { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES + "/Infinity/", imgurMedia.getFileName()); - } else { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, imgurMedia.getFileName()); - } - } - - DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE); - - if (manager == null) { - Toast.makeText(activity, R.string.download_failed, Toast.LENGTH_SHORT).show(); - return; - } - - manager.enqueue(request); - Toast.makeText(activity, R.string.download_started, Toast.LENGTH_SHORT).show(); - } - @Override public void onAttach(@NonNull Context context) { super.onAttach(context); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/ViewImgurVideoFragment.java b/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/ViewImgurVideoFragment.java index 3ec6eb39..dd3853d0 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/ViewImgurVideoFragment.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/Fragment/ViewImgurVideoFragment.java @@ -2,7 +2,6 @@ package ml.docilealligator.infinityforreddit.Fragment; import android.Manifest; import android.app.Activity; -import android.app.DownloadManager; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; @@ -11,7 +10,6 @@ import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; -import android.os.Environment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; @@ -42,8 +40,6 @@ import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.util.Util; -import java.io.File; - import javax.inject.Inject; import javax.inject.Named; @@ -51,6 +47,8 @@ import butterknife.BindView; import butterknife.ButterKnife; import ml.docilealligator.infinityforreddit.ImgurMedia; import ml.docilealligator.infinityforreddit.Infinity; +import ml.docilealligator.infinityforreddit.MediaDownloader; +import ml.docilealligator.infinityforreddit.MediaDownloaderImpl; import ml.docilealligator.infinityforreddit.R; import ml.docilealligator.infinityforreddit.Utils.SharedPreferencesUtils; @@ -71,6 +69,7 @@ public class ViewImgurVideoFragment extends Fragment { private ImgurMedia imgurMedia; private SimpleExoPlayer player; private DataSource.Factory dataSourceFactory; + private MediaDownloader mediaDownloader; private boolean wasPlaying = false; private boolean isMute = false; private boolean isDownloading = false; @@ -131,6 +130,8 @@ public class ViewImgurVideoFragment extends Fragment { } }); + mediaDownloader = new MediaDownloaderImpl(); + TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(); TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory); player = ExoPlayerFactory.newSimpleInstance(activity, trackSelector); @@ -190,47 +191,7 @@ public class ViewImgurVideoFragment extends Fragment { private void download() { isDownloading = false; - DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imgurMedia.getLink())); - request.setTitle(imgurMedia.getFileName()); - - request.allowScanningByMediaScanner(); - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - - //Android Q support - if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, imgurMedia.getFileName()); - } else { - String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString(); - File directory = new File(path + "/Infinity/"); - boolean saveToInfinityFolder = true; - if (!directory.exists()) { - if (!directory.mkdir()) { - saveToInfinityFolder = false; - } - } else { - if (directory.isFile()) { - if (!(directory.delete() && directory.mkdir())) { - saveToInfinityFolder = false; - } - } - } - - if (saveToInfinityFolder) { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES + "/Infinity/", imgurMedia.getFileName()); - } else { - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, imgurMedia.getFileName()); - } - } - - DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE); - - if (manager == null) { - Toast.makeText(activity, R.string.download_failed, Toast.LENGTH_SHORT).show(); - return; - } - - manager.enqueue(request); - Toast.makeText(activity, R.string.download_started, Toast.LENGTH_SHORT).show(); + mediaDownloader.download(imgurMedia.getLink(), imgurMedia.getFileName(), getContext()); } private void preparePlayer(Bundle savedInstanceState) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/MediaDownloader.java b/app/src/main/java/ml/docilealligator/infinityforreddit/MediaDownloader.java new file mode 100644 index 00000000..9967a6a4 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/MediaDownloader.java @@ -0,0 +1,7 @@ +package ml.docilealligator.infinityforreddit; + +import android.content.Context; + +public interface MediaDownloader { + void download(String url, String fileName, Context ctx); +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/MediaDownloaderImpl.java b/app/src/main/java/ml/docilealligator/infinityforreddit/MediaDownloaderImpl.java new file mode 100644 index 00000000..638bdf93 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/MediaDownloaderImpl.java @@ -0,0 +1,58 @@ +package ml.docilealligator.infinityforreddit; + +import android.app.DownloadManager; +import android.content.Context; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.widget.Toast; + +import java.io.File; + +public class MediaDownloaderImpl implements MediaDownloader { + + @Override + public void download(String url, String fileName, Context ctx) { + DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); + request.setTitle(fileName); + + request.allowScanningByMediaScanner(); + request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); + + //Android Q support + if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, fileName); + } else { + String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString(); + File directory = new File(path + "/Infinity/"); + boolean saveToInfinityFolder = true; + if (!directory.exists()) { + if (!directory.mkdir()) { + saveToInfinityFolder = false; + } + } else { + if (directory.isFile()) { + if (!(directory.delete() && directory.mkdir())) { + saveToInfinityFolder = false; + } + } + } + + if (saveToInfinityFolder) { + request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES + "/Infinity/", fileName); + } else { + request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, fileName); + } + } + + DownloadManager manager = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE); + + if (manager == null) { + Toast.makeText(ctx, R.string.download_failed, Toast.LENGTH_SHORT).show(); + return; + } + + manager.enqueue(request); + Toast.makeText(ctx, R.string.download_started, Toast.LENGTH_SHORT).show(); + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/WallpaperSetter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/WallpaperSetter.java new file mode 100644 index 00000000..58884997 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/WallpaperSetter.java @@ -0,0 +1,92 @@ +package ml.docilealligator.infinityforreddit; + +import android.app.WallpaperManager; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.media.ThumbnailUtils; +import android.os.Build; +import android.util.DisplayMetrics; +import android.view.WindowManager; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import com.bumptech.glide.Glide; +import com.bumptech.glide.request.target.CustomTarget; +import com.bumptech.glide.request.transition.Transition; + +import java.io.IOException; + +public class WallpaperSetter { + public static final int HOME_SCREEN = 0; + public static final int LOCK_SCREEN = 1; + public static final int BOTH_SCREENS = 2; + + public void set(String url, int setTo, Context ctx) { + Toast.makeText(ctx, R.string.save_image_first, Toast.LENGTH_SHORT).show(); + Glide.with(ctx).asBitmap().load(url).into(new CustomTarget() { + @Override + public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) { + WallpaperManager manager = WallpaperManager.getInstance(ctx); + + DisplayMetrics metrics = new DisplayMetrics(); + WindowManager windowManager = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); + + Rect rect = null; + + if (windowManager != null) { + windowManager.getDefaultDisplay().getMetrics(metrics); + int height = metrics.heightPixels; + int width = metrics.widthPixels; + + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { + resource = ThumbnailUtils.extractThumbnail(resource, width, height); + } + + float imageAR = (float) resource.getWidth() / (float) resource.getHeight(); + float screenAR = (float) width / (float) height; + + if (imageAR > screenAR) { + int desiredWidth = (int) (resource.getHeight() * screenAR); + rect = new Rect((resource.getWidth() - desiredWidth) / 2, 0, resource.getWidth(), resource.getHeight()); + } else { + int desiredHeight = (int) (resource.getWidth() / screenAR); + rect = new Rect(0, (resource.getHeight() - desiredHeight) / 2, resource.getWidth(), (resource.getHeight() + desiredHeight) / 2); + } + } + try { + switch (setTo) { + case HOME_SCREEN: + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + manager.setBitmap(resource, rect, true, WallpaperManager.FLAG_SYSTEM); + } + break; + case LOCK_SCREEN: + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + manager.setBitmap(resource, rect, true, WallpaperManager.FLAG_LOCK); + } + break; + case BOTH_SCREENS: + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + manager.setBitmap(resource, rect, true, WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK); + } else { + manager.setBitmap(resource); + } + break; + } + Toast.makeText(ctx, R.string.wallpaper_set, Toast.LENGTH_SHORT).show(); + } catch (IOException e) { + Toast.makeText(ctx, R.string.error_set_wallpaper, Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onLoadCleared(@Nullable Drawable placeholder) { + + } + }); + } +} -- cgit v1.2.3