How to count Push notification bedge android - java

The counter badge should be displayed on the notification icon from firebase. I don't know how to bring bedge to these, I tried many things but I didn't get any answer If you know anything let me know How to bring these to budget. I am getting errors. How to fix these counter icon show bedge
`public class MyFirebaseMessageService extends FirebaseMessagingService {
#Override
public void onNewToken(#NonNull String token) {
super.onNewToken(token);
}
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
try {
if(remoteMessage.getData().size() > 0) {
final JSONObject jsonObject = new JSONObject(remoteMessage.getData().toString());
Log.d(TAG,"remoteMessage = " + jsonObject.toString());
}
} catch (Exception e) {
Log.e(TAG, "onMessageReceived: ", e);
}
if (remoteMessage.getData().size() > 0) {
Map<String, String> data = remoteMessage.getData();
Log.d("onMessageFirebase: ", remoteMessage.getData().toString());
if (data.get("post_id") != null) {
String _unique_id = data.get("unique_id");
String title = data.get("title");
String message = data.get("message");
String big_image = data.get("big_image");
String link = data.get("link");
String _post_id = data.get("post_id");
assert _unique_id != null;
long unique_id = Long.parseLong(_unique_id);
assert _post_id != null;
long post_id = Long.parseLong(_post_id);
createNotification(unique_id, title, message, big_image, link, post_id);
}
}
}
private void createNotification(long unique_id, String title, String message, String image_url, String link, long post_id) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("unique_id", unique_id);
intent.putExtra("post_id", post_id);
intent.putExtra("title", title);
intent.putExtra("link", link);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = getApplicationContext().getString(R.string.app_name);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(getNotificationIcon(notificationBuilder))
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification_large_icon))
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
notificationBuilder.setPriority(Notification.PRIORITY_MAX);
} else {
notificationBuilder.setPriority(NotificationManager.IMPORTANCE_HIGH);
}
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder.setSound(alarmSound).setVibrate(new long[]{100, 200, 300, 400});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.shouldShowLights();
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(false);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
}
if (image_url != null && !image_url.isEmpty()) {
Bitmap image = fetchBitmap(image_url);
if (image != null) {
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image));
}
}
//assert notificationManager != null;
notificationManager.notify((int) post_id, notificationBuilder.build());
}
private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
return R.drawable.ic_stat_onesignal_default;
}
private Bitmap fetchBitmap(String src) {
try {
if (src != null) {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setConnectTimeout(1200000);
connection.setReadTimeout(1200000);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
}
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
}`
how clear this error

Related

Parcelable object being received null via notification but works between activites

I have an Intent Service called ParserService which performs some task and creates an object(ArtistInfo) which is parcelable. Then it checks if the app is in foreground. If it is then it sends a broadcast with the parcelable object in the intent extras. This broadcast is received by the activity MainActivity.java which then creates an intent with the same object and launches an activity called ListSongsActivity where the parcelable object is successfully received.
But if the app is not in foreground then the ParserService sends a notification which has the same intent as that of a broadcast. But when the ListSongsActivity is being launched through the notification the parcelable object(ArtistInfo) this time is null. And I am also passing a string in the intent. This string is being received correctly via the notification intent but the parcelable object is null.
Please find the relevant code snippets below.
Broadcast and notification code from the ParserService:
if (CommonUtils.appInForeground(getApplicationContext())) {
Log.d(TAG, "onHandleIntent(): Sending success broadcast.");
sendBroadcast(createSuccessIntent(artistInfo));
} else {
// TODO: 10-10-2018 tapping on notification does nothing!!
Log.d(TAG, "onHandleIntent(): Sending success notification.");
String body = "Parsing complete for the url: " + url;
Intent notifyIntent = new Intent(getApplicationContext(), ListSongsActivity.class);
notifyIntent.putExtra(Constants.MUSIC_SITE, siteName);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.PARSED_ARTIST_INFO, artistInfo);
intent.putExtras(bundle);
CommonUtils.sendNotification(getApplicationContext(), Constants.LIST_SONGS_NOTIFICATION_TITLE
, body, Constants.LIST_SONGS_NOTIFICATION_CHANNEL_ID, notifyIntent,
Constants.LIST_SONGS_NOTIFICATION_ID, R.drawable.ic_launcher_background);
}
private Intent createSuccessIntent(ArtistInfo artistInfo) {
Intent intent = new Intent();
intent.setAction(Constants.PARSE_SUCCESS_ACTION_KEY);
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.PARSE_SUCCESS_MESSAGE_KEY, artistInfo);
intent.putExtras(bundle);
return intent;
}
Broadcast Received in a fragment of the MainActivity:
private class ParserBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "ParserBroadcastReceiver, onReceive()");
String parseResult = intent.getAction();
if (parseResult == null || parseResult.equals(Constants.EMPTY_STRING)) {
return;
}
switch (parseResult) {
case Constants.PARSE_SUCCESS_ACTION_KEY:
ArtistInfo artistInfo = intent.getParcelableExtra(Constants.PARSE_SUCCESS_MESSAGE_KEY);
Log.d(TAG, "ParserBroadcastReceiver, onReceive() PARSE_SUCCESS_ACTION_KEY, artistInfo: "
+ artistInfo.toString());
Log.d(TAG, "site: " + musicSite);
createIntentAndDelegateActivity(artistInfo);
break;
default:
break;
}
}
}
private void createIntentAndDelegateActivity(ArtistInfo artistInfo) {
Log.d(TAG, "createIntentAndDelegateActivity()");
Intent intent = new Intent(getContext(), ListSongsActivity.class);
intent.putExtra(Constants.MUSIC_SITE, musicSite);
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.PARSED_ARTIST_INFO, artistInfo);
intent.putExtras(bundle);
startActivity(intent);
}
sendNotification in CommonUtils:
public static void sendNotification(Context context, String title, String body,
String channelId, Intent intent, Integer id, Integer iconResourceId) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager == null) {
Log.d(TAG, "sendNotification(): noti manager null!!");
return;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
Constants.DEFAULT_NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(Constants.DEFAULT_NOTIFICATION_CHANNEL_DESCRIPTION);
notificationManager.createNotificationChannel(channel);
}
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntentWithParentStack(intent);
PendingIntent pendingIntent1 = stackBuilder.getPendingIntent(Constants.PENDING_INTENT_DEFAULT_REQ_CODE,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId);
builder.setContentTitle(title);
builder.setContentText(body);
builder.setSmallIcon(iconResourceId);
builder.setContentIntent(pendingIntent1);
Notification notification = builder.build();
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
NotificationManagerCompat.from(context).notify(id, notification);
}
This is how I getIntentExtras in the ListSongsActivity:
private void getIntentExtras() {
Log.d(TAG, "getIntentExtras()");
Intent intent = getIntent();
parsedArtistInfo = intent.getParcelableExtra(Constants.PARSED_ARTIST_INFO);
String siteName = intent.getStringExtra(Constants.MUSIC_SITE);
Log.d(TAG, "getIntentExtras() sitename: " + siteName);
musicSite = Enum.valueOf(MusicSite.class, siteName);
Log.d(TAG, "getIntentExtras() artInfo: " + parsedArtistInfo.toString());
}
When the ListSongsAtivity is started by the broadcast receiver, the parsedArtistInfo object is the correct object passed by the ParserService, but when ListSongsActivity is opened by notification the parsedArtistInfo object is null.
ArtistInfo class:
public class ArtistInfo implements Parcelable {
private static final String TAG = ArtistInfo.class.getSimpleName();
private String url;
private String artist;
// album name to list of ids of songs
private HashMap<String, List<Integer>> albumInfo;
// song id to songInfo
private SparseArray<SongInfo> songsMap;
/**
* to be used only for ui display logic, don't use for downloading logic
*/
private HashMap<String, Boolean> albumCheckedStatus;
public ArtistInfo() {
}
private ArtistInfo(Parcel in) {
url = in.readString();
artist = in.readString();
// Read album info
getAlbumInfo();
int albumInfoSize = in.readInt();
for (int i = 0; i < albumInfoSize; i++) {
String key = in.readString();
List<Integer> value = new ArrayList<>();
in.readList(value, null);
albumInfo.put(key, value);
}
// Read songs map
getSongsMap();
int songsMapSize = in.readInt();
for (int i = 0; i < songsMapSize; i++) {
int key = in.readInt();
SongInfo value = in.readParcelable(SongInfo.class.getClassLoader());
songsMap.put(key, value);
}
getAlbumCheckedStatus();
int albumCheckStatusSize = in.readInt();
for (int i = 0; i < albumCheckStatusSize; i++) {
String key = in.readString();
Boolean value = in.readByte() != 0;
albumCheckedStatus.put(key, value);
}
}
public static final Creator<ArtistInfo> CREATOR = new Creator<ArtistInfo>() {
#Override
public ArtistInfo createFromParcel(Parcel in) {
return new ArtistInfo(in);
}
#Override
public ArtistInfo[] newArray(int size) {
return new ArtistInfo[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(url);
dest.writeString(artist);
// Write album info
getAlbumInfo();
dest.writeInt(albumInfo.size());
for (Map.Entry<String, List<Integer>> item : albumInfo.entrySet()) {
dest.writeString(item.getKey());
dest.writeList(item.getValue());
}
// Write song map
getSongsMap();
dest.writeInt(songsMap.size());
for (int i = 0; i < songsMap.size(); i++) {
int key = songsMap.keyAt(i);
dest.writeInt(key);
dest.writeParcelable(songsMap.get(key), flags);
}
getAlbumCheckedStatus();
dest.writeInt(albumCheckedStatus.size());
for (Map.Entry<String, Boolean> item : albumCheckedStatus.entrySet()) {
dest.writeString(item.getKey());
dest.writeByte((byte) (item.getValue() ? 1 : 0));
}
}
Can someone please point out the error I am making while sending the object in via notification. Thanks!
Before calling sendNotification() in your else condition, you are putting bundle to a different intent, not to notifyIntent. Change your code inside the else like below
else {
// TODO: 10-10-2018 tapping on notification does nothing!!
Log.d(TAG, "onHandleIntent(): Sending success notification.");
String body = "Parsing complete for the url: " + url;
Intent notifyIntent = new Intent(getApplicationContext(), ListSongsActivity.class);
notifyIntent.putExtra(Constants.MUSIC_SITE, siteName);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.PARSED_ARTIST_INFO, artistInfo);
notifyIntent.putExtras(bundle);
CommonUtils.sendNotification(getApplicationContext(), Constants.LIST_SONGS_NOTIFICATION_TITLE
, body, Constants.LIST_SONGS_NOTIFICATION_CHANNEL_ID, notifyIntent,
Constants.LIST_SONGS_NOTIFICATION_ID, R.drawable.ic_launcher_background);
}
Maybe you are creating pending intents more than ones in your app. In this case, you should use,
PendingIntent.FLAG_CANCEL_CURRENT
to create the Intent from scratch and inflate your bundle

Display notifications over activity when app is starting

At this moment i use push notifications in my app. when i start my app they go into the notification drawer like this
1
but i need them to be over the main activity. i cant find the solution anywhere... Which type of notifications can i use ?(without losing the functionality) and how to dublicate the info from push notifications into that type? also is there a way to display push notifications on the whole screen ? fullscreen ? thats what i want: 2
Can someone give me a solution and its code as an example?
my code:
private static int sNotificationId = 1;
public static int showsId = -1;
...
Utils.GetAuthToken(this);
Bundle intent_extras = getIntent().getExtras();
showsId = -1;
if (intent_extras != null && intent_extras.containsKey("com.example.romanchuk.appisode.show_id")) {
if (intent_extras.containsKey("com.example.romanchuk.appisode.notifyId")) {
int notification_id = intent_extras.getInt("com.example.romanchuk.appisode.notifyId", -1);
new ReadNotification(notification_id).execute();
}
showsId = intent_extras.getInt("com.example.romanchuk.appisode.show_id", -1);
} else {
try {
ArrayList<NotificationItem> list = new LoadNotifications().execute().get();
for (int jIndex = 0; jIndex < list.size(); jIndex++) {
new sendNotification(this, list.get(jIndex).getId(),
list.get(jIndex).getShow_id(),
list.get(jIndex).getMessage(),
"Appisode",
list.get(jIndex).getImage()).execute();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
...
private void handleDataMessage(int id, String title, String message) {
try {
String imageUrl = "";
Log.e(TAG, "title: " + title);
Log.e(TAG, "message: " + message);
Log.e(TAG, "imageUrl: " + imageUrl);
if (!true) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
} else {
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
resultIntent.putExtra("com.example.romanchuk.appisode.notifyId", id);
resultIntent.putExtra("message", message);
NotificationUtils notificationUtils = new NotificationUtils(this);
// resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, resultIntent);
}
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
private class sendNotification extends AsyncTask<String, Void, Bitmap> {
Context ctx;
int id, show_id;
String message;
String title;
String icon;
public sendNotification(Context context, int id, int show_id, String message, String title, String icon) {
super();
this.ctx = context;
this.id = id;
this.show_id = show_id;
this.message = message;
this.title = title;
this.icon = icon;
}
...
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
Intent intent = new Intent(ctx, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("com.example.romanchuk.appisode.notifyId", id);
intent.putExtra("com.example.romanchuk.appisode.show_id", show_id);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, sNotificationId , intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(message);
bigText.setBigContentTitle(getString(R.string.app_name));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
Notification notification = null;
notification = builder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setColor(getResources().getColor(R.color.color_accent))
.setContentTitle("Appisode")
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true)
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(inboxStyle)
.setSmallIcon(R.drawable.small_icon)
.setWhen(System.currentTimeMillis())
.setSound(defaultSoundUri).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(sNotificationId++, notification);
}
}

Android Notification Service from JSON

How do I make a notification service, that will notify user about some new news storeis?
I get news from a JSON API (https://newsapi.org/) to my app, and want show user notification if he there are any new stories he hasn't seen.
yes it is easy to create Push notifications in android using FireBase services.Follow my steps here:
https://firebase.google.com/docs/notifications/android/console-audience go here create your first project in firebase console. you will get a file downloaded and paste it in your app module and perform instructions provided by the site
create these files in your project.copy and paste 1.https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseInstanceIDService.java 2.https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java
add necessary permissions and gradle plugins.call this String token = FirebaseInstanceId.getInstance().getToken(); in Activity class.
To test this by giving required parameters in this site: http://apns-gcm.bryantan.info/
Look at my code
Thats beta..
`public class Notification extends Service {
String datanews;
String titlenotif;
String destnotif;
MyAsynk asynk;
#Override
public void onCreate() {
super.onCreate();
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(), 0, 1800000); //тикаем каждые 30 мinute без задержки 1800000
}
//задача для таймера
//Проверяем на новую запись.
class UpdateTimeTask extends TimerTask {
public void run() {
asynk = new MyAsynk();
asynk.execute();
createNotification(getApplicationContext());//пушим уведомление
}
}
class MyAsynk extends AsyncTask<Void,Void,StringBuilder> {
#Override
//работа в бекграунде
protected StringBuilder doInBackground(Void... voids) {
StringBuilder stringBuilder = new StringBuilder();
String key = "YOUR_KEY";
try {
URL url = new URL("YOUR_URL_HERE" + key);
URLConnection uc = url.openConnection();
uc.connect();
BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
int ch;
while ((ch = in.read()) != -1) {
stringBuilder.append((char) ch);
}
} catch (Exception e) {
}
return stringBuilder;
}
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
try {
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String title = object.getString("title");
String desc = object.getString("description");
String newsdata = object.getString("publishedAt");
datanews = newsdata;
titlenotif = title;
destnotif = desc;
}
}
catch (Exception e){
}
}
}
private void createNotification(Context context) {
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncBuilder = new NotificationCompat.Builder(context);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
ncBuilder.setVibrate(new long[]{500});
ncBuilder.setLights(Color.WHITE, 3000, 3000);
ncBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
ncBuilder.setContentIntent(pIntent);
ncBuilder.setContentTitle(titlenotif + "");
ncBuilder.setContentText(destnotif + "");
ncBuilder.setTicker("You have news!");
ncBuilder.setSmallIcon(R.drawable.news_icon);
ncBuilder.setAutoCancel(true);
manager.notify((int)System.currentTimeMillis(),ncBuilder.build());
}
public IBinder onBind(Intent arg0) {
return null;
}
}`

Android Download Manager - Trouble Opening Download No File or Path Exists

I am attempting to download a file using Android's download manager. When the download is successfull, I want to copy the file's contents to another. However, I am not able to open it as an FileInputStream. I receive the following error:
04-07 15:41:49.830 31782-31782/midamcorp.com.burgerkingapp E/Exception: /my_downloads/7: open failed: ENOENT (No such file or directory)/my_downloads/7
Here is the code for the launcher activity:
public class launch_activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch_activity);
final DownloadManager dManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
// set download alarm
Intent downloadIntent = new Intent(launch_activity.this, downloadReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(launch_activity.this, 0, downloadIntent, 0);
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
// cal.set(Calendar.HOUR_OF_DAY, 4);
final AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 1000, AlarmManager.INTERVAL_DAY, pending);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadID);
Cursor cursor = dManager.query(query);
if(cursor.moveToFirst()) {
int colIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(colIndex)) {
Uri uri = dManager.getUriForDownloadedFile(downloadID);
File file = new File(uri.getPath());
try {
FileInputStream inputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = context.openFileOutput(databaseHelper.DB_NAME, MODE_PRIVATE);
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0 , read);
}
fileOutputStream.close();
inputStream.close();
} catch (Exception ex) {
Log.e("Exception", ex.getMessage() + uri.getPath());
}
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
File dbFile = new File(getFilesDir(), "bk.db");
if(!dbFile.exists()) {
try {
InputStream localDB = getAssets().open("bk.db");
OutputStream newDB = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
int read;
while ((read = localDB.read(buffer)) > 0) {
newDB.write(buffer, 0 , read);
}
localDB.close();
newDB.close();
} catch(IOException e) {
Log.e(this.getClass().toString(), "IO Error!");
}
}
SharedPreferences preferences = getSharedPreferences("config", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if(!(preferences.contains("User"))) {
editor.putString("User", "admin");
editor.putString("Pass", "admin");
editor.commit();
}
}
protected void onStart() {
super.onStart();
SharedPreferences preferences = getSharedPreferences("config", MODE_PRIVATE);
if (!(preferences.getBoolean("configured", false))) { // app has not yet been set-up
Intent intent = new Intent(this, midamcorp.com.burgerkingapp.preferences.class);
intent.putExtra("setUp", true);
startActivity(intent);
return;
} else {
Calendar cal = Calendar.getInstance();
if (cal.get(Calendar.HOUR_OF_DAY) > 4 && cal.get(Calendar.HOUR_OF_DAY) < 10) // between 4 - 10 AM
{
Intent intent = new Intent(this, breakfastHome.class);
startActivity(intent);
} else if ((cal.get(Calendar.HOUR_OF_DAY) == 10 && cal.get(Calendar.MINUTE) < 28)) { // between 10 - 10:28 AM
Intent intent = new Intent(this, breakfastHome.class);
startActivity(intent);
} else {
Intent intent = new Intent(this, lunchHome.class);
startActivity(intent);
}
}
}
protected void onResume() {
super.onResume();
this.onStart();
}
}
and the downloadReceiver activity:
public class downloadReceiver extends BroadcastReceiver {
private Context context;
#Override
public void onReceive(Context c, Intent i) {
DownloadManager manager = (DownloadManager) c.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("https://onedrive.live.com/redir?resid=A8EBCBA721A8A30D!8973&authkey=!AIj_ELxdgN7ZBsc&ithint=file%2cdb"));
manager.enqueue(request);
}
}
Also, is there any way to set the file name when requesting a download.
Thanks so much!

Android upload file to AWS S3 error Status Code: 400

I am uploading a file to Amazon S3 server into my BUCKET i am getting error, i am using the code from github https://github.com/jgilfelt/android-simpl3r i will post my code: i have found some information here about my error but i don not know to solve this error https://github.com/jgilfelt/android-simpl3r/issues/4
Status Code: 400, AWS Service: Amazon S3, AWS Request ID: D49EFFBB39B49EEA, AWS Error Code: MalformedXML, AWS Error Message: The XML you provided was not well-formed or did not validate against our published schema, S3 Extended Request ID: fpAsdF+sxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// start file chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent,"Select a file to upload"),FILE_SELECT_CODE);
}
});
public class UploadService extends IntentService {
public static final String ARG_FILE_PATH = "file_path";
public static final String UPLOAD_STATE_CHANGED_ACTION = "com.readystatesoftware.simpl3r.example.UPLOAD_STATE_CHANGED_ACTION";
public static final String UPLOAD_CANCELLED_ACTION = "com.readystatesoftware.simpl3r.example.UPLOAD_CANCELLED_ACTION";
public static final String S3KEY_EXTRA = "s3key";
public static final String PERCENT_EXTRA = "percent";
public static final String MSG_EXTRA = "msg";
private static final int NOTIFY_ID_UPLOAD = 1337;
private AmazonS3Client s3Client;
private Uploader uploader;
private NotificationManager nm;
public UploadService() {
super("simpl3r-example-upload");
}
#Override
public void onCreate() {
super.onCreate();
s3Client = new AmazonS3Client(
new BasicAWSCredentials(getString(R.string.s3_access_key), getString(R.string.s3_secret)));
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
IntentFilter f = new IntentFilter();
f.addAction(UPLOAD_CANCELLED_ACTION);
registerReceiver(uploadCancelReceiver, f);
}
#Override
protected void onHandleIntent(Intent intent) {
String filePath = intent.getStringExtra(ARG_FILE_PATH);
File fileToUpload = new File(filePath);
Log.v("filePath", ""+filePath);
final String s3ObjectKey = md5(filePath);
Log.v("s3ObjectKey", ""+s3ObjectKey);
String s3BucketName = getString(R.string.s3_bucket);
final String msg = "Uploading " + s3ObjectKey + "...";
// create a new uploader for this file
uploader = new Uploader(this, s3Client, s3BucketName, s3ObjectKey, fileToUpload);
// listen for progress updates and broadcast/notify them appropriately
uploader.setProgressListener(new UploadProgressListener() {
#Override
public void progressChanged(ProgressEvent progressEvent,
long bytesUploaded, int percentUploaded) {
Notification notification = buildNotification(msg, percentUploaded);
nm.notify(NOTIFY_ID_UPLOAD, notification);
broadcastState(s3ObjectKey, percentUploaded, msg);
}
});
// broadcast/notify that our upload is starting
Notification notification = buildNotification(msg, 0);
nm.notify(NOTIFY_ID_UPLOAD, notification);
broadcastState(s3ObjectKey, 0, msg);
try {
String s3Location = uploader.start(); // initiate the upload
broadcastState(s3ObjectKey, -1, "File successfully uploaded to " + s3Location);
} catch (UploadIterruptedException uie) {
broadcastState(s3ObjectKey, -1, "User interrupted");
} catch (Exception e) {
e.printStackTrace();
broadcastState(s3ObjectKey, -1, "Error: " + e.getMessage());
}
}
#Override
public void onDestroy() {
nm.cancel(NOTIFY_ID_UPLOAD);
unregisterReceiver(uploadCancelReceiver);
super.onDestroy();
}
private void broadcastState(String s3key, int percent, String msg) {
Intent intent = new Intent(UPLOAD_STATE_CHANGED_ACTION);
Bundle b = new Bundle();
b.putString(S3KEY_EXTRA, s3key);
b.putInt(PERCENT_EXTRA, percent);
b.putString(MSG_EXTRA, msg);
intent.putExtras(b);
sendBroadcast(intent);
}
private Notification buildNotification(String msg, int progress) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setWhen(System.currentTimeMillis());
builder.setTicker(msg);
builder.setContentTitle(getString(R.string.app_name));
builder.setContentText(msg);
builder.setSmallIcon(R.drawable.ic_stat_uploading);
builder.setOngoing(true);
builder.setProgress(100, progress, false);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder.setContentIntent(contentIntent);
return builder.build();
}
private BroadcastReceiver uploadCancelReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (uploader != null) {
uploader.interrupt();
}
}
};
private String md5(String s) {
try {
// create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}

Categories

Resources