/
NotificationHandler.java
326 lines (295 loc) · 14.1 KB
/
NotificationHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package javinator9889.bitcoinpools.BackgroundJobs;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import com.googlecode.charts4j.AxisLabels;
import com.googlecode.charts4j.AxisLabelsFactory;
import com.googlecode.charts4j.AxisStyle;
import com.googlecode.charts4j.AxisTextAlignment;
import com.googlecode.charts4j.Color;
import com.googlecode.charts4j.Data;
import com.googlecode.charts4j.Fills;
import com.googlecode.charts4j.GCharts;
import com.googlecode.charts4j.Line;
import com.googlecode.charts4j.LineChart;
import com.googlecode.charts4j.LineStyle;
import com.googlecode.charts4j.Plots;
import com.googlecode.charts4j.Shape;
import org.json.JSONException;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import androidx.annotation.NonNull;
import javinator9889.bitcoinpools.BitCoinApp;
import javinator9889.bitcoinpools.Constants;
import javinator9889.bitcoinpools.DataLoaderScreen;
import javinator9889.bitcoinpools.JSONTools.JSONTools;
import javinator9889.bitcoinpools.MainActivity;
import javinator9889.bitcoinpools.NetTools.net;
import javinator9889.bitcoinpools.R;
import static javinator9889.bitcoinpools.Constants.API_URL;
/**
* Created by Javinator9889 on 23/01/2018. Based on: https://stackoverflow.com/a/46991229
*/
class NotificationHandler {
private static boolean NOTIFICATIONS_ENABLED = false;
private static boolean NOTIFIED_HIGH = false;
private static boolean NOTIFIED_LOW = false;
private static int SPECIFIC_VALUE = 0;
private static float MPU;
private NotificationHandler() {
final SharedPreferences sp = BitCoinApp.getSharedPreferences();
Log.d(Constants.LOG.NTAG, Constants.LOG.CREATING_NOTIFICATION);
NOTIFICATIONS_ENABLED = sp.getBoolean(Constants.SHARED_PREFERENCES.NOTIFICATIONS_ENABLED,
false);
NOTIFIED_HIGH = sp.getBoolean(Constants.SHARED_PREFERENCES.NOTIFIED_HIGH, false);
NOTIFIED_LOW = sp.getBoolean(Constants.SHARED_PREFERENCES.NOTIFIED_LOW, false);
SPECIFIC_VALUE = sp.getInt(Constants.SHARED_PREFERENCES.VALUE_TO_CHECK, 1000);
MPU = initMPU();
Log.d(Constants.LOG.NTAG, Constants.LOG.CURRRENT_NOT_SETTINGS
+ NOTIFICATIONS_ENABLED + "\n"
+ NOTIFIED_HIGH + "\n"
+ NOTIFIED_LOW + "\n"
+ SPECIFIC_VALUE + "\n"
+ MPU);
}
void putNotification() {
boolean notify = false;
String notificationTitle = "";
String notificationText = "";
String notificationTextLong = "";
NotificationManager notificationManager = (NotificationManager) BitCoinApp.getAppContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent clickIntent = PendingIntent.getActivity(
BitCoinApp.getAppContext(),
Constants.REQUEST_CODE,
new Intent(BitCoinApp.getAppContext(), DataLoaderScreen.class),
PendingIntent.FLAG_UPDATE_CURRENT
);
if (NOTIFICATIONS_ENABLED) {
if ((MPU < SPECIFIC_VALUE) && !NOTIFIED_LOW) {
notificationTitle = BitCoinApp.getAppContext().getString(R.string.lowerPrice);
notificationTextLong = BitCoinApp.getAppContext().getString(R.string.lowerPriceX)
+ SPECIFIC_VALUE + ". "
+ BitCoinApp.getAppContext().getString(R.string.actualCost) + MPU;
notificationText = BitCoinApp.getAppContext().getString(R.string.lowerPriceX)
+ SPECIFIC_VALUE;
NOTIFIED_HIGH = false;
NOTIFIED_LOW = true;
notify = (MPU != -1);
} else if ((MPU > SPECIFIC_VALUE) && !NOTIFIED_HIGH) {
notificationTitle = BitCoinApp.getAppContext().getString(R.string.morePrice);
notificationTextLong = BitCoinApp.getAppContext().getString(R.string.morePriceX)
+ SPECIFIC_VALUE + ". " + BitCoinApp.getAppContext().getString(R.string.actualCost) + MPU;
notificationText = BitCoinApp.getAppContext().getString(R.string.morePriceX)
+ SPECIFIC_VALUE;
NOTIFIED_HIGH = true;
NOTIFIED_LOW = false;
notify = (MPU != -1);
}
String notificationTitleLong = BitCoinApp
.getAppContext()
.getString(R.string.actualCost) + MPU;
if (notify) {
Log.d(Constants.LOG.NTAG, Constants.LOG.NOTIFYING);
updatePreferences();
AsyncTask<String, Void, Bitmap> lineChartTask = generateLineChart();
String name = BitCoinApp.getAppContext().getString(R.string.alerts);
String description = BitCoinApp.getAppContext().getString(R.string.description);
Notification.Builder notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = android.app.NotificationManager.IMPORTANCE_HIGH;
assert notificationManager != null;
NotificationChannel mChannel = notificationManager
.getNotificationChannel(Constants.CHANNEL_ID);
if (mChannel == null) {
mChannel = new NotificationChannel(Constants.CHANNEL_ID, name, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 100, 300});
notificationManager.createNotificationChannel(mChannel);
}
notification = new Notification.Builder(BitCoinApp.getAppContext(),
Constants.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_equalizer)
.setCategory(Notification.CATEGORY_MESSAGE)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setAutoCancel(true)
.setTicker(notificationTitle)
.setStyle(new Notification.BigTextStyle()
.bigText(notificationTextLong));
} else {
notification = new Notification.Builder(BitCoinApp.getAppContext())
.setSmallIcon(R.drawable.ic_stat_equalizer)
.setCategory(Notification.CATEGORY_MESSAGE)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setAutoCancel(true)
.setTicker(notificationTitle)
.setStyle(new Notification.BigTextStyle()
.bigText(notificationTextLong));
}
try {
if (lineChartTask != null) {
Bitmap lineChart = lineChartTask.get();
if (lineChart != null)
notification.setStyle(new Notification.BigPictureStyle()
.bigPicture(lineChart)
.setBigContentTitle(notificationTitleLong));
}
} catch (ExecutionException | InterruptedException ignored) {
} finally {
notification.setContentIntent(clickIntent);
assert notificationManager != null;
notificationManager.notify(Constants.NOTIFICATION_ID, notification.build());
}
}
} else
Log.d(Constants.LOG.NTAG, Constants.LOG.NNOTIFYING);
}
private AsyncTask<String, Void, Bitmap> generateLineChart() {
Map<Date, Float> pricesMap;
Calendar start = Calendar.getInstance();
start.add(Calendar.DAY_OF_MONTH, -7);
String startDate = String.format(Locale.US, "%d-%02d-%02d",
start.get(Calendar.YEAR),
(start.get(Calendar.MONTH) + 1),
start.get(Calendar.DAY_OF_MONTH));
String url = API_URL + "?start=" + startDate + "&end=" +
new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Calendar.getInstance().getTime());
pricesMap = getValuesByDatedURL(url);
if (pricesMap == null)
return null;
int divider = getDivider(pricesMap);
Line bitcoinPricesLine = Plots.newLine(getNormalizedData(pricesMap), Color.DARKBLUE);
bitcoinPricesLine.setLineStyle(LineStyle.MEDIUM_DOTTED_LINE);
bitcoinPricesLine.addShapeMarkers(Shape.CIRCLE, Color.BLACK, 8);
bitcoinPricesLine.setFillAreaColor(Color.CYAN);
final LineChart bitcoinPricesChart = GCharts.newLineChart(bitcoinPricesLine);
bitcoinPricesChart.setSize(760, 380);
bitcoinPricesChart.setGrid(25, 25, 3, 2);
AxisStyle axisStyle = AxisStyle.newAxisStyle(Color.BLACK, 11, AxisTextAlignment.CENTER);
AxisLabels xAxis = AxisLabelsFactory.newAxisLabels(getDates(pricesMap));
AxisLabels yAxis = AxisLabelsFactory.newAxisLabels(getValues(pricesMap, divider));
xAxis.setAxisStyle(axisStyle);
yAxis.setAxisStyle(axisStyle);
bitcoinPricesChart.addXAxisLabels(xAxis);
bitcoinPricesChart.addYAxisLabels(yAxis);
bitcoinPricesChart.setBackgroundFill(Fills.newSolidFill(Color.WHITE));
ImageDownloader downloader = new ImageDownloader();
return downloader.execute(bitcoinPricesChart.toURLString());
}
private int getDivider(@NonNull Map<Date, Float> pricesMap) {
Float maximum = Collections.max(pricesMap.values());
int iterations = 0;
while (maximum >= 10) {
maximum /= 10;
++iterations;
}
return (int) Math.pow(10, iterations);
}
private List<String> getDates(@NonNull Map<Date, Float> pricesMap) {
List<String> dates = new ArrayList<>(pricesMap.keySet().size());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
for (Date currentDate : pricesMap.keySet())
dates.add(formatter.format(currentDate));
return dates;
}
private List<String> getValues(@NonNull Map<Date, Float> pricesMap, int divider) {
Collection<Float> values = pricesMap.values();
List<String> formattedValues = new ArrayList<>(6);
float maximum = Collections.max(values);
float minimum = Collections.min(values);
float difference = maximum - minimum;
float amount = difference / 5;
formattedValues.add(0, String.format(Locale.US, "%.2fK", (minimum / divider)));
float latest = minimum;
for (int i = 1; i < 5; ++i) {
latest += amount;
formattedValues.add(i, String.format(Locale.US, "%.2fK", (latest / divider)));
}
formattedValues.add(5, String.format(Locale.US, "%.2fK", (maximum / divider)));
return formattedValues;
}
private Data getNormalizedData(@NonNull Map<Date, Float> pricesMap) {
double[] normalizedValues = new double[pricesMap.values().size()];
float maximum = Collections.max(pricesMap.values());
float minimum = Collections.min(pricesMap.values());
float difference = maximum - minimum;
int i = 0;
for (Float currentValue : pricesMap.values()) {
float actualDifference = currentValue - minimum;
normalizedValues[i] = (100 * actualDifference) / difference;
++i;
}
return Data.newData(normalizedValues);
}
private Map<Date, Float> getValuesByDatedURL(@NonNull String url) {
net netRequest = new net();
netRequest.execute(url);
try {
return JSONTools.sortDateByValue(
JSONTools.convert2DateHashMap(netRequest.get().getJSONObject("bpi")));
} catch (InterruptedException | ExecutionException |
JSONException | NullPointerException ignored) {
return null;
}
}
private static class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
try {
URL imageUrl = new URL(urls[0]);
return BitmapFactory.decodeStream(imageUrl.openConnection().getInputStream());
} catch (IOException ignored) {
return null;
}
}
}
@NonNull
static NotificationHandler newInstance() {
return new NotificationHandler();
}
private static float initMPU() {
net market = new net();
market.execute("https://api.blockchain.info/stats");
try {
return MainActivity.round((float) market.get().getDouble("market_price_usd"),
2);
} catch (InterruptedException | ExecutionException
| JSONException | NullPointerException e) {
return -1;
}
}
void updatePreferences() {
updateSharedPreferences();
}
private static void updateSharedPreferences() {
final SharedPreferences.Editor sharedPreferencesEditor = BitCoinApp
.getSharedPreferences().edit();
sharedPreferencesEditor.putBoolean(Constants.SHARED_PREFERENCES.NOTIFIED_HIGH,
NOTIFIED_HIGH);
sharedPreferencesEditor.putBoolean(Constants.SHARED_PREFERENCES.NOTIFIED_LOW,
NOTIFIED_LOW);
sharedPreferencesEditor.apply();
}
}