Programmatically Downloading and Installing APK [duplicate] - android

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.

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

Unable to create directory in Android Error

I am trying to download file from server and store it in Storage but the code gives error - Unable to create directory. Please check for error
Task - File gets downloaded from server and then it is loaded in webview in android.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
try {
webView.loadUrl("file://" + Environment.getExternalStorageDirectory() + "/sponsors/"+ "dddd.html");
}
catch (Exception e)
{
Toast.makeText(MainActivity.this, "File Doesn't Exist", Toast.LENGTH_SHORT).show();
}
try {
myDownloadLast("http://192.168.76.1:8084/MyTest/dddd.html");
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_SHORT).show();
}
}
public void myDownloadLast(String myURL) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myURL));
request.setTitle("Updating TimeTable");
request.setDescription("Please Wait");
//request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
String nameOfFile = URLUtil.guessFileName(myURL, null, MimeTypeMap.getFileExtensionFromUrl(myURL));
File myFile = new File(String.valueOf(Environment.getExternalStoragePublicDirectory("/sponsors/")));
if(!myFile.exists()){
myFile.mkdir();
}
try {
request.setDestinationInExternalPublicDir(String.valueOf(myFile), nameOfFile);
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_SHORT).show();
}
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
//Toast.makeText(getActivity(), "Download Complete", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Update Complete\nFor Best Performance\nRestart The App", Toast.LENGTH_SHORT).show();
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
Your problem can be related to a few suspects
Make sure to have permissions on the Android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also, refer to the external directory with the following :
String name = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DirectoryNameYouWant/" ;

How to Record Android Screen Video programmatically in KitKat 4.4

I know this question has been asked so many times and there are so many questions, answers and discussions available. But I don't know what to do and what not to do.
I already referred to the links below to get solution with no luck.
https://stackoverflow.com/questions/23438767/how-to-record-video-on-kitkat-4-4
https://stackoverflow.com/questions/23185125/i-cannot-screen-record-with-my-kitkat-4-4-moto-x
Android KitKat start screenrecord from App
screen recorder with kitkat
Screen Recording kitkat with button
With lots of search I didn't get any simple example to achieve this task. Since 2 days i am trying to achieve this but with no success.
So the simple question is whether it is possible to record video of our own screen in android. I just heard that it is possible from android 4.4 Kitkat and i also check some app from market.
I know to do this our device should be rooted and other things which required to do this.
But I am not getting how to develop this programmatically. If any one have any idea then please guide me how to do this. or any example or code will be great help.
I appreciate your any kind of help.
I try to develop with this simple piece of code but not getting anything
public void startRecording(View v) {
File recordfolder = Environment.getExternalStorageDirectory();
String record = "su — bit rate 8000000 --time-limit 30 "
+ recordfolder + "Record.mp4";
recordfolder.mkdir();
try {
Process screenrecording = Runtime.getRuntime().exec(record);
} catch (IOException e) {
e.printStackTrace();
}
}
so basically I don't know what i have to do with this Process screenrecording, I mean how can I start progress.
Good Question But the answer depends on what type of platform you want to use to record the screen in android.
Here are some tricks.....
1) Using this class you can record the screen fort that you required rooted device you can test this in genymotion 4.4 also.
public static class MainFragment extends Fragment {
private Context mContext;
private EditText mWidthEditText;
private EditText mHeightEditText;
private EditText mBitrateEditText;
private EditText mTimeEditText;
private Button mRecordButton;
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
mContext = getActivity();
mRecordButton = (Button) rootView.findViewById(R.id.btn_record);
mRecordButton.setOnClickListener(RecordOnClickListener);
mWidthEditText = (EditText) rootView.findViewById(R.id.et_width);
mHeightEditText = (EditText) rootView.findViewById(R.id.et_height);
mBitrateEditText = (EditText) rootView
.findViewById(R.id.et_bitrate);
mBitrateEditText.addTextChangedListener(BitrateTextWatcher);
mTimeEditText = (EditText) rootView.findViewById(R.id.et_time);
mTimeEditText.addTextChangedListener(TimeTextWatcher);
return rootView;
}
private TextWatcher BitrateTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i,
int i2, int i3) {
// Not used.
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2,
int i3) {
if (TextUtils.isEmpty(charSequence)) {
return;
}
int value = Integer.valueOf(charSequence.toString());
if (value > 50 || value == 0) {
mBitrateEditText.setError(mContext
.getString(R.string.error_bitrate_edittext));
return;
}
mTimeEditText.setError(null);
}
#Override
public void afterTextChanged(Editable editable) {
// Not used.
}
};
private TextWatcher TimeTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i,
int i2, int i3) {
// Not used.
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2,
int i3) {
if (TextUtils.isEmpty(charSequence)) {
return;
}
int value = Integer.valueOf(charSequence.toString());
if (value > 180 || value == 0) {
mTimeEditText.setError(mContext
.getString(R.string.error_time_editext));
return;
}
mTimeEditText.setError(null);
}
#Override
public void afterTextChanged(Editable editable) {
// Not used.
}
};
private View.OnClickListener RecordOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!TextUtils.isEmpty(mTimeEditText.getError())
|| !TextUtils.isEmpty(mBitrateEditText.getError())) {
Toast.makeText(mContext,
mContext.getString(R.string.toast_invalid_values),
Toast.LENGTH_LONG).show();
return;
}
boolean widthSet = !TextUtils.isEmpty(mWidthEditText.getText());
boolean heightSet = !TextUtils.isEmpty(mHeightEditText
.getText());
if ((!widthSet && heightSet) || (widthSet && !heightSet)) {
Toast.makeText(mContext,
mContext.getString(R.string.error_invalid_wxh),
Toast.LENGTH_LONG).show();
return;
}
boolean bitrateSet = !TextUtils.isEmpty(mBitrateEditText
.getText());
boolean timeSet = !TextUtils.isEmpty(mTimeEditText.getText());
StringBuilder stringBuilder = new StringBuilder(
"/system/bin/screenrecord");
if (widthSet) {
stringBuilder.append(" --size ")
.append(mWidthEditText.getText()).append("x")
.append(mHeightEditText.getText());
}
if (bitrateSet) {
stringBuilder.append(" --bit-rate ").append(
mBitrateEditText.getText());
}
if (timeSet) {
stringBuilder.append(" --time-limit ").append(
mTimeEditText.getText());
}
// TODO User definable location.
stringBuilder
.append(" ")
.append(Environment.getExternalStorageDirectory()
.toString()).append("/recording.mp4");
Log.d("TAG", "comamnd: " + stringBuilder.toString());
try {
new SuTask(stringBuilder.toString().getBytes("ASCII"))
.execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private class SuTask extends AsyncTask<Boolean, Void, Boolean> {
private final byte[] mCommand;
public SuTask(byte[] command) {
super();
this.mCommand = command;
}
#Override
protected Boolean doInBackground(Boolean... booleans) {
try {
Process sh = Runtime.getRuntime().exec("su", null, null);
OutputStream outputStream = sh.getOutputStream();
outputStream.write(mCommand);
outputStream.flush();
outputStream.close();
final NotificationManager notificationManager = (NotificationManager) mContext
.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(RUNNING_NOTIFICATION_ID,
createRunningNotification(mContext));
sh.waitFor();
return true;
} catch (InterruptedException e) {
e.printStackTrace();
Toast.makeText(mContext,
mContext.getString(R.string.error_start_recording),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(mContext,
mContext.getString(R.string.error_start_recording),
Toast.LENGTH_LONG).show();
}
return false;
}
#Override
protected void onPostExecute(Boolean bool) {
super.onPostExecute(bool);
if (bool) {
final NotificationManager notificationManager = (NotificationManager) mContext
.getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(RUNNING_NOTIFICATION_ID);
File file = new File(Environment
.getExternalStorageDirectory().toString()
+ "/recording.mp4");
notificationManager.notify(FINISHED_NOTIFICATION_ID,
createFinishedNotification(mContext, file));
}
}
private Notification createRunningNotification(Context context) {
Notification.Builder mBuilder = new Notification.Builder(
context)
.setSmallIcon(android.R.drawable.stat_notify_sdcard)
.setContentTitle(
context.getResources().getString(
R.string.app_name))
.setContentText("Recording Running")
.setTicker("Recording Running")
.setPriority(Integer.MAX_VALUE).setOngoing(true);
return mBuilder.build();
}
private Notification createFinishedNotification(Context context,
File file) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "video/mp4");
PendingIntent pendingIntent = PendingIntent.getActivity(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder mBuilder = new Notification.Builder(
context)
.setSmallIcon(android.R.drawable.stat_notify_sdcard)
.setContentTitle(
context.getResources().getString(
R.string.app_name))
.setContentText("Recording Finished")
.setTicker("Recording Finished")
.setContentIntent(pendingIntent).setOngoing(false)
.setAutoCancel(true);
return mBuilder.build();
}
}
}
2) You can capture the screen shots and make the video from it and it will work for the 3.0+ devices And for converting the images to video you can use FFMPEG or JavaCV.
-For Rooted devices(in that you can capture the keyboard screen also)
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
// we check if external storage is\ available, otherwise
// display an error message to the user using Toast Message
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/ScreenShots");
directory.mkdirs();
String filename = "screenshot_jpeg_" + i + ".png";
File yourFile = new File(directory, filename);
try {
Process sh = Runtime.getRuntime().exec("su", null, null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/ScreenShots/" + filename).getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
i++;
} catch (Exception e) {
e.printStackTrace();
}
}
-For without Rooted devices(in that you can not capture the keyboard screen)
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
// we check if external storage is\ available, otherwise
// display an error message to the user using Toast Message
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/ScreenShots");
directory.mkdirs();
String filename = "screenshot_jpeg_" + i + ".png";
File yourFile = new File(directory, filename);
try {
Process sh = Runtime.getRuntime().exec("su", null, null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/ScreenShots/" + filename).getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
i++;
} catch (Exception e) {
e.printStackTrace();
}
}

ftp file download result in black screen

I am downloading a file from ftp server. downloading code worked fine, however after download code screen doesn't show anything ,it gets black. Also download function is not returning true value, even the file is being saved in the specified directory.
public class FTPClass{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_player);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Intent intent = getIntent();
dirname = intent.getStringExtra("currentDirName");
MyFTPClient mftp = new MyFTPClient();
createPath = mftp.getAppRootPath().concat("/"+ dirname);
mftp.setCurrentDir(createPath);
System.out.println(mftp.ftpChangeDirectory(createPath));
FTPFile[] farr = mftp.ftpListAllFiles();
System.out.println(farr.length);
for(int i = 0; i<farr.length;i++){
System.out.println("SRC: "+createPath+"/"+farr[i].getName());
String src = createPath+"/"+farr[i].getName();
System.out.println("DEST: "+"/data/data/com.example.ftpplayer" + "/app_"+dirname);
String dest ="/data/data/com.example.ftpplayer" + "/app_"+dirname+"/"+farr[i].getName();
System.out.println(mftp.downloadFile(src,dest));
}
}
}
public class CallingIntent extends Activity{
System.out.println("In item click ");
Intent intent = new Intent(getApplicationContext(), FTPClass.class);
String dir = ((TextView) view).getText().toString();
intent.putExtra("currentDirName", dir);
startActivity(intent);
}
public class MyFTPClient{
public boolean downloadFile(String srcPath , String destPath){
try {
FileOutputStream fos = new FileOutputStream(destPath);
System.out.println(mftp.retrieveFile(srcPath, fos)); // retrieve file doesn't return true
fos.flush();
fos.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return false;
}
}
You need to run your code on the background thread, try using an asyncTask.

Sharing button with only facebook and twitter apps in dialog

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();
}

Categories

Resources