Sharing button with only facebook and twitter apps in dialog - android

I want to add sharing button to my app, and I have done the following:
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
/* Fill it with Data */
shareIntent.setType("plain/text");
shareIntent.putExtra(Intent.EXTRA_TEXT, "www.somesite.com");
/* Send it off to the Activity-Chooser */
startActivity(Intent.createChooser(shareIntent, "Share..."));
It shows a dialog and I dont see in this dialog facebook and twitter. I do have both these applicaitons installed in my phone. So, first question is why it doesnt show them? And second if later I will make them somehow appear in the phone, how to make that dialog show only facebook and twitter, and if user does not have them, ask user just to install it by giving link to official app.

You can check them by using below code,
How to customize share intent in Android?
Android Intent for Twitter application
I've seen a lot of questions about modifying the app chooser, and they
all seem to state that no, you cannot change the built-in app chooser,
but you can create a custom app chooser using queryIntentActivities()
in the PackageManager class.
try{
ApplicationInfo info = getPackageManager().getApplicationInfo("com.facebook.katana", 0 );
return true;
} catch( PackageManager.NameNotFoundException e ){
return false;
}
try{
ApplicationInfo info = getPackageManager().getApplicationInfo("com.twitter.android", 0 );
return true;
} catch( PackageManager.NameNotFoundException e ){
return false;
}

After Successfully login completion.
public class ShareOnTwitterTrophy extends AsyncTask<String, Integer, Long> {
private Activity mActivity;
private Bitmap bitmap;
public ShareOnTwitterTrophy(Activity mActivity,Bitmap bitmap) {
this.mActivity=mActivity;
this.bitmap=bitmap;
}
protected void onPreExecute() {
}
#Override
protected Long doInBackground(String... arg0) {
long result = 0;
// TwitterSession twitterSession = new TwitterSession(activity);
// AccessToken accessToken = twitterSession.getAccessToken();
AccessToken accessToken = new UserSharedPreference(mActivity).getTwitterAccessToken();
if (accessToken != null) {
Configuration conf = new ConfigurationBuilder()
.setOAuthConsumerKey("your key")
.setOAuthConsumerSecret(
"your secret")
.setOAuthAccessToken(accessToken.getToken())
.setOAuthAccessTokenSecret(accessToken.getTokenSecret())
.build();
ImageUploadFactory factory = new ImageUploadFactory(conf);
ImageUpload upload = factory.getInstance();
Log.d("", "Start sending image...");
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
// you can create a new file name "test.jpg" in sdcard
// folder.
String imagePath = Environment
.getExternalStorageDirectory()
+ File.separator
+ "test.jpg";
File f = new File(imagePath);
f.createNewFile();
// write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
upload.upload(f, "");
Log.e("Image Uploaded", "yayeeeee");
result = 1;
} catch (Exception e) {
Log.e("image upload failed", "awwwww :(");
e.printStackTrace();
}
return result;
}
return result;
}
#Override
protected void onPostExecute(Long result) {
if (result == 1)
Toast.makeText(
mActivity,
mActivity
.getString(R.string.twitter_shared_successfully),
Toast.LENGTH_LONG).show();
}

Related

programmatically update apk (download&start installation) Android API v26

I read all of the solutions about this problem.Also I know it can be considered as duplicated but it is not.
I see Error: Try Again toast message and I see Update Error log message.
I think at android v26 changed somethings about intent.setDataAndType or I dont know why this is not working.
Also I get the permissions something like this code
ActivityCompat.requestPermissions(Update.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
Problem can not be solved. I just want to do download and install apk file.
AndroidManifest.xml (I added write permission)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Update.java
package com.my.testapp;
public class Update extends AppCompatActivity {
ProgressDialog bar;
private static String TAG = "Update";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadNewVersion().execute();
}
class DownloadNewVersion extends AsyncTask<String,Integer,Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bar = new ProgressDialog(Update.this);
bar.setCancelable(false);
bar.setMessage("Downloading...");
bar.setIndeterminate(true);
bar.setCanceledOnTouchOutside(false);
bar.show();
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
bar.setIndeterminate(false);
bar.setMax(100);
bar.setProgress(progress[0]);
String msg = "";
if(progress[0]>99){
msg="Finishing... ";
}else {
msg="Downloading... "+progress[0]+"%";
}
bar.setMessage(msg);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
bar.dismiss();
if(result){
Toast.makeText(getApplicationContext(),"Update Done",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Error: Try Again",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected Boolean doInBackground(String... arg0) {
Boolean flag = false;
try {
URL url = new URL("http://mydownloadurl.com/_download/update.apk");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory()+"/Download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file,"app-debug.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
int total_size = 277962;//size of apk
byte[] buffer = new byte[1024];
int len1 = 0;
int per = 0;
int downloaded=0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
downloaded +=len1;
per = (int) (downloaded * 100 / total_size);
publishProgress(per);
}
fos.close();
is.close();
OpenNewVersion(PATH);
flag = true;
} catch (Exception e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
}
return flag;
}
}
void OpenNewVersion(String location) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(location + "app-debug.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Commonsware thanks a lot, I waste my 2-3 hours to do different ways.
Actually I added this code before but the problem was not solved.
I tried again and it worked, it might be lazy solution but it is working.
This url have more info about the problem ,other solutions can be applied,
but it is enough for me.
if(Build.VERSION.SDK_INT>=24){
try{
Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
m.invoke(null);
}catch(Exception e){
e.printStackTrace();
}
}
It is totally fixed thank you very much again.
Application also need this storage permission.
ActivityCompat.requestPermissions(Update.this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE

Programmatically Downloading and Installing APK [duplicate]

This question already has answers here:
Android: install .apk programmatically [duplicate]
(4 answers)
Closed 5 years ago.
I've seen a few answers related to this but can't quite seem to find what I'm looking for. Say I have a self hosted app. Now say I've made some changes to that app and would like to let the user know within the app that there is an update available. I can get the app to successfully download the apk file and begin installing it. After the installation is "finished" the app closes out. When I restart the app none of the changes I've made have been applied. So it appears the installation has failed, but there was no apparent crash. However, when I install the apk that was downloaded from the Downloads manager it installs just fine and the changes I have made are applied. Any ideas? Here is the section of code I use to download and install programmatically:
String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = "TheApp.apk";
destination += fileName;
final Uri uri = Uri.parse("file://" + destination);
String url = "myapplocation";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading necessary update files.");
request.setTitle("Updating The App");
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(uri,
manager.getMimeTypeForDownloadedFile(downloadId));
startActivityForResult(install, 0);
unregisterReceiver(this);
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Get VersionName and VersionCode for current Running application.
code:
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
Common.VersionName = pInfo.versionName;
Common.VersionCode = pInfo.versionCode;
Log.e("VersionCode", ">>>>>>>>>>" + Common.VersionCode + Common.VersionName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
**Check the Version Names**
if (!Common.VersionName.equals(Common.VersionNamefromWebApi)) {
AlertDialogUpdate(MakeTransactionActivity.this, Common.AppUpdateTitle, "YokoYepi Version" + Common.VersionNamefromWebApi + " available.");
}
**Alert Dialog Box**
public void AlertDialogUpdate(Activity activity, String title, CharSequence message) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setCancelable(false);
if (title != null) builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new DownloadNewVersion().execute();
dialog.dismiss();
}
});
builder.show();
}
**Download and Install the .apk file from URL**
class DownloadNewVersion extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bar = new ProgressDialog(MakeTransactionActivity.this);
bar.setCancelable(false);
bar.setMessage("Downloading...");
bar.setIndeterminate(true);
bar.setCanceledOnTouchOutside(false);
bar.show();
stoptimertask();
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
bar.setIndeterminate(false);
bar.setMax(100);
bar.setProgress(progress[0]);
String msg = "";
if (progress[0] > 99) {
msg = "Finishing... ";
} else {
msg = "Downloading... " + progress[0] + "%";
}
bar.setMessage(msg);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
startTimer();
bar.dismiss();
if (result) {
Toast.makeText(getApplicationContext(), "Update Done",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error: Try Again",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected Boolean doInBackground(String... arg0) {
Boolean flag = false;
try {
String PATH;
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if (isSDPresent) {
PATH = Environment.getExternalStorageDirectory() + "/Download/";
} else {
PATH = Environment.getDataDirectory() + "/Download/";
}
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "yokoyepi.apk");
if (outputFile.exists()) {
outputFile.delete();
}
// Download File from url
URL u = new URL(Common.AppUpdateURL);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
// Install dowloaded Apk file from Devive----------------
OpenNewVersion(PATH);
flag = true;
} catch (MalformedURLException e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
} catch (IOException e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
} catch (Exception e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
}
return flag;
}
}
void OpenNewVersion(String location) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(location + "yokoyepi.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
// if your not install u should call the function in onResume().
// again it will check whether apk updated or not.

AsyncTask println needs a message No Exception thrown

My AsyncTask is logging an error "println needs a message" however no exception is being thrown in my class. The task is started in an Activity which implements a callback interface I wrote called TaskCallback. In the onPostExecute() it calles the callback in the Activity. From this callback, I run another AsyncTask. Below is the code:
public class SaveImageTask extends AsyncTask<byte[], String, File> {
private static final String IMAGE_DATA_PATH =
Environment.getExternalStorageDirectory().toString() + "/MyAppFolder/AppImages/";
private static final String TAG = "SaveImageTask";
private TaskCallback mTaskCallback;
private ProgressDialog mProgressDialog;
public SaveImageTask(TaskCallback taskCallback) {
mTaskCallback = taskCallback;
}
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog((Context) mTaskCallback);
mProgressDialog.setMessage("Saving Image...");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected File doInBackground(byte[]... data) {
File imageFile = createOutputPictureFile();
if(imageFile == null) {
return null;
}
try {
Bitmap image = BitmapFactory.decodeByteArray(data[0], 0, data[0].length);
FileOutputStream out = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
return imageFile;
}
#Override
public void onPostExecute(File imageFile) {
if(mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
if(mTaskCallback != null) {
mTaskCallback.onTaskComplete(imageFile);
}
}
private File createOutputPictureFile() {
File imageStorageDirectory = new File(IMAGE_DATA_PATH);
// If the default save directory doesn't exist, try and create it
if (!imageStorageDirectory.exists()){
if (!imageStorageDirectory.mkdirs()){
//Log.e(TAG, "Required media storage does not exist");
return null;
}
}
// Create a timestamp and use it as part of the file name
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.UK);
String timeStamp = dateFormat.format(new Date());
String fileName = "img_"+ timeStamp + ".jpg";
return new File (imageStorageDirectory, fileName);
}
}
The onTaskComplete(File file) looks like this:
#Override
public void onTaskComplete(File file) {
if(file == null) {
Util.showToast(this, "Save Failed.", Toast.LENGTH_SHORT);
return;
}
notifyDeviceOfNewFile(file);
ProcessImageTask pit = new ProcessImageTask(this);
pit.execute(file);
}
And the error logged is:
E/SaveImageTask: println needs a message
As it says in the title, no exception is thrown and the code actually does what it is supposed to do. I've narrowed the issue down to this line of code in the callback:
pit.execute(file);
If I comment out this line the error doesn't appear. I'm a bit stumped on what's going on. If I remove all logging in my SaveImageTask it still appears so something else is logging it.
There is a reason why a exception is not thrown, because you catch it. That is the whole concept about try-catch.
try {
Bitmap image = BitmapFactory.decodeByteArray(data[0], 0, data[0].length);
FileOutputStream out = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
// normally you do stuff here when it fails.
}
I believe "println needs a message" is what's shown if you pass a null to Log.x(). You're probably getting an IOException - e.printstacktrace() will probably give you a better idea of why.
Ok, turns out I was being an idiot and the error was from another class which for some reason had the same TAG it was logging with. Thank you for your input and suggestions, an important lesson about copy/pasting code was learned today.

how can I access Picasso' s cached image to make a share intent?

I' m using Picasso to help the cache of images.
The question is, how can I access the downloaded image to make a share intent?
any ideas? thanks!
I hope you can understand my question :-)
Sorry for my delay, I found a solution, but, not a good one...
First, I really searched for a while and looked at the code of Picasso. It seems like you should provide your own downloader and other stuff. But then, why should I use the lib...
And then, I suppose it's Picasso's design / architecture to just cache the file in the internal storage. Maybe because the external storage is not always available (like the user may plug in his SD card to his computer), or maybe because the external storage is not as fast as the internal... That's my guess. In a word, other apps cannot access the internal storage of the current app, so the share cannot be done.
Thus, I made a really ordinary solution. I just wait for Picasso to give the Bitmap, and compress it to a file in the external file, then do the share. It seems like a bad solution, but it really solves the problem, yes...
You should be aware of whether the external cache directory is available or not. If not, you cannot do the share. And you need to put the compress task in a background thread, so, waiting the external file cached... Does it seem like a bad solution? I think so...
Below is my project code, you can have a try...
private boolean mSaved; // a flag, whether the image is saved in external storage
private MenuItem mShare;
private Intent mIntent;
private ShareActionProvider mShareActionProvider;
private File mImage; // the external image file would be saved...
private Target target = new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
FileOutputStream os = null;
try {
String dir = CatnutUtils.mkdir(getActivity(), Constants.FANTASY_DIR); // check the exteral dir avaiable or not...
String[] paths = Uri.parse(mUrl).getPath().split("/");
mImage = new File(dir + File.separator + paths[2] + Constants.JPG); // resoleve the file name
} catch (Exception e) { // the external storage not available...
Log.e(TAG, "create dir error!", e);
return;
}
try {
if (mImage.length() > 10) { // > 0 means the file exists
// the file exists, done.
mIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mImage));
mSaved = true;
return;
}
os = new FileOutputStream(mImage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
mIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mImage));
mSaved = true;
} catch (FileNotFoundException e) {
Log.e(TAG, "io error!", e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
Log.e(TAG, "io closing error!", e);
}
}
}
}
}).start();
mFantasy.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
mFantasy.setImageDrawable(errorDrawable);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {
mFantasy.setImageDrawable(placeHolderDrawable);
}
}
};
#Override
public void onPrepareOptionsMenu(Menu menu) {
mShare.setEnabled(mSaved);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fantasy, menu);
mShare = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider) mShare.getActionProvider();
mShare.setActionProvider(mShareActionProvider);
mShareActionProvider.setShareIntent(mIntent);
}
Finally, call Picasso.with(getActivity()).load(mUrl).into(target);
When the file is saved, the user can click the share menu do the share.
public static File getImageFile(Context context, String url)
{
final String CACHE_PATH = context.getCacheDir().getAbsolutePath() + "/picasso-cache/";
File[] files=new File(CACHE_PATH).listFiles();
for (File file:files)
{
String fname= file.getName();
if (fname.contains(".") && fname.substring(fname.lastIndexOf(".")).equals(".0"))
{
try
{
BufferedReader br=new BufferedReader(new FileReader(file));
if (br.readLine().equals(url))
{
File imgfile= new File(CACHE_PATH + fname.replace(".0", ".1"));
if (imgfile.exists())
{
return imgfile;
}
}
}
catch (FileNotFoundException|IOException e)
{
}
}
}
return null;
}
I've just found out this guide with a very good solution.
https://guides.codepath.com/android/Sharing-Content-with-Intents
The code will be like this:
// Can be triggered by a view event such as a button press
public void onShareItem(View v) {
// Get access to bitmap image from view
ImageView ivImage = (ImageView) findViewById(R.id.ivResult);
// Get access to the URI for the bitmap
Uri bmpUri = getLocalBitmapUri(ivImage);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
}
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
It basically consists in retrieving the bitmap from the imageview and saving it to a local temp file and then using it for sharing. I've tested it and it seems to work fine.

how to maintain user picture from server?

I need to show picture of user in my application and I retrieve that picture from server since my application also works in offline mode so I need to save that picture from server to my SD card , also I when i sync data from server next time If picture has changed then i need to change that picture in my SD card too how to determine if picture for particular user has changed
currently i save the image from server as follow though I use hardcoded url as of now and static user id
public class fetchImage extends Activity implements OnClickListener {
int id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
id = 1;// declaring static as of now
}
{
new BackgroundTask().execute();
File storagePath = Environment.getExternalStorageDirectory();
File imgFile = new File(storagePath, "/Pictures/" + id + ".jpg");
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
.getAbsolutePath());
}
}
class BackgroundTask extends AsyncTask<Void, Void, Void> {
ProgressDialog mDialog;
protected void onPreExecute() {
mDialog = ProgressDialog.show(fetchImage.this, "",
getString(R.string.progress_bar_loading), true);
};
#Override
protected Void doInBackground(Void... params) {
try {
savesd(id, null);
} catch (final Exception e) {
}
return null;
}
private void savesd(int id, URL uri) throws IOException {
URL url;
if (uri == null) {
url = new URL("http://i.zdnet.com/blogs/3-29-androids.jpg");
} else {
url = uri;
}
InputStream input = url.openStream();
try {
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream(new File(
storagePath, "/Pictures/" + id + ".jpg"));
try {
byte[] buffer = new byte[20000];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
input.close();
}
}
protected void onPostExecute(Void result) {
mDialog.dismiss();
};
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Also i've got one problem that when I uninstall this app from Device it should also clear these user images from sd card
I used timestamp to save the time when I last sync data and download files only after that time stamp

Categories

Resources