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

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!

Related

I need to update list adapter in background auto refresh listview and notify user if there new data from database

Hello I am creating a social network in android, I have fetching data from mysql data and put it in listview Adapter but I need auto refresh for listview and notification if there is new insert data, I am using Broadcast receiver and service but it there is nothing happen please help me
here is my code
Broadcast receiver
public class BraodcastReceiverNotif extends BroadcastReceiver {
static int noOfTimes = 0;
JSONObject data;
Exception exception;
SharedPreferences sharedpreferences;;
public static final String mypreference = "pkAppPrefs";
int pageNumber = 0;
public static final int REQUEST_CODE = 12345;
Intent intnt;
Context context;
#Override
public void onReceive(final Context context, Intent intent) {
sharedpreferences = context.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
noOfTimes++;
//Toast.makeText(context, "BC Service Running for " + noOfTimes + " times", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
noOfTimes++;
try {
startNetworkCalls ();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void startNetworkCalls () throws JSONException {
data = new JSONObject();
data.put("user_key", sharedpreferences.getString("userKey", ""));
data.put("city_id", sharedpreferences.getString("user_city_id", ""));
data.put("sector_id", sharedpreferences.getString("sector_id", ""));
data.put("page", pageNumber);
String URL = ".............................................";
getOnlinePosts onlinePosts = new getOnlinePosts();
onlinePosts.execute(URL);
}
private class getOnlinePosts extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG =getOnlinePosts.class.getSimpleName();
private Exception exception = null;
#Override
protected void onPreExecute() {
}
#Override
protected String[] doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String docsJson = null;
String JsonDATA = data.toString();
String JsonResponse = null;
Context context = null;
try {
Log.e(LOG_TAG, "Started Connecting to " + params[0] + " Sending " +JsonDATA);
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
writer.close();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
docsJson = buffer.toString();
Log.v(LOG_TAG, "My data is: " + docsJson);
} catch (Exception e) {
exception = e;
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
try {
return getDocumentDataFromJson(docsJson);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// this will only happen if there is an error
return null;
}
#Override
protected void onPostExecute(String[] result) {
}
}
private String[] getDocumentDataFromJson(String documentJsonStrArr)
throws JSONException {
final String data_status = "status";
final String data_data = "data";
final String data_name = "fullname";
final String data_username = "community";
JSONObject documentJson = new JSONObject(documentJsonStrArr);
String status = documentJson.getString(data_status);
if (status.equals("success")) {
JSONArray docs = documentJson.getJSONArray(data_data);
if (docs.length() > 0) {
for (int i = 0; i < docs.length(); i++) {
JSONObject singleDoc = docs.getJSONObject(i);
// String success = singleDoc.getString(documentJson.getString(data_status));
String name = singleDoc.getString(data_name);
String username = singleDoc.getString(data_username);
intnt = new Intent(context, MyService.class);
// Set unsynced count in intent data
intnt.putExtra("success", "success");
intnt.putExtra("name", name);
// Call MyService
context.startService(intnt);
}
}
}
return null;
}
}
here is my service
public class MyService extends Service {
int numMessages = 0;
ArrayList<SinglePost> PostEntries = null;
public ArrayAdapter<SinglePost> mycardAdapter;
SharedPreferences sharedpreferences;;
public static final String mypreference = "pkAppPrefs";
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Intent resultIntent = new Intent(this, Community.class);
Toast.makeText(this, intent.getStringExtra("name"), Toast.LENGTH_LONG).show();
PostEntries.add(new SinglePost(intent.getStringExtra("post_key"),
intent.getStringExtra("name"),
intent.getStringExtra("username"), intent.getStringExtra("profile_image"),intent.getStringExtra("poster_key") ,
intent.getStringExtra("postdate"),intent.getStringExtra("message") ,intent.getStringExtra("likes") ,
intent.getStringExtra("liked"),intent.getStringExtra("comments") ,intent.getStringExtra("commented") ,
Boolean.parseBoolean(intent.getStringExtra("moderate")),intent.getStringExtra("sector") ,
intent.getStringExtra("district"),intent.getStringExtra("province") ,
intent.getStringExtra("city"),intent.getStringExtra("country") ,intent.getStringExtra("media") ,
Integer.parseInt(intent.getStringExtra("media_count") ),
Integer.parseInt(intent.getStringExtra("moderate_level")) ,
Boolean.parseBoolean( intent.getStringExtra("own_post")) ,intent.getStringExtra("online")));
//if (Integer.parseInt(intent.getStringExtra("count_data")) < Integer.parseInt(sharedpreferences.getString("count_data", ""))){
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 9001;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Alert")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_launcher);
// Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | android.app.Notification.DEFAULT_LIGHTS;
defaults = defaults | android.app.Notification.DEFAULT_VIBRATE;
defaults = defaults | android.app.Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
mNotifyBuilder.setContentText(intent.getStringExtra("success"));
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
// }
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
MainActivity class i am passing scheduleAlarm method to check every 10 second in database and refresh my listview
Setup a recurring alarm every 10 seconds
public void scheduleAlarm() {
BroadCase Receiver Intent Object
Intent alarmIntent = new Intent(getContext().getApplicationContext(), BraodcastReceiverNotif.class);
// Pending Intent Object
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext().getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Alarm Manager Object
AlarmManager alarmManager = (AlarmManager) getContext().getApplicationContext().getSystemService(Context.ALARM_SERVICE);
// Alarm Manager calls BroadCast for every Ten seconds (10 * 1000), BroadCase further calls service to check if new records are inserted in
// Remote MySQL DB
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + 5000, 10 * 1000, pendingIntent);
}
fixed format
I really dont understand your question but I got some sense.
If I understand correctly, you want to fetch data from server, store in SQLite database and display the data in Listview
To achieve this functionality,
Create the Http class that gets data from the server.
Create IntentService to make HTTP request.
Once receive data from the server, insert into SQLite. And Broadcast
how you can broadcast is,
you register broadcast receiver in your activity that has the listview.
The broadcast only pass the message as the 'boolean' value that determines did data fetch from the server? If successfully fetched from the server then pass boolean true and after broadcast receive , make a local db call and fetch all changes. After that you can update the listview

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;
}
}`

Receiver for download -- Android

i am doing research oh how to trigger my application if any of download happens in any of application. I have code snippet which uses DownloadManager and that will notify me only when my application had perform any of download, but whereas i never find any solution on which any of download happens in my mobile, that has to notify my application. Pl suggest me if this will be possible. Thanks
1- You have to make Service for Download any file in Background.
public class DownloadService extends Service {
private static final String TAG = "DownloadService";
public static final int UPDATE_PROGRESS = 8344;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
} else {
final String urlToDownload = intent.getStringExtra("url");
final ResultReceiver receiver = (ResultReceiver) intent
.getParcelableExtra("receiver");
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url
.openStream());
String localPath = Environment
.getExternalStorageDirectory()
.getAbsoluteFile()
+ File.separator
+ Constant.ROOT_FOLDER_NAME
+ File.separator
+ Constant.FOLDER_IMAGE
+ File.separator
+ urlToDownload.substring(urlToDownload
.lastIndexOf('/') + 1);
AppLog.Log(TAG, "Path :: " + localPath);
OutputStream output = new FileOutputStream(localPath);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress",
(int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
AppLog.Log(TAG, "********* EXCEPTION *****");
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress", 100);
receiver.send(UPDATE_PROGRESS, resultData);
stopSelf();
}
}).start();
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
2- Then you have to Make ResultReceiver to get notifying while download is completed.
private class DownloadReceiver extends ResultReceiver {
public DownloadReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress");
if (progress == 100) {
// Download Complete
}
}
}
}
3- Call Download Service
Intent intent = new Intent(context, DownloadService.class);
intent.putExtra("url", "url to download");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
Changes in Manifest.xml
Add tag in manifest file inside Application tag:
<application >
------
------
<service android:name="PACKAGENAME.DownloadService" />
------
------
</application>

Preventing swipe from recent apps to terminate tcp connection in a foreground service

I am using a foreground service to perform long I/O operations (upload of files) with a server via a tcp socket.
Inside the service I am using an AsynTask to be able to publish the transfer progress to the UI (notification or whatever else, I don't really mind).
The problem is whenever the app is swiped from recent apps, the socket seems to get closed as well. This is completely contradictory to everything I have read and tested regarding foreground services (like the music app when I swipe it, it displays a foreground service notification and music keeps playing without a glitch).
So what am I doing wrong?
here is my service code:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.i(TAG, "StorageServerProxyService started");
final Intent intentForThread = intent;
new Thread() {
#Override
public void run() {
if (intentForThread != null)
{
String action = intentForThread.getAction();
Log.i(TAG, "Action:" + action);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
try {
connectIfNecessary();
switch (action) {
case ACTION_UPLOAD: {
startServiceForeground();
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG + "_wakeLock");
wakeLock.acquire();
String destId = intentForThread.getStringExtra(DESTINATION_ID);
FileManager managedFile = (FileManager) intentForThread.getSerializableExtra(FILE_TO_UPLOAD);
uploadFileToServer(destId, managedFile);
releaseLockIfNecessary();
stopForeground(true);
}
break;
default:
Log.w(TAG, "Service started with action:" + action);
}
} catch (IOException e) {
e.printStackTrace();
String errMsg = "Action failed:"+action+" Exception:"+e.getMessage();
Log.e(TAG, errMsg);
handleDisconnection(errMsg);
}
} else
Log.w(TAG, "Service started with missing action");
}
}.start();
return START_NOT_STICKY;
}
public void uploadFileToServer(final String destNumber, final FileManager managedFile) throws IOException {
TransferDetails td = new TransferDetails(SharedConstants.MY_ID, destNumber, managedFile);
new UploadTask(getApplicationContext(), connectionToServer).execute(td);
}
private void startServiceForeground() {
Notification notification = new Notification(android.R.drawable.stat_sys_upload, getText(R.string.upload_ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, StorageServerProxyService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
}
This is the AsynTask (UploadTask) code:
public class UploadTask extends AsyncTask<TransferDetails,String,Void> {
private NotificationHelper mNotificationHelper;
private static final String TAG = UploadTask.class.getSimpleName();
private ConnectionToServer _connectionToServer;
private TransferDetails _td;
private Context _context;
public UploadTask(Context context, ConnectionToServer connectionToServer){
_context = context;
mNotificationHelper = new NotificationHelper(_context);
_connectionToServer = connectionToServer;
}
protected void onPreExecute(){
//Create the notification in the statusbar
mNotificationHelper.createUploadNotification();
}
#Override
protected Void doInBackground(TransferDetails... details) {
_td = details[0];
FileManager managedFile = _td.get_managedFile();
MessageUploadFile msgUF = new MessageUploadFile(_td.getSourceId(),_td);
try {
_connectionToServer.sendToServer(msgUF);
Log.i(TAG, "Initiating file data upload...");
DataOutputStream dos = new DataOutputStream(_connectionToServer.getClientSocket().getOutputStream());
FileInputStream fis = new FileInputStream(managedFile.getFile());
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buf = new byte[1024 * 8];
long fileSize = managedFile.getFileSize();
long bytesToRead = fileSize;
int bytesRead;
while (bytesToRead > 0 && (bytesRead = bis.read(buf, 0, (int) Math.min(buf.length, bytesToRead))) != -1) {
dos.write(buf, 0, bytesRead);
String msg = "File upload to:"+_td.getDestinationId()+" %.0f%% complete";
float percent = (float) (fileSize - bytesToRead) / fileSize * 100;
publishProgress(String.format(msg, percent));
bytesToRead -= bytesRead;
}
}
catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Failed:" + e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
//This method runs on the UI thread, it receives progress updates
//from the background thread and publishes them to the status bar
mNotificationHelper.progressUpdate(progress[0]);
}
protected void onPostExecute(Void result) {
//The task is complete, tell the status bar about it
mNotificationHelper.completed();
}
}

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