FTP file upload issue - android

I need to upload a file from the sdcard to a server(using FTP), but I've encountered some problems when trying to save the file. The file seems to exist at first, but when I choose to play it... well, it just won't (like it crashes during upload rendering it invalid). Any ideas regarding what might going wrong? I've set the extension .mp3, and here's the code:
holder.upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str_useid = Recording.str_getValue;
if (upload_or_not == true) {
FTPClient con = new FTPClient();
try {
con.connect("FTP URL");
if (con.login("USERNAME", "PASSWORD")) {
Handler progressHandler = new Handler();
con.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn = new BufferedInputStream(
new FileInputStream(
"/sdcard/audiometer/shanesh" +
RequestId[position] + "-"
str_useid + ".mp3"
)
);
con.enterLocalPassiveMode(); // important!
ProgressInputStream progressInput = new ProgressInputStream(
buffIn,
progressHandler
);
boolean status = con.storeFile(
"/Rangam/shanesh" +
RequestId[position] + "-" +
str_useid +
".mp3",
progressInput
);
String filename = "/shanesh" + RequestId[position] +
"-" + str_useid + ".mp3";
buffIn.close();
con.logout();
con.disconnect();
String MachineName = "DOT-NET-SERVER";
sendFlagToServer(RequestId[position], filename, MachineName);
Toast.makeText(
context,
" :: sucessfully upload :: " + status,
Toast.LENGTH_LONG
).show();
Toast.makeText(
context,
" :: RequestId is :: " +
RequestId[position],
Toast.LENGTH_LONG
).show();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(
context,
" :: File not Found :: ",
Toast.LENGTH_LONG
).show();
}
}
ProgressInputStream.java
package com.RecordingApp;
import java.io.IOException;
import java.io.InputStream;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class ProgressInputStream extends InputStream {
/* Key to retrieve progress value from message bundle passed to handler */
public static final String PROGRESS_UPDATE = "progress_update";
private static final int TEN_KILOBYTES = 1024 * 10;
private InputStream inputStream;
private Handler handler;
private long progress;
private long lastUpdate;
private boolean closed;
public ProgressInputStream(InputStream inputStream, Handler handler) {
this.inputStream = inputStream;
this.handler = handler;
this.progress = 0;
this.lastUpdate = 0;
this.closed = false;
}
#Override
public int read() throws IOException {
int count = inputStream.read();
return incrementCounterAndUpdateDisplay(count);
}
#Override
public int read(byte[] b, int off, int len) throws IOException {
int count = inputStream.read(b, off, len);
return incrementCounterAndUpdateDisplay(count);
}
#Override
public void close() throws IOException {
super.close();
if (closed)
throw new IOException("already closed");
closed = true;
}
private int incrementCounterAndUpdateDisplay(int count) {
if (count > 0)
progress += count;
lastUpdate = maybeUpdateDisplay(progress, lastUpdate);
return count;
}
private long maybeUpdateDisplay(long progress, long lastUpdate) {
if (progress - lastUpdate > TEN_KILOBYTES) {
lastUpdate = progress;
sendLong(PROGRESS_UPDATE, progress);
}
return lastUpdate;
}
public void sendLong(String key, long value) {
Bundle data = new Bundle();
data.putLong(key, value);
Message message = Message.obtain();
message.setData(data);
handler.sendMessage(message);
}
}

Related

How can i add custom header fields while uploading file into Amazon s3

I need to store multimedia files in Amazons3.
I used the following code for uploading a the file.
Method 1:
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.StrictMode;
import android.util.Log;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AbortMultipartUploadRequest;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest;
import com.amazonaws.services.s3.model.CompleteMultipartUploadResult;
import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest;
import com.amazonaws.services.s3.model.InitiateMultipartUploadResult;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PartETag;
import com.amazonaws.services.s3.model.ProgressEvent;
import com.amazonaws.services.s3.model.ProgressListener;
import com.amazonaws.services.s3.model.UploadPartRequest;
import com.amazonaws.services.s3.model.UploadPartResult;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AmazonUploader {
private static final long MIN_DEFAULT_PART_SIZE = 5 * 1024 * 1024;
private static final String TAG = "AmazonUploader";
private static final String PREFS_NAME = "preferences_simpl3r";
private static final String PREFS_UPLOAD_ID = "_uploadId";
private static final String PREFS_ETAGS = "_etags";
private static final String PREFS_ETAG_SEP = "~~";
private AmazonS3Client s3Client;
private String s3bucketName;
private String s3key;
private File file;
private SharedPreferences prefs;
private long partSize = MIN_DEFAULT_PART_SIZE;
private UploadProgressListener progressListener;
private long bytesUploaded = 0;
private boolean userInterrupted = false;
private boolean userAborted = false;
public AmazonUploader(Context context, AmazonS3Client s3Client, String s3bucketName, String s3key, File file) {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
this.s3Client = s3Client;
this.s3key = s3key;
this.s3bucketName = s3bucketName;
this.file = file;
prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
/**
* Initiate a multipart file upload to Amazon S3
*
* #return the URL of a successfully uploaded file
*/
public String start() {
// initialize
List<PartETag> partETags = new ArrayList<PartETag>();
final long contentLength = file.length();
long filePosition = 0;
int startPartNumber = 1;
userInterrupted = false;
userAborted = false;
bytesUploaded = 0;
// check if we can resume an incomplete download
String uploadId = getCachedUploadId();
if (uploadId != null) {
// we can resume the download
Log.i(TAG, "resuming upload for " + uploadId);
// get the cached etags
List<PartETag> cachedEtags = getCachedPartEtags();
partETags.addAll(cachedEtags);
// calculate the start position for resume
startPartNumber = cachedEtags.size() + 1;
filePosition = (startPartNumber - 1) * partSize;
bytesUploaded = filePosition;
Log.i(TAG, "resuming at part " + startPartNumber + " position " + filePosition);
} else {
// initiate a new multi part upload
Log.i(TAG, "initiating new upload");
InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(s3bucketName, s3key);
// ObjectMetadata obj = new ObjectMetadata();
// obj.setContentType("image/jpeg");
// obj.setHeader(Constants.APP_HEADER_REFERER, Constants.APP_REFERER_URL);
// initRequest.setObjectMetadata(obj);
configureInitiateRequest(initRequest);
InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest);
uploadId = initResponse.getUploadId();
}
final AbortMultipartUploadRequest abortRequest = new AbortMultipartUploadRequest(s3bucketName, s3key, uploadId);
for (int k = startPartNumber; filePosition < contentLength; k++) {
long thisPartSize = Math.min(partSize, (contentLength - filePosition));
Log.i(TAG, "starting file part " + k + " with size " + thisPartSize);
UploadPartRequest uploadRequest = new UploadPartRequest().withBucketName(s3bucketName)
.withKey(s3key).withUploadId(uploadId)
.withPartNumber(k).withFileOffset(filePosition).withFile(file)
.withPartSize(thisPartSize);
ProgressListener s3progressListener = new ProgressListener() {
public void progressChanged(ProgressEvent progressEvent) {
// bail out if user cancelled
// TODO calling shutdown too brute force?
if (userInterrupted) {
s3Client.shutdown();
throw new UploadIterruptedException("User interrupted");
} else if (userAborted) {
// aborted requests cannot be resumed, so clear any cached etags
clearProgressCache();
s3Client.abortMultipartUpload(abortRequest);
s3Client.shutdown();
}
bytesUploaded += progressEvent.getBytesTransfered();
//Log.d(TAG, "bytesUploaded=" + bytesUploaded);
// broadcast progress
float fpercent = ((bytesUploaded * 100) / contentLength);
int percent = Math.round(fpercent);
if (progressListener != null) {
progressListener.progressChanged(progressEvent, bytesUploaded, percent);
}
}
};
uploadRequest.setProgressListener(s3progressListener);
UploadPartResult result = s3Client.uploadPart(uploadRequest);
partETags.add(result.getPartETag());
// cache the part progress for this upload
if (k == 1) {
initProgressCache(uploadId);
}
// store part etag
cachePartEtag(result);
filePosition += thisPartSize;
}
CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(
s3bucketName, s3key, uploadId,
partETags);
CompleteMultipartUploadResult result = s3Client.completeMultipartUpload(compRequest);
bytesUploaded = 0;
Log.i(TAG, "upload complete for " + uploadId);
clearProgressCache();
return result.getLocation();
}
private String getCachedUploadId() {
return prefs.getString(s3key + PREFS_UPLOAD_ID, null);
}
private List<PartETag> getCachedPartEtags() {
List<PartETag> result = new ArrayList<PartETag>();
// get the cached etags
ArrayList<String> etags = SharedPreferencesUtils.getStringArrayPref(prefs, s3key + PREFS_ETAGS);
for (String etagString : etags) {
String partNum = etagString.substring(0, etagString.indexOf(PREFS_ETAG_SEP));
String partTag = etagString.substring(etagString.indexOf(PREFS_ETAG_SEP) + 2, etagString.length());
PartETag etag = new PartETag(Integer.parseInt(partNum), partTag);
result.add(etag);
}
return result;
}
private void cachePartEtag(UploadPartResult result) {
String serialEtag = result.getPartETag().getPartNumber() + PREFS_ETAG_SEP + result.getPartETag().getETag();
ArrayList<String> etags = SharedPreferencesUtils.getStringArrayPref(prefs, s3key + PREFS_ETAGS);
etags.add(serialEtag);
SharedPreferencesUtils.setStringArrayPref(prefs, s3key + PREFS_ETAGS, etags);
}
private void initProgressCache(String uploadId) {
// store uploadID
Editor edit = prefs.edit().putString(s3key + PREFS_UPLOAD_ID, uploadId);
AmazonSharedPreferencesCompact.apply(edit);
// create empty etag array
ArrayList<String> etags = new ArrayList<String>();
SharedPreferencesUtils.setStringArrayPref(prefs, s3key + PREFS_ETAGS, etags);
}
private void clearProgressCache() {
// clear the cached uploadId and etags
Editor edit = prefs.edit();
edit.remove(s3key + PREFS_UPLOAD_ID);
edit.remove(s3key + PREFS_ETAGS);
AmazonSharedPreferencesCompact.apply(edit);
}
public void interrupt() {
userInterrupted = true;
}
public void abort() {
userAborted = true;
}
/**
* Override to configure the multipart upload request.
* <p/>
* By default uploaded files are publicly readable.
*
* #param initRequest S3 request object for the file to be uploaded
*/
protected void configureInitiateRequest(InitiateMultipartUploadRequest initRequest) {
initRequest.setCannedACL(CannedAccessControlList.PublicRead);
ObjectMetadata obj = new ObjectMetadata();
obj.setContentType("image/jpeg");
obj.setHeader(Constants.APP_HEADER_REFERER, Constants.APP_REFERER_URL);
initRequest.withObjectMetadata(obj);
}
public void setPrefs(SharedPreferences prefs) {
this.prefs = prefs;
}
public long getPartSize() {
return partSize;
}
public void setPartSize(long partSize) {
if (partSize < MIN_DEFAULT_PART_SIZE) {
throw new IllegalStateException("Part size is less than S3 minimum of " + MIN_DEFAULT_PART_SIZE);
} else {
this.partSize = partSize;
}
}
public void setProgressListener(UploadProgressListener progressListener) {
this.progressListener = progressListener;
}
public interface UploadProgressListener {
public void progressChanged(ProgressEvent progressEvent, long bytesUploaded, int percentUploaded);
}
}
Method 2:
TransferObserver transferObserver = transferUtility.upload(
Constants.S3_BUCKET_NAME, /* The bucket to upload to */
fileName, /* The key for the uploaded object */
new File(imagePath), /* The file where the data to upload exists */
objectMetadata);
transferObserverListener(transferObserver);
in both method i got the following error
com.amazonaws.services.s3.model.AmazonS3Exception: Forbidden (Service: Amazon S3; Status Code: 403; Error Code: 403 Forbidden; Request...
Here i must pass customer header parameters, so i add like following
ObjectMetadata objectMetadata = new ObjectMetadata();
HashMap<String, String> mMetaMap = new HashMap<String, String>();
mMetaMap.put("content-type", "image/jpeg");
mMetaMap.put(Constants.APP_HEADER_REFERER, Constants.APP_REFERER_URL);
objectMetadata.setUserMetadata(mMetaMap);
But still i got the above error.
Is i'm passing the header parameters in correct way either i need to do changes. Kindly advise on this. Thanks

how to all file download in android and save all file in sd card?

In my case i click download button when download all file but in show all file sdcard and some file display . and i used thread .what me wrong in my code : and Cancel(cl) button working but in i used delted download file is not working and {cl and dl button} setVisibitly not changed. My Code Below: Please Helpme>
mainDownloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adtf.setAllDownload();
}
});
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
ProgressBar pr;
ProgressBar[] prArray = new ProgressBar[list.size()];
Button cl, dl;
ImageView im;
DownloadFileFromURL downloadFileFromURL;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setAllDownload() {
if (prArray.length > 0) {
for (int i = 0; i < prArray.length; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, list.get(i).url_video, i);
}
}
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custome_list_view, null);
cl = (Button) convertView.findViewById(R.id.cancle_sedual);
dl = (Button) convertView.findViewById(R.id.download_sedual);
pr = (ProgressBar) convertView.findViewById(R.id.listprogressbar);
prArray[position] = pr;
im = (ImageView) convertView.findViewById(R.id.list_image);
im.setImageResource(list.get(position).images[position]);
getProgress(pr, position, cl, dl);
// pr.setProgress(getItem(position));
cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Cancle Button Click");
// dl.setVisibility(View.VISIBLE);
dl.setVisibility(View.VISIBLE);
cl.setVisibility(View.GONE);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
//downloadFileFromURL.cancel(true);
downloadFileFromURL.downloadFile();
pr.setProgress(0);
}
});
dl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
str_start = list.get(position).url_video;
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
Log.v("log_tag","Start Button Click ");
//
// new DownloadFileFromURL().execute(str_start);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, str_start, position);
}
});
return convertView;
}
}
class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {
int count = 0;
ProgressDialog dialog;
ProgressBar progressBar;
int myProgress;
int position;
Button start, cancel;
boolean download1 = false;
public DownloadFileFromURL(Button start, Button cancel) {
this.start = start;
this.cancel = cancel;
}
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar progressBar;
download1 = true;
}
public void downloadFile() {
this.download1 = false;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
/**
* Downloading file in background thread
* */
#Override
protected Integer doInBackground(Object... params) {
//Log.v("log_tag", "params :::; " + params);
int count;
progressBar = (ProgressBar) params[0];
position = (Integer) params[2];
try {
// URL url = new URL(f_url[0]);
URL url = new URL((String) params[1]);
//Log.v("log_tag", "name ::: " + url);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
//Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
if (this.download1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
// publishProgress("" + (int) ((total * 100) /
// lenghtOfFile));
// writing data to file
progressBar
.setProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
setProgress(progressBar, position, start, cancel, this);
}
}
// flushing output
output.flush();
if(!this.download1){
File delete = new File(strDownloaDuRL);
delete.delete();
}
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return 0;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Log.v("log_tag", "progress :: " + values);
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.v("log", "login ::: 4::: " + download);
String videoPath = download + "/" + name;
String chpName = name;
Log.v("log_tag", "chpName ::::" + chpName + " videoPath "
+ videoPath);
db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
+ chpName + "\",\"" + videoPath + "\" )");
}
}
private void setProgress(final ProgressBar pr, final int position,
final Button Start, final Button cancel,
final DownloadFileFromURL downloadFileFromURL) {
ProgressBarSeek pbarSeek = new ProgressBarSeek();
pbarSeek.setPosition(position);
pbarSeek.setProgressValue(pr.getProgress());
//Log.v("log_tag", position + " progress " + pr.getProgress());
progreeSeekList.add(pbarSeek);
/* cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Cancle Button Click Set progress");
Start.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
downloadFileFromURL.cancel(true);
pr.setProgress(0);
}
});
Start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Start Button Click set Progress");
str_start = list.get(position).url_video;
Start.setVisibility(View.GONE);
cancel.setVisibility(View.VISIBLE);
Log.v("log_tag", "str_start " + str_start);
//
// new DownloadFileFromURL().execute(str_start);
DownloadFileFromURL downloadFileFromU = new DownloadFileFromURL(
Start, cancel);
downloadFileFromU.execute(pr, str_start, position);
}
});*/
}
private void getProgress(ProgressBar pr, int position, Button cl, Button dl) {
if (progreeSeekList.size() > 0) {
for (int j = 0; j < progreeSeekList.size(); j++) {
if (position == progreeSeekList.get(j).getPosition()) {
pr.setProgress(progreeSeekList.get(j).getProgressValue());
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
}
}
}
}
}
You can try using the below code to download the files from the url and save into the sdcard:
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/xmls");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download url:" + url);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
Also keep in mind that you specify the below permissions in your manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
I hope it will help you.
Thanks

How to Use Android SeekBar For File Upload and Download using FTP?

I have an issue when I am trying to download a file from server using FTP. I need to display seek-bar status of downloading file and download speed of the Internet. I am able to display seek-bar status and speed of the Internet for HTTP, but for FTP I am not able to perform that same task. In the attached image below I need to display seek-bar and network speed for FTP and HTTP. Below is the source code I used for HTTP and FTP. I don't know where I missed it?
HTTP Code:
class DownloadFileAsync extends AsyncTask<String, String, String> { //see the summary of asyncTask
long duration, pk;
private boolean sleep = false;
private HashMap<String, Object> map;
private ProgressBar bar;
private TextView real_time, test_avg, peak, status;
private ImageView pp;
//constructor
public DownloadFileAsync(HashMap<String, Object> map) {
this.map = map;
bar = (ProgressBar) map.get("bar");
// trans = (TextView) map.get("trans");
//real_time = (TextView) map.get("real_time");
test_avg = (TextView) map.get("test_avg");
//peak = (TextView) map.get("peak");
status = (TextView) map.get("status");
pp = (ImageView) map.get("pp");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count = 0;
try {
updateUI(pp, R.drawable.pause);
updateUI(status, "Connecting");
URL url = new URL(map.get("url").toString());
URLConnection conexion = url.openConnection();
conexion.connect();
final int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
updateUI(status, "Connected");
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()
+ File.separator
+ Info.getInfo(con).HTTP_DOWNLOAD_FILE_NAME);
byte data[] = new byte[1024];
long total = 0;
final long started = System.currentTimeMillis();
long sleepingTime= 0;
System.out.println("started time --"+started);
updateUI(status, "Downloading");
while ((count = input.read(data)) != -1) {
while (sleep) {
Thread.sleep(1000);
sleepingTime +=1000;
}
total += count;
final int progress = (int) ((total * 100) / lenghtOfFile);
final long speed = total;
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((speed / duration) / 1024 + " kbps");
if (pk <= (speed / duration) / 1024)
{
pk = (speed / duration) / 1024;
}
//peak.setText(pk + " kbps");
}
}
});
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
updateUI(status, "Success");
}
catch (final Exception e) {
e.printStackTrace();
updateUI(status, "Failed");
}
updateUI(pp, R.drawable.resume);
return null;
}
private void updateUI(final TextView tv, final String str) {
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
}
});
}
private void updateUI(final ImageView iv, final int id) { // may create problem
runOnUiThread(new Runnable() {
public void run() {
iv.setImageResource(id);
}
});
}
public void gotosleep(boolean val) {
sleep = val;
}
public boolean areYouSleeping() {
return sleep;
}
#Override
protected void onPostExecute(String unused) {
try {
//System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);
if (!PARALLEL_MODE //for sequence mode
&& (Info.getInfo(con).data.indexOf(map) + 1) <= Info.getInfo(con).data.size()
&& testRunning) {
/*System.out.println("Info.getInfo(con).data.indexOf(map) + 1 "+Info.getInfo(con).data.indexOf(map) + 1
+" Info.getInfo(con).data.size() "+Info.getInfo(con).data.size()+" testRunning "+testRunning);
System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);*/
System.out.println("asynclist "+asynclist.size());
asynclist.remove(0); //asynclist contains objects of (downloadAsync(map))
if(asynclist.size() > 0){
System.out.println("tlist in post execute+++"+tlist);
//DownloadFileAsync dfa = new DownloadFileAsync(tlist.get(0));
DownloadFileAsync dfa = (DownloadFileAsync) asynclist.get(0);
dfa.execute();
tlist.remove(0);
}
else{
startTests();
}
}
else if (PARALLEL_MODE && stopCount < asynclist.size() && testRunning) { //for parallel mode
System.out.println("stopCount before condition= " + stopCount);
if (stopCount == asynclist.size() -1 && testRunning) {
System.out.println("stopCount inside 1st condition= " + stopCount);
stopCount = 0;
// stopTests(0);
startTests();
System.out.println("Tests Started");
}
else {
stopCount++;
System.out.println("stopCount after increment = " + stopCount);
;
}
}
}
catch (Exception ed) {
ed.printStackTrace();
go.setText(R.string.go);
//testRunning = false;
}
}
}
For FTP:--
class FTPAsync extends AsyncTask<String, String, String> {
//private int mode = -1;
//added
long duration, pk;
private boolean sleep1 = false;
private HashMap<String, Object> map;
private ProgressBar bar;
private TextView real_time, test_avg, peak, status;
private ImageView pp;
//
public FTPAsync(int mode) {
// this.mode = mode;
}
//added
public FTPAsync(HashMap<String, Object> map) {
//Toast.makeText(con, "ftpAsync constructer is called" ,Toast.LENGTH_SHORT).show();
this.map = map;
bar = (ProgressBar) map.get("bar");
// trans = (TextView) map.get("trans");
//real_time = (TextView) map.get("real_time");
test_avg = (TextView) map.get("test_avg");
//peak = (TextView) map.get("peak");
status = (TextView) map.get("status");
pp = (ImageView) map.get("pp");
}
//
#Override
protected void onPreExecute() {
//Toast.makeText(con, "onPreExecute() is called" ,Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
int count = 0;
FTPClient ObjFtpCon = new FTPClient();
//Toast.makeText(con, "FTPasync doInBackground() is called" ,Toast.LENGTH_SHORT).show();
try {
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(0);
//real_time.setText(0 + " secs");
//test_avg.setText(0+ " kbps");
//peak.setText(0+" kbps");
}
});
updateUI(pp, R.drawable.pause);
//ObjFtpCon.connect("ftp.customhdclips.com");
ObjFtpCon.connect("ftp."+map.get("url").toString());
updateUI(status, "Connecting");
//if (ObjFtpCon.login("fstech#customhdclips.com", "fstech123")) {
if (ObjFtpCon.login(map.get("username").toString(), map.get("password").toString())) {
updateUI(status, "Connected");
// toast("Connected to FTP Server : ftp.customhdclips.com");
ObjFtpCon.enterLocalPassiveMode(); // important!
ObjFtpCon.cwd("/");// to send the FTP CWD command to the server, receive the reply, and return the reply code.
//if (mode == 0) {
if(Integer.parseInt((map.get("oprn").toString()))== 0){
// Download
System.out.println("download test is called");
File objfile = new File(
Environment.getExternalStorageDirectory()
+ File.separator + "/logo.png");
objfile.createNewFile();
FileOutputStream objFos = new FileOutputStream(objfile);
boolean blnresult = ObjFtpCon.retrieveFile("/logo.png",
objFos);
objFos.close();
if (blnresult) {
// toast("Download succeeded");
// toast("Stored at : " +
// objfile.getAbsolutePath());
}
}
else {
// Upload
System.out.println("upload test is called");
//Toast.makeText(con, "upload FTP test is called", Toast.LENGTH_SHORT).show();
//ContextWrapper context = null;
//assetManager= context.getAssets();
assetManager = getResources().getAssets();
input1 = assetManager.open("hello.txt");
final long started = System.currentTimeMillis();
int size = input1.available();
//byte[] buffer = new byte[size];
byte dataByte[] = new byte[1024];
//input1.read(buffer);
//String data = "ZK DATA TESTER TEST DATA1sdfsdf";
String data = input1.toString();
System.out.println("dat value is........"+data);
final int lenghtOfFile = data.getBytes().length;
//final int lenghtOfFile = input1.getBytes().length;
System.out.println("length of file....."+lenghtOfFile);
ByteArrayInputStream in = new ByteArrayInputStream(
data.getBytes());
//toast("Uploading /test.txt");
//Toast.makeText(con,"File Size : " +data.getBytes().length + " bytes",Toast.LENGTH_SHORT).show();
//byte b[] = new byte[1024];
long total = 0;
long sleepingTime= 0;
System.out.println("started time --"+started);
updateUI(status, "Uploading");
while ((count = in.read(dataByte)) != -1)
{
System.out.println("read value is...."+in.read(dataByte));
while (sleep1) {
Thread.sleep(1000);
System.out.println("ftp upload is in sleeping mode");
sleepingTime +=1000;
}
System.out.println("Total count --"+count);
total += count;
System.out.println("Only Total --"+total);
final int progress = (int) ((total * 100) / lenghtOfFile);
final long speed = total;
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
boolean result = ObjFtpCon.storeFile("/test.txt", input1);
//boolean result = ObjFtpCon.storeFile(map.get("file_address").toString()+"/test.txt", input1);
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((((speed / duration)*1000)*0.0078125)
+ " kbps");
/*if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}*/
if (pk <= ((speed / duration)*1000)*0.0078125) {
pk = (long)(((speed / duration)*1000)*0.0078125);
}
//peak.setText(pk + " kbps");
}
}
});
//in.close();
if (result) {
updateUI(status, "Uploaded");
// toast("Uploading succeeded");
// toast("Uploaded at /test.txt");
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
System.out.println("curreent time..... "+System.currentTimeMillis());
System.out.println("started time --"+started);
System.out.println("sleep tome...."+sleepingTime);
System.out.println("duration is....."+duration);
/*runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((speed / duration) / 1024
+ " kbps");
if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}
peak.setText(pk + " kbps");
}
}
});*/
}
/*while(!result){Thread.sleep(1000);}*/
}
in.close();
}
}
else{
System.out.println("password entered is incorrect");
//Toast.makeText(con, "Username or/and password is incorrect", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
try {
ObjFtpCon.logout();
ObjFtpCon.disconnect();
}
catch (IOException e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
return null;
}
#override
protected void onPostExecute(String unused) {
try {
//System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);
if (!PARALLEL_MODE //for sequence mode
&& (Info.getInfo(con).data.indexOf(map) + 1) <= Info.getInfo(con).data.size()
&& testRunning) {
System.out.println("ftpasynclist "+ftpasynclist.size());
ftpasynclist.remove(0); //asynclist contains objects of (FTPAsync(map))
if(ftpasynclist.size() > 0){
System.out.println("tlist in post execute+++"+ftplist);
//DownloadFileAsync dfa = new DownloadFileAsync(tlist.get(0));
FTPAsync dfa = (FTPAsync)ftpasynclist.get(0);
dfa.execute();
ftplist.remove(0);
}
else{
startTests();
}
}
else if (PARALLEL_MODE //for parallel mode
&& ftpStopCount <ftpasynclist.size()
&& testRunning) {
System.out.println("stopCount before condition= " +ftpStopCount);
if (ftpStopCount == ftpasynclist.size() -1 && testRunning) {
System.out.println("stopCount inside 1st condition= " + ftpStopCount);
ftpStopCount = 0;
// stopTests(0);
startTests();
System.out.println("Tests Started");
}
else {
ftpStopCount++;
System.out.println("stopCount after increment = " + ftpStopCount);
;
}
}
}
catch (Exception ed) {
ed.printStackTrace();
go.setText(R.string.go);
//testRunning = false;
}
super.onPostExecute(unused);
}
private void updateUI(final TextView tv, final String str) {
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
}
});
}
private void updateUI(final ImageView iv, final int id) { // may create problem
runOnUiThread(new Runnable() {
public void run() {
iv.setImageResource(id);
}
});
}
public void gotosleep(boolean val) {
sleep1 = val;
}
public boolean areYouSleeping() {
return sleep1;
}
}

Updating Activity TextView from Service

I need to download 100MB of images, so i decided that the best way is to make Service wich download it, and will show results for each file in activity. But this works like theres no service, the Activity fzreees, and unfreezes only after download all files.
Heres the code of Activity:
public class DownloadActivity extends Activity
{
String hist;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.download_activity);
startService(new Intent(this, DownloadService.class));
registerReceiver(broadcastReceiver,
new IntentFilter(DownloadService.BROADCAST_ACTION));
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent _intent)
{
updateUI(_intent);
}
};
private void updateUI(Intent intent)
{
if (intent.getBooleanExtra("exists", false))
hist = hist + "Item " +
intent.getIntExtra("item", -1) + ", image " +
intent.getIntExtra("obraz", -1) + " - DOWNLOADED\n";
else
hist = hist + "Item " +
intent.getIntExtra("item", -1) + ", image " +
intent.getIntExtra("obraz", -1) + " - ALREADY EXISTS\n";
((TextView) findViewById(R.id.dtitle)).setText("Item " +
intent.getIntExtra("item", -1) + ", image " +
intent.getIntExtra("image", -1) + ".");
((TextView) findViewById(R.id.ddetails)).setText(hist);
}
}
Code of Service:
public class DownloadService extends Service
{
public static final String BROADCAST_ACTION = "emis.katalog.grzybow.publishprogress";
Intent intent;
int counter = 0;
String postString;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId)
{
SQLiteDatabase db = new BazaGrzybowHelper(DownloadService.this).getReadableDatabase();
Cursor kursor = db.rawQuery("SELECT * FROM table", null);
InputStream in = null;
OutputStream out = null;
URL ulrn;
int nn = 1;
int pos = 1;
//out:
while(kursor.moveToNext())
{
while(kursor.getString(kursor.getColumnIndex("i_url_" + nn)) != "" ||
kursor.getString(kursor.getColumnIndex("i_url_" + nn)) != null)
{
String filename = "thg_" + pos + "_" + (nn+2) + ".jpg";
if (new File(Environment.getExternalStorageDirectory(),
"emis/katalog.grzybow/zapis_na_stale/"+filename).exists())
publishProgress(pos, nn, true);
else
{
publishProgress(pos, nn, false);
File destDir = new File(Environment.getExternalStorageDirectory(),
"emis/katalog.grzybow/zapis_na_stale");
if (!destDir.exists())
destDir.mkdirs();
destDir = null;
try
{
ulrn = new URL(kursor.getString(kursor.getColumnIndex("i_url_" + nn)));
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
in = con.getInputStream();
out = new FileOutputStream(Environment.getExternalStorageDirectory().
getPath() + "/emis/katalog.grzybow/zapis_na_stale/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
nn++;
if (nn > 10 || kursor.getString(kursor.getColumnIndex("i_url_" + nn)) == "" ||
kursor.getString(kursor.getColumnIndex("i_url_" + nn)) == null)
{
nn = 1;
break;
}
/*if (anuluj)
break out;*/
}
pos++;
}
db.close();
}
private void publishProgress(int item, int image, boolean exists)
{
intent.putExtra("item", item);
intent.putExtra("image", image);
intent.putExtra("exists", exists);
sendBroadcast(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
What am I doing wrong?
Perhaps this?
Caution: A service runs in the main thread of its hosting process—the
service does not create its own thread and does not run in a separate
process (unless you specify otherwise). This means that, if your
service is going to do any CPU intensive work or blocking operations
(such as MP3 playback or networking), you should create a new thread
within the service to do that work. By using a separate thread, you
will reduce the risk of Application Not Responding (ANR) errors and
the application's main thread can remain dedicated to user interaction
with your activities.

Android widget get touch position

is it possible to get the position of a touch when the user touches my widget on the homescreen? TIA
edit: my widget code:
public class MyWidgetProvider extends AppWidgetProvider {
public static String ACTION_WIDGET_MEMO = "comNgarsideMemoActionWidgetMemo";
public static String ACTION_WIDGET_PEN = "comNgarsideMemoActionWidgetPen";
public static String ACTION_WIDGET_ERASER = "comNgarsideMemoActionWidgetEraser";
public static String ACTION_WIDGET_UNDO = "comNgarsideMemoActionWidgetUndo";
public static String ACTION_WIDGET_REDO = "comNgarsideMemoActionWidgetRedo";
public static String ACTION_WIDGET_SAVE = "comNgarsideMemoActionWidgetSave";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
Intent memoIntent = new Intent(context, ListActivity.class);
memoIntent.setAction(ACTION_WIDGET_MEMO);
Intent penIntent = new Intent(context, MyWidgetProvider.class);
penIntent.setAction(ACTION_WIDGET_PEN);
Intent eraserIntent = new Intent(context, MyWidgetProvider.class);
eraserIntent.setAction(ACTION_WIDGET_ERASER);
Intent undoIntent = new Intent(context, MyWidgetProvider.class);
undoIntent.setAction(ACTION_WIDGET_UNDO);
Intent redoIntent = new Intent(context, MyWidgetProvider.class);
redoIntent.setAction(ACTION_WIDGET_REDO);
Intent saveIntent = new Intent(context, MyWidgetProvider.class);
saveIntent.setAction(ACTION_WIDGET_SAVE);
PendingIntent memoPendingIntent = PendingIntent.getActivity(context, 0, memoIntent, 0);
PendingIntent penPendingIntent = PendingIntent.getBroadcast(context, 0, penIntent, 0);
PendingIntent eraserPendingIntent = PendingIntent.getBroadcast(context, 0, eraserIntent, 0);
PendingIntent undoPendingIntent = PendingIntent.getBroadcast(context, 0, undoIntent, 0);
PendingIntent redoPendingIntent = PendingIntent.getBroadcast(context, 0, redoIntent, 0);
PendingIntent savePendingIntent = PendingIntent.getBroadcast(context, 0, saveIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.iconBtn, memoPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.penBtn, penPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.eraserBtn, eraserPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.undoBtn, undoPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.redoBtn, redoPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.saveBtn, savePendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
if (intent.getAction().equals(ACTION_WIDGET_PEN)) {
} else if (intent.getAction().equals(ACTION_WIDGET_ERASER)) {
} else if (intent.getAction().equals(ACTION_WIDGET_UNDO)) {
} else if (intent.getAction().equals(ACTION_WIDGET_REDO)) {
} else if (intent.getAction().equals(ACTION_WIDGET_SAVE)) {
}
super.onReceive(context, intent);
}
}
}
Maybe this will give you an idea...
PressureDynamics.java
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.util.Log;
/**
* Keyboard sensor
*/
public class PressureDynamics extends Thread implements FeatureExtractor{
public static final String AVG_TOUCH_PRESSURE = "Avg_Touch_Pressure";
public static final String AVG_TOUCH_AREA = "Avg_Touch_Area";
private static final int EVENT_BYTE_SIZE = 16;
private InputStream _fis = null;
private boolean _shouldRun;
private Map<String, TouchScreenSensor> _sensors;
public PressureDynamics(Context context, Collection<FeatureInfo> featureInfos,
Long timeStamp){
super("Pressure Dynamics Feature Extractor Thread");
_shouldRun = true;
_sensors = new HashMap<String, TouchScreenSensor>();
int featureCount = 0;
for (FeatureInfo featureInfo : featureInfos){
String name = featureInfo.name;
try{
if (name.equalsIgnoreCase(AVG_TOUCH_PRESSURE)){
TouchScreenSensor s = new AvgTouchPressureSensor(featureInfo);
_sensors.put(AVG_TOUCH_PRESSURE, s);
}else if (name.equalsIgnoreCase(AVG_TOUCH_AREA)){
TouchScreenSensor s = new AvgTouchAreaSensor(featureInfo);
_sensors.put(AVG_TOUCH_AREA, s);
}else{
Log.e(FE_TAG, "Unhandled feature by " + getClass().getCanonicalName()
+ ": " + name);
continue;
}
++featureCount;
}catch(RuntimeException e){
Log.e(FE_TAG, "Unable to initialize feature: " + name, e);
}
}
if (featureCount == 0){
throw new FeatureExtractorInitException("No features of "
+ getClass().getCanonicalName() + " could be initialized");
}
_fis = openTouchScreenInputStream();
start();
}
private static InputStream openTouchScreenInputStream(){
final String HTC_TOUCH_SCREEN_INPUT_FILEPATH = "/dev/input/event1";
LocalServerConn localServerConn;
try{
localServerConn = LocalServerConn.getInstance();
localServerConn.runLocalServer();
}catch(Exception e){
throw new FeatureExtractorInitException(
"Unable to collect Touch Screen features", e);
}
try{
FileDescriptor[] fdArr = localServerConn
.sendFileDescriptorReq(HTC_TOUCH_SCREEN_INPUT_FILEPATH);
if (fdArr == null || fdArr.length == 0){
throw new FeatureExtractorInitException("Can't open keyboard device");
}
return new FileInputStream(fdArr[0]);
}catch(IOException e){
throw new FeatureExtractorInitException("Can't open keyboard input stream: "
+ e.getMessage(), e);
}
}
public void close(){
_shouldRun = false;
}
public void collectData(List<MonitoredData> monitoredData, ParcelableDate endTime){
for (Sensor s : _sensors.values()){
s.collectData(monitoredData, endTime);
}
}
public void run(){
int n;
int pos = 0;
byte[] buffer = new byte[256];
for (;;){
try{
n = _fis.read(buffer, pos, EVENT_BYTE_SIZE);
/*
* check if we are shutting down - this may have the thread hanging around
* until the next touch event comes in
*/
if (_shouldRun == false){
break;
}
pos += n;
// Log.v(FE_TAG, "read touch screen event: " + n + " bytes\n");
if (pos >= EVENT_BYTE_SIZE){
long currentTimeMillis = System.currentTimeMillis();
TouchEvent touchScreenEvent = new TouchEvent(buffer,
currentTimeMillis);
updateSensors(touchScreenEvent, currentTimeMillis);
pos -= EVENT_BYTE_SIZE;
}
}catch(IOException e){
Log.e(FE_TAG, e.getMessage(), e);
}
}
}
private void updateSensors(TouchEvent touchScreenEvent, long currentTimeMillis){
try{
// currently filter out all non preassure event types
//
switch ((int)touchScreenEvent.getCode()){
case TouchEvent.X_POS_EVENT:
case TouchEvent.Y_POS_EVENT:
case TouchEvent.TOUCH_DEVICE_TYPE_EVENT:
break;
case TouchEvent.ABS_PRESSURE_EVENT:
_sensors.get(AVG_TOUCH_PRESSURE).updateSensor(touchScreenEvent,
currentTimeMillis);
break;
case TouchEvent.ABS_TOOL_WIDTH_EVENT:
_sensors.get(AVG_TOUCH_AREA).updateSensor(touchScreenEvent,
currentTimeMillis);
break;
default:
Log.e(FE_TAG, "unrecognized touch event code :"
+ touchScreenEvent.getCode());
break;
}
}catch(Exception e){
Log.e(FE_TAG, e.getMessage(), e);
}
}
public String toString(){
return getClass().getSimpleName();
}
private static abstract class TouchScreenSensor extends Sensor{
private TouchScreenSensor(String name, FeatureInfo info){
//super(name, info.getValueTimeout());
super(name);
}
public abstract void updateSensor(TouchEvent event, long currentTimeMillis);
}
private static class AvgTouchPressureSensor extends TouchScreenSensor{
public AvgTouchPressureSensor(FeatureInfo info){
super(AVG_TOUCH_PRESSURE, info);
}
public void updateSensor(TouchEvent event, long currentTimeMillis){
addToAvg(event.getValue(), currentTimeMillis);
}
}
private static class AvgTouchAreaSensor extends TouchScreenSensor{
public AvgTouchAreaSensor(FeatureInfo info){
super(AVG_TOUCH_AREA, info);
}
public void updateSensor(TouchEvent event, long currentTimeMillis){
addToAvg(event.getValue(), currentTimeMillis);
}
}
}
Sensor.java
import java.util.List;
public class Sensor{
private final String _name;
private Double _avg;
private int _count;
private long _lastValueUpdateTime;
/**
* Constructor
*
* #param name The name of the feature that is collected by this sensor
* #param valueTimeout The time period of no value changes it takes for the current
* value to reset to the initial value (in millis)
*/
public Sensor(String name){
_lastValueUpdateTime = 0;
_name = name;
_avg = null;
_count = 0;
}
public void collectData(List<MonitoredData> monitoredData, ParcelableDate endTime){
Double value = getValue(endTime.getTime());
if (value != null){
value = Utils.truncateDouble(value);
}
monitoredData.add(new MonitoredData(_name, value, endTime));
}
public Double getValue(long time){
if (time - _lastValueUpdateTime > MainActivity.getAgentLoopTime()){
_avg = null;
_count = 0;
}
return _avg;
}
public String getName(){
return _name;
}
public void addToAvg(double value, long time){
Double avg = getValue(time);
if (avg == null){
avg = value; // Initial value
}else{
value = (avg * _count + value) / (_count + 1);
}
++_count;
_avg = value;
_lastValueUpdateTime = time;
}
#Override
public String toString(){
return _name;
}
}
TouchEvent.java
import android.util.Log;
import dt.util.Utils;
public class TouchEvent{
public static final int ABS_PRESSURE_EVENT = 0x18;
public static final int ABS_TOOL_WIDTH_EVENT = 0x1c;
public static final int X_POS_EVENT = 0x0;
public static final int Y_POS_EVENT = 0x1;
/* type of touching device ie. finger, stylus etc. */
public static final int TOUCH_DEVICE_TYPE_EVENT = 0x14a;
// private final long _timeStamp;
// private final int _sec;
// private final int _usec;
// 3, 1, 0 - ?
// private final long _type;
// different event types have different codes
private final long _code;
private final int _value;
//
public TouchEvent(byte[] _buffer, long currentTimeMillis){
int pos;
byte b[] = new byte[4];
byte s[] = new byte[2];
// _timeStamp = currentTimeMillis;
pos = 0;
// _sec = Utils.LittleEndianBytesToInt(_buffer);
pos += 4;
System.arraycopy(_buffer, pos, b, 0, 4);
// _usec = Utils.LittleEndianBytesToInt(b);
pos += 4;
// _type = Utils.LittleEndianBytesToUShort(s);
pos += 2;
System.arraycopy(_buffer, pos, s, 0, 2);
_code = Utils.littleEndianBytesToUShort(s);
pos += 2;
System.arraycopy(_buffer, pos, b, 0, 4);
_value = Utils.littleEndianBytesToInt(b);
if (_code != X_POS_EVENT && _code != Y_POS_EVENT
&& _code != TOUCH_DEVICE_TYPE_EVENT && _code != ABS_PRESSURE_EVENT
&& _code != ABS_TOOL_WIDTH_EVENT){
Log.d(FE_TAG, "unrecognized touch event code :" + _code);
}
}
public long getCode(){
return _code;
}
public double getValue(){
return _value;
}
}
FeatureInfo.java
import java.util.HashMap;
public class FeatureInfo{
/** The name of the feature */
public final String name;
/** The parameters relevant to the feature */
public final HashMap<String, String> params;
/**
* Constructs a FeatureInfo object from the given parameters
*
* #param name The name of the feature
* #param params The parameters relevant to the feature
*/
public FeatureInfo(String name, HashMap<String, String> params){
this.name = name;
this.params = (params == null) ? new HashMap<String, String>() : params;
}
#Override
public String toString(){
return name;
}
public int getTimeWindow() throws IllegalArgumentException{
final String paramName = "Time_Window";
try{
int timeWindow = Integer.parseInt(params.get(paramName)) * 1000;
if (timeWindow <= 0){
throw new IllegalArgumentException("Must be a positive integer");
}
return timeWindow;
}catch(Exception e){// NullPointer or Parsing
throw new IllegalArgumentException("Corrupt parameter: " + paramName
+ " in feature " + name, e);
}
}
// public int getTimeWindow() throws IllegalArgumentException{
// final String paramName = "Time_Window";
// try{
// int timeWindow = Integer.parseInt(params.get(paramName)) * 1000;
// if (timeWindow <= 0){
// throw new IllegalArgumentException("Must be a positive integer");
// }
// return timeWindow;
// }catch(Exception e){// NullPointer or Parsing
// throw new IllegalArgumentException("Corrupt parameter: " + paramName
// + " in feature " + name, e);
// }
// }
public int getValueTimeout() throws IllegalArgumentException{
final String paramName = "Value_Timeout";
try{
int valueTimeout = Integer.parseInt(params.get(paramName)) * 1000;
if (valueTimeout <= 0){
throw new IllegalArgumentException("Must be a positive integer");
}
return valueTimeout;
}catch(Exception e){// NullPointer or Parsing
throw new IllegalArgumentException("Corrupt parameter: " + paramName
+ " in feature " + name, e);
}
}
public double getMovieAverageWeight() throws IllegalArgumentException{
final String paramName = "Moving_Average_Weight";
try{
double movingAverageWeight = Double.parseDouble(params.get(paramName));
if (movingAverageWeight < 0 || movingAverageWeight > 1){
throw new IllegalArgumentException("Must be positive and 1.0 at most");
}
return movingAverageWeight;
}catch(Exception e){// NullPointer or Parsing
throw new IllegalArgumentException("Corrupt parameter: " + paramName
+ " in feature " + name, e);
}
}
public boolean getIncludeEventTimes(){
final String paramName = "Include_Event_Times";
return Boolean.parseBoolean(params
.get(paramName));
}
public boolean getIncludeMaximalEntity(){
final String paramName = "Include_Maximal_Entity";
return Boolean.parseBoolean(params
.get(paramName));
}
}
MonitoredData.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
#SuppressWarnings("unchecked")
public class MonitoredData implements Map, Parcelable{
public static final int DEFAULT = 0;
public static final int HAS_EXTRAS = 1;
protected String _name;
protected ParcelableDate _startTime, _endTime;
protected Object _value;
protected Bundle _extras;
public static final Parcelable.Creator<MonitoredData> CREATOR = new Parcelable.Creator<MonitoredData>(){
public MonitoredData createFromParcel(Parcel in){
ClassLoader cl = ParcelableDate.class.getClassLoader();
String name = in.readString();
Object value = in.readValue(null);
ParcelableDate startTime = (ParcelableDate)in.readParcelable(cl);
ParcelableDate endTime = (ParcelableDate)in.readParcelable(cl);
Bundle extras = in.readBundle();
MonitoredData monitoredData = new MonitoredData(name, value, startTime,
endTime);
if (extras != null){
monitoredData.setExtras(extras);
}
return monitoredData;
}
public MonitoredData[] newArray(int size){
return new MonitoredData[size];
}
};
private static DateFormat _sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
public MonitoredData(String name, Object value, Date endTime){
this(name, value, new ParcelableDate(endTime), new ParcelableDate(endTime));
}
public MonitoredData(String name, Object value, ParcelableDate endTime){
this(name, value, endTime, endTime);
}
public MonitoredData(String name, Object value, Date startTime, Date endTime){
this(name, value, new ParcelableDate(startTime), new ParcelableDate(endTime));
}
public MonitoredData(String name, Object value, Date startTime, ParcelableDate endTime){
this(name, value, new ParcelableDate(startTime), endTime);
}
public MonitoredData(String name, Object value, ParcelableDate startTime,
ParcelableDate endTime){
_name = name;
_startTime = startTime;
_endTime = endTime;
_value = value;
_extras = null;
}
public void setExtras(Bundle extras){
_extras = extras;
}
public Map<String, Object> toMap(){
TreeMap<String, Object> map = new TreeMap<String, Object>();
map.put("Name", _name);
map.put("StartTime", _startTime);
map.put("EndTime", _endTime);
map.put("Value", _value);
return map;
}
public String conciseToString(){
String extrasToString = (_extras != null && !_extras.isEmpty()) ? " - "
+ _extras.toString() : "";
return "{" + getName() + " = " + getValue() + "}" + extrasToString;
}
public int describeContents(){
return (_extras == null || _extras.isEmpty()) ? DEFAULT : HAS_EXTRAS;
}
public ParcelableDate getEndTime(){
return _endTime;
}
public String getName(){
return _name;
}
public ParcelableDate getStartTime(){
return _startTime;
}
public Object getValue(){
return _value;
}
public Bundle getExtras(){
return _extras;
}
public String toString(){
StringBuilder sb = new StringBuilder("{");
sb.append("Name = " + getName() + ", ");
sb.append("Value = " + getValue() + ", ");
sb.append("StartTime = " + _sdf.format(getStartTime()) + ", ");
sb.append("EndTime = " + _sdf.format(getEndTime()));
sb.append("}");
return sb.toString();
}
public void writeToParcel(Parcel dest, int flags){
dest.writeString(getName());
dest.writeValue(getValue());
dest.writeParcelable(getStartTime(), 0);
dest.writeParcelable(getEndTime(), 0);
dest.writeBundle(_extras);
}
public void clear(){
throw new UnsupportedOperationException();
}
public boolean containsKey(Object key){
throw new UnsupportedOperationException();
}
public boolean containsValue(Object value){
throw new UnsupportedOperationException();
}
public Set entrySet(){
return Collections.unmodifiableSet(toMap().entrySet());
}
public Object get(Object key){
throw new UnsupportedOperationException();
}
public boolean isEmpty(){
throw new UnsupportedOperationException();
}
public Set keySet(){
throw new UnsupportedOperationException();
}
public Object put(Object key, Object value){
throw new UnsupportedOperationException();
}
public void putAll(Map arg0){
throw new UnsupportedOperationException();
}
public Object remove(Object key){
throw new UnsupportedOperationException();
}
public int size(){
throw new UnsupportedOperationException();
}
public Collection values(){
throw new UnsupportedOperationException();
}
/**
* Returns the value of the monitored data as a Double.
* Null is returned if the value is null or is can not be converted to double.
*
* #return The value as double if possible, null otherwise
*/
public Double mdToDouble(){
Double sample;
Object val = getValue();
if (val instanceof Double){
sample = ((Double)val).doubleValue();
}else if (val instanceof Long){
sample = ((Long)val).doubleValue();
}else if (val instanceof Integer){
sample = ((Integer)val).doubleValue();
}else{
sample = null;
}
return sample;
}
}
Utils.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.content.res.Resources;
import android.os.Environment;
import android.widget.Toast;
public class Utils{
public static byte[] append(byte[] first, byte[] second){
byte[] bytes;
bytes = new byte[first.length + second.length];
System.arraycopy(first, 0, bytes, 0, first.length);
System.arraycopy(second, 0, bytes, first.length, second.length);
return bytes;
}
public static int bytesToInt(byte[] bytes){
return (bytes[3] & 0xFF) | ((bytes[2] & 0xFF) << 8) | ((bytes[1] & 0xFF) << 16)
| ((bytes[0] & 0xFF) << 24);
}
public static int littleEndianBytesToInt(byte[] bytes){
return (bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[2] & 0xFF) << 16)
| ((bytes[3] & 0xFF) << 24);
}
public static long littleEndianBytesToUShort(byte[] arr){
return (arr[1] << 8) | arr[0];
}
public static void displayShortAlert(Context context, String message){
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static XmlPullParser getXPP(Context context, int resourceId, boolean isBinary){
XmlPullParser xpp;
Resources resources = context.getResources();
if (isBinary){
return resources.getXml(resourceId);
}else{
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
xpp = factory.newPullParser();
xpp.setInput(resources.openRawResource(resourceId), null);
}catch(XmlPullParserException e){
xpp = null;
}
return xpp;
}
}
public static byte[] intToBytes(int i){
byte[] bytes = new byte[]{(byte)((i >> 24) & 0xff), (byte)((i >> 16) & 0xff),
(byte)((i >> 8) & 0xff), (byte)((i) & 0xff)};
return bytes;
}
/*
* debugging
*/
public static String printByteArray(byte[] bytes, int len){
StringBuilder sb = new StringBuilder();
sb.append("msg len: " + len + " :");
Formatter f = new Formatter(sb);
for (int i = 0; i < len; i++){
f.format("%2x", bytes[i]);
}
sb.append("\n");
return sb.toString();
}
public static List<Integer> getPids(String fileName){
String line;
int pidIndex = -1;
try{
Process p = Runtime.getRuntime().exec("ps " + fileName);
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()), 256);
if ((line = br.readLine()) == null){
throw new IllegalStateException("Unable to read ps output");
}
String[] tokens = line.split(" +");
for (int i = 0; i < tokens.length; ++i){
if (tokens[i].equalsIgnoreCase("pid")){
pidIndex = i;
}
}
if (pidIndex < 0){
throw new IllegalStateException("Unable to locate pid field in ps output");
}
List<Integer> pids = new ArrayList<Integer>();
while ((line = br.readLine()) != null){
tokens = line.split(" +");
assert tokens.length < 9;
try{
pids.add(Integer.parseInt(tokens[pidIndex]));
}catch(NumberFormatException e){
throw new IllegalStateException("Pid is not an integer");
}
}
br.close();
return pids;
}catch(Exception e){
throw new IllegalStateException("Unable to read running process through ps: "
+ e.getMessage(), e);
}
}
public static void killProcesses(List<Integer> pids){
for (Integer pid : pids){
android.os.Process.killProcess(pid);
}
}
public static void killProcesses(String processName){
killProcesses(getPids(processName));
}
public static void suKillProcesses(List<Integer> pids){
StringBuilder cmd = new StringBuilder("kill");
for (Integer pid : pids){
cmd.append(" ").append(pid);
}
try{
Runtime.getRuntime().exec(new String[]{"su", "-c", cmd.toString()});
}catch(IOException e){
e.printStackTrace();
}
}
public static void suKillProcess(int pid){
try{
Runtime.getRuntime().exec(new String[]{"su", "-c", "kill " + pid});
}catch(IOException e){
e.printStackTrace();
}
}
public static void suKillProcesses(String processName){
suKillProcesses(getPids(processName));
}
public static double truncateDouble(double d){
long l = Math.round(d * 100);
return l / 100.0;
}
public static double calcMovingAvg(double oldVal, double newVal, double newValWeight){
return (oldVal * (1.0 - newValWeight)) + (newValWeight * newVal);
}
public static double calcAvg(double oldAvg, int count, double newVal){
return (oldAvg * count + newVal) / (count + 1);
}
public static void writeLogToFile(Context context, boolean onSdcard, String prefix, int timeWindowInSeconds) throws Exception{
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
final DateFormat logDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
final long currentTime = System.currentTimeMillis();
final long startTime = currentTime - timeWindowInSeconds * 1000;
final String currentYear = Calendar.getInstance().get(Calendar.YEAR) + "-";
final String logFileName = prefix + sdf.format(new Date(currentTime)) + ".log";
BufferedReader logcatIn;
Process logcat;
OutputStream logFile;
try{
logcat = Runtime.getRuntime().exec("logcat -v time -d *:d");
logcatIn = new BufferedReader(new InputStreamReader(logcat
.getInputStream()), 1024);
}catch(IOException e){
throw new Exception("Unable to launch logcat: " + e.getMessage(), e);
}
try{
if (onSdcard){
logFile = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), logFileName));
}else{
logFile = context.openFileOutput(logFileName, 0);
}
}catch(IOException e){
throw new Exception("Unable to create log file: " + e.getMessage(), e);
}
PrintWriter pw = new PrintWriter(logFile, false);
String line;
long logLineTime;
while ((line = logcatIn.readLine()) != null){
logLineTime = logDF.parse(currentYear + line.substring(0, line.indexOf(".") + 4)).getTime();
if (logLineTime >= startTime){
pw.println(line);
}
}
pw.flush();
pw.close();
logcatIn.close();
logcat.destroy();
}
}
FeatureExtractor.java
import java.util.List;
/**
* A class capable of extracting one or more features. It MUST have a public constructor
* with the following parameters in this order:
* <ul>
* <li>Context context</li>
* <li>Collection<FeatureInfo> featureInfos</li>
* <li>Long timeStamp</li>
* </ul>
*
*/
public interface FeatureExtractor{
/**
* Invoked during a data collection. It is up to the extractor to add the data
* relevant to it's monitored features to the monitoredData list.
*
* #param monitoredData The overall collected data (from all extractors) so far
* #param endTime The time of the current data collection
*/
public void collectData(List<MonitoredData> monitoredData, ParcelableDate endTime);
/**
* Invoked when the feature extractor is no longer needed. This is the place to
* release any resources, unregister any listeners, close any threads, etc.
*/
public void close();
}
FeatureExtractorInitException.java
public class FeatureExtractorInitException extends RuntimeException{
private static final long serialVersionUID = 1L;
public FeatureExtractorInitException(String message){
super(message);
}
public FeatureExtractorInitException(String message, Throwable t){
super(message, t);
}
public FeatureExtractorInitException(Throwable t){
super(t);
}
}
For example if you had an imageView one way of fetching coordinates is...
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
int[] values = new int[2];
view.getLocationOnScreen(values);
Log.d("X & Y",values[0]+" "+values[1]);
}
});
Check out these ST threads:
How to get imageView inside onTouchEvent(MotionEvent event) in android
Android: How do I get the x y coordinates within an image / ImageView?
OnClickListener - x,y location of event?
Find layout with x,y coordinate
If you use reuf codes,you will need to use ParcelableData.java.I add ParcelableData class that found here and hope to save your time:
package dev.drsoran.moloko.service.parcel;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
public class ParcelableDate implements Parcelable
{
public static final Parcelable.Creator< ParcelableDate > CREATOR = new Parcelable.Creator< ParcelableDate >()
{
public ParcelableDate createFromParcel( Parcel source )
{
return new ParcelableDate( source );
}
public ParcelableDate[] newArray( int size )
{
return new ParcelableDate[ size ];
}
};
private final Date date;
public ParcelableDate( final Date date )
{
this.date = date;
}
public ParcelableDate( long millis )
{
this.date = new Date( millis );
}
public ParcelableDate( Parcel source )
{
date = new Date( source.readLong() );
}
public Date getDate()
{
return date;
}
#Override
public String toString()
{
return date.toString();
}
public int describeContents()
{
return 0;
}
public void writeToParcel( Parcel dest, int flags )
{
dest.writeLong( date.getTime() );
}
}

Categories

Resources