Browse Source

Add widget

widgets
Apostolos Fanakis 5 years ago
parent
commit
68508d713e
  1. 11
      app/src/main/AndroidManifest.xml
  2. 93
      app/src/main/java/gr/thmmy/mthmmy/activities/bookmarks/BookmarksActivity.java
  3. 25
      app/src/main/java/gr/thmmy/mthmmy/activities/bookmarks/BookmarksFragment.java
  4. 103
      app/src/main/java/gr/thmmy/mthmmy/activities/widget/WidgetProvider.java
  5. 10
      app/src/main/java/gr/thmmy/mthmmy/model/Bookmark.java
  6. 2
      app/src/main/java/gr/thmmy/mthmmy/session/SessionManager.java
  7. 38
      app/src/main/res/layout/widget.xml
  8. 3
      app/src/main/res/values/strings.xml
  9. 10
      app/src/main/res/xml/widget_info.xml

11
app/src/main/AndroidManifest.xml

@ -133,6 +133,9 @@
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.main.MainActivity" />
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
<activity
android:name=".activities.settings.SettingsActivity"
@ -170,6 +173,14 @@
</intent-filter>
</receiver>
<receiver android:name=".activities.widget.WidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget_info" />
</receiver>
<activity
android:name=".activities.create_content.CreateContentActivity"
android:configChanges="orientation|screenSize"

93
app/src/main/java/gr/thmmy/mthmmy/activities/bookmarks/BookmarksActivity.java

@ -1,9 +1,13 @@
package gr.thmmy.mthmmy.activities.bookmarks;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
@ -18,6 +22,7 @@ import java.util.List;
import gr.thmmy.mthmmy.R;
import gr.thmmy.mthmmy.activities.board.BoardActivity;
import gr.thmmy.mthmmy.activities.topic.TopicActivity;
import gr.thmmy.mthmmy.activities.widget.WidgetProvider;
import gr.thmmy.mthmmy.base.BaseActivity;
import gr.thmmy.mthmmy.model.Bookmark;
@ -25,18 +30,44 @@ import static gr.thmmy.mthmmy.activities.board.BoardActivity.BUNDLE_BOARD_TITLE;
import static gr.thmmy.mthmmy.activities.board.BoardActivity.BUNDLE_BOARD_URL;
import static gr.thmmy.mthmmy.activities.topic.TopicActivity.BUNDLE_TOPIC_TITLE;
import static gr.thmmy.mthmmy.activities.topic.TopicActivity.BUNDLE_TOPIC_URL;
import static gr.thmmy.mthmmy.activities.widget.WidgetProvider.BOOKMARK_WIDGETS_KEY;
import static gr.thmmy.mthmmy.activities.widget.WidgetProvider.BOOKMARK_WIDGET_SHARED_PREFS;
import static gr.thmmy.mthmmy.session.SessionManager.boardUrl;
import static gr.thmmy.mthmmy.session.SessionManager.topicUrl;
//TODO proper handling with adapter etc.
//TODO after clicking bookmark and then back button should return to this activity
public class BookmarksActivity extends BaseActivity {
private static final String TOPIC_URL = "https://www.thmmy.gr/smf/index.php?topic=";
private static final String BOARD_URL = "https://www.thmmy.gr/smf/index.php?board=";
private boolean isCalledForWidgetSetup = false;
private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
isCalledForWidgetSetup = true;
// Finds the widget id from the intent.
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
// Sets the result to CANCELED. In case the activity is started from intent to setup a
// widget, this will cause the widget host to cancel out of the widget placement if they
// press the back button.
setResult(RESULT_CANCELED);
// If they gave us an intent without the widget id, just bail.
if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
}
setContentView(R.layout.activity_bookmarks);
if (!isCalledForWidgetSetup) {
//Initialize toolbar
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Bookmarks");
@ -48,11 +79,16 @@ public class BookmarksActivity extends BaseActivity {
createDrawer();
drawer.setSelection(BOOKMARKS_ID);
}
//Creates the adapter that will return a fragment for each section of the activity
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
sectionsPagerAdapter.addFragment(BookmarksFragment.newInstance(1, Bookmark.arrayListToString(getTopicsBookmarked()), BookmarksFragment.Type.TOPIC), "Topics");
sectionsPagerAdapter.addFragment(BookmarksFragment.newInstance(2, Bookmark.arrayListToString(getBoardsBookmarked()), BookmarksFragment.Type.BOARD), "Boards");
sectionsPagerAdapter.addFragment(BookmarksFragment.newInstance(1,
Bookmark.arrayListToString(getTopicsBookmarked()),
BookmarksFragment.Type.TOPIC, isCalledForWidgetSetup), "Topics");
sectionsPagerAdapter.addFragment(BookmarksFragment.newInstance(2,
Bookmark.arrayListToString(getBoardsBookmarked()),
BookmarksFragment.Type.BOARD, isCalledForWidgetSetup), "Boards");
//Sets up the ViewPager with the sections adapter.
ViewPager viewPager = findViewById(R.id.bookmarks_container);
@ -64,6 +100,7 @@ public class BookmarksActivity extends BaseActivity {
@Override
protected void onResume() {
if (drawer != null)
drawer.setSelection(BOOKMARKS_ID);
super.onResume();
}
@ -78,11 +115,18 @@ public class BookmarksActivity extends BaseActivity {
}
private boolean onTopicInteractionListener(String interactionType, Bookmark bookmarkedTopic) {
// Handles clicks during widget setups
if (isCalledForWidgetSetup) {
handleWidgetCreation(BookmarksFragment.Type.TOPIC, bookmarkedTopic);
return true;
}
// Default behavior
switch (interactionType) {
case BookmarksFragment.INTERACTION_CLICK_TOPIC_BOOKMARK:
Intent intent = new Intent(BookmarksActivity.this, TopicActivity.class);
Bundle extras = new Bundle();
extras.putString(BUNDLE_TOPIC_URL, TOPIC_URL
extras.putString(BUNDLE_TOPIC_URL, topicUrl
+ bookmarkedTopic.getId() + "." + 2147483647);
extras.putString(BUNDLE_TOPIC_TITLE, bookmarkedTopic.getTitle());
intent.putExtras(extras);
@ -101,11 +145,18 @@ public class BookmarksActivity extends BaseActivity {
}
private boolean onBoardInteractionListener(String interactionType, Bookmark bookmarkedBoard) {
// Handles clicks during widget setups
if (isCalledForWidgetSetup) {
handleWidgetCreation(BookmarksFragment.Type.BOARD, bookmarkedBoard);
return true;
}
// Default behavior
switch (interactionType) {
case BookmarksFragment.INTERACTION_CLICK_BOARD_BOOKMARK:
Intent intent = new Intent(BookmarksActivity.this, BoardActivity.class);
Bundle extras = new Bundle();
extras.putString(BUNDLE_BOARD_URL, BOARD_URL
extras.putString(BUNDLE_BOARD_URL, boardUrl
+ bookmarkedBoard.getId() + ".0");
extras.putString(BUNDLE_BOARD_TITLE, bookmarkedBoard.getTitle());
intent.putExtras(extras);
@ -123,6 +174,33 @@ public class BookmarksActivity extends BaseActivity {
return true;
}
private void handleWidgetCreation(BookmarksFragment.Type type, Bookmark bookmark) {
// Saves the bookmark in our prefs
SharedPreferences widgetSharedPrefs = getSharedPreferences(BOOKMARK_WIDGET_SHARED_PREFS, Context.MODE_PRIVATE);
ArrayList<Bookmark> tmpArrayList = new ArrayList<>();
tmpArrayList.add(bookmark);
SharedPreferences.Editor widgetSharedPrefsEditor = widgetSharedPrefs.edit();
if (type == BookmarksFragment.Type.TOPIC) {
widgetSharedPrefsEditor.putString(BOOKMARK_WIDGETS_KEY + "_t_" + mAppWidgetId, Bookmark.arrayListToString(tmpArrayList));
} else if (type == BookmarksFragment.Type.BOARD) {
widgetSharedPrefsEditor.putString(BOOKMARK_WIDGETS_KEY + "_b_" + mAppWidgetId, Bookmark.arrayListToString(tmpArrayList));
} else {
finish();
}
widgetSharedPrefsEditor.apply();
// Push widget update to surface
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
WidgetProvider.updateAppWidget(this, appWidgetManager, mAppWidgetId, 0); // Todo: check if there are already notifications available
// Make sure we pass back the original appWidgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages. If it becomes too memory intensive,
@ -143,6 +221,7 @@ public class BookmarksActivity extends BaseActivity {
notifyDataSetChanged();
}
@NonNull
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
@ -159,7 +238,7 @@ public class BookmarksActivity extends BaseActivity {
}
@Override
public int getItemPosition(Object object) {
public int getItemPosition(@NonNull Object object) {
@SuppressWarnings("RedundantCast")
int position = fragmentList.indexOf((Fragment) object);
return position == -1 ? POSITION_NONE : position;

25
app/src/main/java/gr/thmmy/mthmmy/activities/bookmarks/BookmarksFragment.java

@ -23,8 +23,10 @@ import gr.thmmy.mthmmy.model.Bookmark;
public class BookmarksFragment extends Fragment {
enum Type {TOPIC, BOARD}
private static final String ARG_SECTION_NUMBER = "SECTION_NUMBER";
private static final String ARG_BOOKMARKS = "BOOKMARKS";
private static final String ARG_CALL_FOR_WIDGET_SETUP = "ARG_CALL_FOR_WIDGET_SETUP";
static final String INTERACTION_CLICK_TOPIC_BOOKMARK = "CLICK_TOPIC_BOOKMARK";
static final String INTERACTION_TOGGLE_TOPIC_NOTIFICATION = "TOGGLE_TOPIC_NOTIFICATION";
@ -35,6 +37,7 @@ public class BookmarksFragment extends Fragment {
static final String INTERACTION_REMOVE_BOARD_BOOKMARK = "REMOVE_BOARD_BOOKMARK";
private ArrayList<Bookmark> bookmarks = null;
private boolean isCalledForWidgetSetup = false;
private Type type;
private String interactionClick, interactionToggle, interactionRemove;
@ -49,8 +52,7 @@ public class BookmarksFragment extends Fragment {
this.interactionClick = INTERACTION_CLICK_TOPIC_BOOKMARK;
this.interactionToggle = INTERACTION_TOGGLE_TOPIC_NOTIFICATION;
this.interactionRemove = INTERACTION_REMOVE_TOPIC_BOOKMARK;
}
else if (type==Type.BOARD){
} else if (type == Type.BOARD) {
this.interactionClick = INTERACTION_CLICK_BOARD_BOOKMARK;
this.interactionToggle = INTERACTION_TOGGLE_BOARD_NOTIFICATION;
this.interactionRemove = INTERACTION_REMOVE_BOARD_BOOKMARK;
@ -63,11 +65,13 @@ public class BookmarksFragment extends Fragment {
*
* @return A new instance of fragment Forum.
*/
protected static BookmarksFragment newInstance(int sectionNumber, String bookmarks, Type type) {
protected static BookmarksFragment newInstance(int sectionNumber, String bookmarks, Type type,
boolean isCalledForWidgetSetup) {
BookmarksFragment fragment = new BookmarksFragment(type);
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString(ARG_BOOKMARKS, bookmarks);
args.putBoolean(ARG_CALL_FOR_WIDGET_SETUP, isCalledForWidgetSetup);
fragment.setArguments(args);
return fragment;
}
@ -80,6 +84,7 @@ public class BookmarksFragment extends Fragment {
if (bundledBookmarks != null) {
bookmarks = Bookmark.stringToArrayList(bundledBookmarks);
}
isCalledForWidgetSetup = getArguments().getBoolean(ARG_CALL_FOR_WIDGET_SETUP, false);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
@ -114,6 +119,10 @@ public class BookmarksFragment extends Fragment {
((TextView) row.findViewById(R.id.bookmark_title)).setText(bookmark.getTitle());
final ImageButton notificationsEnabledButton = row.findViewById(R.id.toggle_notification);
if (isCalledForWidgetSetup) {
notificationsEnabledButton.setEnabled(false);
notificationsEnabledButton.setVisibility(View.GONE);
} else {
if (!bookmark.isNotificationsEnabled()) {
notificationsEnabledButton.setImageDrawable(notificationsDisabledButtonImage);
}
@ -127,8 +136,14 @@ public class BookmarksFragment extends Fragment {
notificationsEnabledButton.setImageDrawable(notificationsDisabledButtonImage);
}
});
}
(row.findViewById(R.id.remove_bookmark)).setOnClickListener(view -> {
final ImageButton removeButton = row.findViewById(R.id.remove_bookmark);
if (isCalledForWidgetSetup) {
removeButton.setEnabled(false);
removeButton.setVisibility(View.GONE);
} else {
removeButton.setOnClickListener(view -> {
Activity activity = getActivity();
if (activity instanceof BookmarksActivity) {
((BookmarksActivity) activity).onFragmentRowInteractionListener(type, interactionRemove, bookmark);
@ -140,6 +155,8 @@ public class BookmarksFragment extends Fragment {
bookmarksLinearView.addView(bookmarksListEmptyMessage());
}
});
}
bookmarksLinearView.addView(row);
}
}

103
app/src/main/java/gr/thmmy/mthmmy/activities/widget/WidgetProvider.java

@ -0,0 +1,103 @@
package gr.thmmy.mthmmy.activities.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;
import java.util.ArrayList;
import gr.thmmy.mthmmy.R;
import gr.thmmy.mthmmy.activities.board.BoardActivity;
import gr.thmmy.mthmmy.activities.topic.TopicActivity;
import gr.thmmy.mthmmy.model.Bookmark;
import static gr.thmmy.mthmmy.activities.board.BoardActivity.BUNDLE_BOARD_TITLE;
import static gr.thmmy.mthmmy.activities.board.BoardActivity.BUNDLE_BOARD_URL;
import static gr.thmmy.mthmmy.activities.topic.TopicActivity.BUNDLE_TOPIC_TITLE;
import static gr.thmmy.mthmmy.activities.topic.TopicActivity.BUNDLE_TOPIC_URL;
import static gr.thmmy.mthmmy.session.SessionManager.boardUrl;
import static gr.thmmy.mthmmy.session.SessionManager.topicUrl;
public class WidgetProvider extends AppWidgetProvider {
public static final String BOOKMARK_WIDGET_SHARED_PREFS = "bookmarkWidgetSharedPrefs";
public static final String BOOKMARK_WIDGETS_KEY = "bookmarkWidgetsKey";
enum Type {TOPIC, BOARD}
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// Perform this loop procedure for each App Widget that belongs to this provider
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId, 0); // Todo: check if there are already notifications available
}
}
public void onDeleted(Context context, int[] appWidgetIds) {
SharedPreferences widgetSharedPrefs = context.getSharedPreferences(BOOKMARK_WIDGET_SHARED_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor widgetSharedPrefsEditor = widgetSharedPrefs.edit();
for (int appWidgetId : appWidgetIds) {
widgetSharedPrefsEditor.remove(BOOKMARK_WIDGETS_KEY + "_t_" + appWidgetId).remove(BOOKMARK_WIDGETS_KEY + "_b_" + appWidgetId);
}
widgetSharedPrefsEditor.apply();
}
public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, int notifications) {
SharedPreferences widgetSharedPrefs = context.getSharedPreferences(BOOKMARK_WIDGET_SHARED_PREFS, Context.MODE_PRIVATE);
ArrayList<Bookmark> tmpArrayList;
// Gets the bookmark saved in shared prefs
String tmpBookmarkString = widgetSharedPrefs.getString(BOOKMARK_WIDGETS_KEY + "_t_" + appWidgetId, null);
Type type;
if (tmpBookmarkString != null) {
// It's a topic bookmark
tmpArrayList = Bookmark.stringToArrayList(tmpBookmarkString);
type = Type.TOPIC;
} else {
tmpBookmarkString = widgetSharedPrefs.getString(BOOKMARK_WIDGETS_KEY + "_b_" + appWidgetId, null);
if (tmpBookmarkString != null) {
// It's a board bookmark
tmpArrayList = Bookmark.stringToArrayList(tmpBookmarkString);
type = Type.BOARD;
} else {
// Error? TODO: Log on Timber
return;
}
}
// Creates an Intent to launch TopicActivity
Intent intent;
Bundle extras = new Bundle();
if (type == Type.TOPIC) {
intent = new Intent(context, TopicActivity.class);
extras.putString(BUNDLE_TOPIC_URL, topicUrl + tmpArrayList.get(0).getId() + "." + 2147483647);
extras.putString(BUNDLE_TOPIC_TITLE, tmpArrayList.get(0).getTitle());
} else {
intent = new Intent(context, BoardActivity.class);
extras.putString(BUNDLE_BOARD_URL, boardUrl + tmpArrayList.get(0).getId() + ".0");
extras.putString(BUNDLE_BOARD_TITLE, tmpArrayList.get(0).getTitle());
}
intent.putExtras(extras);
PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Gets the layout for the Topic Widget and attach an on-click listener to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);
if (notifications > 0) {
views.setViewVisibility(R.id.widget_notifications_number, View.VISIBLE);
views.setTextViewText(R.id.widget_notifications_number, "" + notifications);
} else {
views.setViewVisibility(R.id.widget_notifications_number, View.GONE);
}
// Tells the AppWidgetManager to perform an update on the current app widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}

10
app/src/main/java/gr/thmmy/mthmmy/model/Bookmark.java

@ -70,15 +70,15 @@ public class Bookmark implements java.io.Serializable {
@Nullable
public static String arrayListToString(@NonNull ArrayList<Bookmark> arrayList) {
String returnString = "";
StringBuilder returnString = new StringBuilder();
for (Bookmark bookmark : arrayList) {
if (bookmark != null) {
returnString += (bookmark.getId() + "\t");
returnString += (bookmark.getTitle() + "\t");
returnString += (bookmark.isNotificationsEnabled() + "\n");
returnString.append(bookmark.getId()).append("\t");
returnString.append(bookmark.getTitle()).append("\t");
returnString.append(bookmark.isNotificationsEnabled()).append("\n");
}
}
if (!Objects.equals(returnString, "")) return returnString;
if (!Objects.equals(returnString.toString(), "")) return returnString.toString();
else return null;
}

2
app/src/main/java/gr/thmmy/mthmmy/session/SessionManager.java

@ -39,6 +39,8 @@ public class SessionManager {
private static final HttpUrl loginUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php?action=login2");
public static final HttpUrl unreadUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php?action=unread;all;start=0;theme=4");
public static final HttpUrl shoutboxUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php?action=tpmod;sa=shoutbox;theme=4");
public static final HttpUrl topicUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php?topic=");
public static final HttpUrl boardUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php?board=");
private static final String guestName = "Guest";
//Response Codes

38
app/src/main/res/layout/widget.xml

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="0dp"
android:paddingTop="0dp"
android:paddingRight="0dp"
android:paddingBottom="0dp">
<ImageView
android:id="@+id/widget_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/widget_button"
android:paddingLeft="0dp"
android:paddingTop="0dp"
android:paddingRight="0dp"
android:paddingBottom="0dp"
android:scaleType="fitCenter"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/widget_notifications_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:background="@color/accent"
android:paddingLeft="5dp"
android:paddingTop="0.5dp"
android:paddingRight="5dp"
android:paddingBottom="0.5dp"
android:textColor="#ffffff"
android:textSize="12dp"
android:visibility="gone"
tools:ignore="SpUsage" />
</FrameLayout>

3
app/src/main/res/values/strings.xml

@ -232,4 +232,7 @@
<string name="new_topic_toolbar">New topic</string>
<string name="create_topic">Create topic</string>
<string name="url_copied_msg">URL copied</string>
<!--Widgets-->
<string name="widget_button">Topic widget</string>
</resources>

10
app/src/main/res/xml/widget_info.xml

@ -0,0 +1,10 @@
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="40dp"
android:minHeight="40dp"
android:updatePeriodMillis="86400000"
android:previewImage="@drawable/ic_bookmark_true_accent_24dp"
android:initialLayout="@layout/widget"
android:configure="gr.thmmy.mthmmy.activities.bookmarks.BookmarksActivity"
android:resizeMode="none"
android:widgetCategory="home_screen">
</appwidget-provider>
Loading…
Cancel
Save