In my project there is an option to download a set of files.To check the storage availability I used the below code
public static int getSDCardStatus() {
String extState = Environment.getExternalStorageState();
int status;
if (extState.equals(Environment.MEDIA_MOUNTED)) {
status = MOUNTED;
} else if (extState.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
status = READ_ONLY;
} else {
status = UNMOUNTED;
}
return status;
}
private String getLoginFolders() {
// TODO Auto-generated method stub
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
File f = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/.nomedia");
f.mkdirs();
file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/" + sotcPref.getString("domain", "") + "/"
+ sotcPref.getString("user_id", ""));
file.mkdirs();
}
return file.getAbsolutePath();
}
While making download in LG Nexus 4 and Samsung Nexus 4 working fine. But in Micromax a114 canvas 2.2 and Nexus 5 not working fine.
For reference the service class which I am using for download
public class DownloadService extends IntentService {
#Override
public void onDestroy() {
super.onDestroy();
if (Constants.DEBUG)
Log.i("StatusDownloadservice", "Ondestroy");
}
private int OFFSET;
private int LIMIT;
String data;
private final String TAG = "DownloadService";
private int result = Activity.RESULT_CANCELED;
public static int COMPLETED = 100;
public static int FAILED = 101;
public static int LOW_SPACE = 102;
public static int NETWORK_PROBLEM = 103;
public static int ASSERT_EXISIT = 104;
public static int PARTIALLY_DOWNLOADED = 105;
public static int NO_FILE = 105;
private NotificationManager notificationManager;
private Notification notification;
ConnectivityManager connMgr;
ArrayList<ConcurrentHashMap<String, String>> showAssetList;
RemoteViews contentView;
private SharedPreferences sotcPref;
PendingIntent contentIntent;
int downloadCount = 1;
String url;
String showname;
String showdatecreated;
String showId;
Messenger messenger;
int noofFiles;
Thread handleIntentThread = null;
Thread downloadJoinThread = null;
public Handler notifyHandler = new Handler();
int assetCount = 0;
// To track the app event
MixpanelAPI mMixpanel;
private SharedPreferences myPrefs;
// private boolean isServiceRunning=false;
public DownloadService() {
super("com.iw.sotc.show.offline.DownloadService");
if (Constants.DEBUG)
Log.d(TAG, "Offline step 5 " + "DownloadService()constructor");
if (Constants.DEBUG)
Log.d(TAG, "DownloadService... Constructor");
OFFSET = 0;
LIMIT = 3;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_REDELIVER_INTENT;
}
#Override
protected void onHandleIntent(Intent intent) {
if (Constants.DEBUG)
Log.i("StatusDownloadservice", "OnhandleIntent");
// Initialize the Mixpanel library for tracking and push notifications.
mMixpanel = MixpanelAPI.getInstance(this, Constants.MIXPANEL_API_TOKEN);
myPrefs = getApplicationContext().getSharedPreferences("SOTCPref",
MODE_PRIVATE);
final Intent intentCpy = intent;
// synchronized (intentCpy) {
/*
* new Thread(new Runnable() {
*
* #Override public void run() {
*/
if (Constants.DEBUG)
Log.d(TAG, "Offline step 6 " + "onHandleIntent");
connMgr = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
sotcPref = getApplicationContext().getSharedPreferences("SOTCPref",
MODE_PRIVATE);
if (Constants.DEBUG)
Log.d(TAG, "onHandleIntent.........");
Bundle extras = intentCpy.getExtras();
url = extras.getString("url");
showname = extras.getString("showname");
showdatecreated = extras.getString("showdatecreated");
// sara
if (showdatecreated.contains("/")) {
data = showdatecreated.replaceAll("/", "#");
if (Constants.DEBUG) {
System.out.println("date");
System.out.println(data);
}
} else {
data = showdatecreated;
if (Constants.DEBUG) {
System.out.println("date in else");
System.out.println(showdatecreated);
System.out.println(data);
}
}
showId = extras.getString("share_id");
noofFiles = extras.getInt("noofFiles");
messenger = (Messenger) extras.get("MESSENGER");
/*
* Intent notificationIntent = new Intent(); contentIntent =
* PendingIntent.getService( getApplicationContext(), 1,
* notificationIntent, 0);
*/
// contentIntent =
// PendingIntent.getActivity(getApplicationContext(), 0,
// notificationIntent, 0);
showNotification();
if (Constants.DEBUG)
Log.i("FOO", "Notification started");
if (showname.length() > 18)
showname = showname.substring(0, 17);
if (DownloadAssets.TOTAL_ASSET_COUNT == 0) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 7 "
+ "if(DownloadAssets.TOTAL_ASSET_COUNT == 0)");
Log.i("Downloadassetvalue", ""
+ DownloadAssets.TOTAL_ASSET_COUNT);
}
// TODO Auto-generated method stub
downloadSetofAssets(OFFSET, LIMIT, url);
assetCount = DownloadAssets.TOTAL_ASSET_COUNT;
if (Constants.DEBUG)
Log.d(TAG, "Offline step 7 asset count :" + assetCount);
DownloadAssets.TOTAL_ASSET_COUNT = 0;
}
if (assetCount > LIMIT) {
if (Constants.DEBUG)
Log.d(TAG, "Offline step 7.1 "
+ "if(DownloadAssets.TOTAL_ASSET_COUNT > LIMIT)");
for (OFFSET = LIMIT; OFFSET < assetCount;) {
if (Constants.DEBUG)
Log.d(TAG,
"Offline step 8.1 "
+ "for(OFFSET = LIMIT; OFFSET < DownloadAssets.TOTAL_ASSET_COUNT;)");
downloadSetofAssets(OFFSET, LIMIT, url);
OFFSET = OFFSET + LIMIT;
}
DownloadAssets.TOTAL_ASSET_COUNT = 0;
}
if (Constants.DEBUG)
Log.d(TAG, "download check :downloadJoinThread is running");
if (Constants.DEBUG)
Log.i("DownloadingStatus", "InService");
if (downloadCount >= 1) {
result = DownloadService.COMPLETED;
// to notify the changes made after the offline
// coded by Karthikeyan V
showNotificationDownloadComplete("download successful.");
Message msg = Message.obtain();
try {
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "Sendmessenger");
msg.arg1 = result;
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(), "Exception sending message", e1);
}
} else {
result = DownloadService.FAILED;
Message msg = Message.obtain();
msg.arg1 = result;
try {
messenger.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// stopForeground(true);
/*
* notification.setLatestEventInfo(DownloadService.this,
* "Download Failed", "", contentIntent);
*/
showNotificationDownloadComplete("download failed.");
}
/*
* }
*
* }).start();
*/
/*
* //to notify the changes made after the offline
* ViewShowList.showListadapter.notifyDataSetChanged();
*/
// }
}
private void showNotificationDownloadComplete(String statusDownload) {
notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.sotc_notification_icon, "",
System.currentTimeMillis());
contentView = new RemoteViews(getPackageName(),
R.layout.upload_progress_aftercomplete);
notification.flags |= Notification.FLAG_NO_CLEAR;
contentView
.setImageViewResource(R.id.imageOfflineshowCompletion, R.drawable.icon);
contentView.setTextViewText(R.id.textView1offlineshowCompletion, showname+"\t"+statusDownload);
//For click event
Intent intentOpenOfflineshows = new Intent(this,
com.iw.sotc.show.offline.ViewOfflineShows.class);
contentIntent = PendingIntent.getActivity(this, 2,
intentOpenOfflineshows, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_SHOW_LIGHTS;
notification.contentIntent = contentIntent;
notification.contentView = contentView;
notificationManager.notify(1, notification);
}
private void showNotification() {
notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.sotc_notification_icon, "",
System.currentTimeMillis());
contentView = new RemoteViews(getPackageName(),
R.layout.upload_progress_bar);
notification.flags |= Notification.FLAG_NO_CLEAR;
contentView
.setImageViewResource(R.id.imageOfflineshow, R.drawable.icon);
contentView.setTextViewText(R.id.textView1, showname);
contentView.setProgressBar(R.id.progressBar1, 100, 0, false);
notification.contentIntent = contentIntent;
notification.contentView = contentView;
notificationManager.notify(1, notification);
/*
* notificationManager = (NotificationManager) this
* .getSystemService(Context.NOTIFICATION_SERVICE); notification = new
* Notification( R.drawable.sotc_notification_icon, "", System
* .currentTimeMillis()); notification.flags = notification.flags |
* Notification.FLAG_ONGOING_EVENT; notification.flags|=
* Notification.FLAG_NO_CLEAR; notification.contentView = new
* RemoteViews( getApplicationContext().getPackageName(),
* R.layout.upload_progress_bar); notification.icon =
* R.drawable.sotc_notification_icon;
* notification.contentView.setTextViewText(R.id.textView1, showname);
* notification.contentIntent = contentIntent;
* notification.contentView.setProgressBar(R.id.progressBar1, 100, 0,
* false); notificationManager.notify(1, notification);
* startForeground(1, notification);
*/
}
private void downloadSetofAssets(int OFFSET, int LIMIT, String url) {
if (Constants.DEBUG)
Log.d(TAG, "Offline step 8 " + "downloadSetofAssets");
if (Constants.DEBUG)
try {
url = url.replace("value1",
URLEncoder.encode("" + OFFSET, "UTF-8"));
url = url.replace("value2",
URLEncoder.encode("" + LIMIT, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (Constants.DEBUG)
Log.i(TAG, "Show offline -- Asset URL: " + url);
showAssetList = DownloadAssets.hit(getApplicationContext(), url);
for (ConcurrentHashMap<String, String> asset : showAssetList) {
String thumbUrl = asset.get("thumb_url");
// String normalUrl = asset.get("normal_url");
// added by Karthikeyan v
// To avoid downloading png file for document type files
// here just used the variable name as normalUrl for testing purpose
// // do not confuse
String largeUrl = asset.get("large_url");
String normalUrl = asset.get("normal_url");
String mp4Url = asset.get("mp4_url");
String fileType = asset.get("filetype");
String assetID = asset.get("id");
String assetType = asset.get("asset_type");
if (Constants.DEBUG)
Log.d(TAG, "Thumb Url :" + thumbUrl);
if (Constants.DEBUG)
Log.d(TAG, "Normal Url :" + normalUrl);
if (Constants.DEBUG)
Log.d(TAG, "Asset ID : " + assetID);
if (Constants.DEBUG)
Log.d(TAG, "Asset Type : " + assetType);
if (Constants.DEBUG)
Log.d(TAG, "MP4 Url : " + mp4Url);
if (Constants.DEBUG)
Log.d(TAG, "FileType : " + fileType);
if (assetType.equals("1")) { // Image
File assetDirectory = createAssetDirectory(showId, showname,
data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(),
"/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(),
"/Normal." + getExtention(normalUrl));
if (Constants.DEBUG)
Log.i("NormalFilepath", normalFile.getAbsolutePath());
if (Constants.DEBUG)
Log.d(TAG,
"Normal File path: "
+ normalFile.getAbsolutePath());
doInBackground(this, normalUrl,
normalFile.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
}
} else if (assetType.equals("2")) { // Video
File assetDirectory = createAssetDirectory(showId, showname,
data, assetID, assetType);
if (assetDirectory != null) {
if (!fileType.equals("Youtube")) { // via AddLink
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File mp4url = new File(
assetDirectory.getAbsolutePath(), "/Normal");
mp4url.mkdirs();
// mp4_Url
File mp4File = new File(mp4url.getAbsolutePath(),
"/Normal." + getExtention(mp4Url));
if (Constants.DEBUG)
Log.d(TAG,
"Normal File path: "
+ mp4File.getAbsolutePath());
doInBackground(this, mp4Url,
mp4File.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
} else if (Constants.DEBUG)
Log.d(TAG,
"Asset type is video but is Youtube link. So not proceeding for offline");
}
} else if (assetType.equals("3")) { // Audio
File assetDirectory = createAssetDirectory(showId, showname,
data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(),
"/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(),
"/Normal." + getExtention(normalUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Normal File path: "
+ normalFile.getAbsolutePath());
doInBackground(this, normalUrl,
normalFile.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
}
} else {
if (!assetType.equals("5")) {
File assetDirectory = createAssetDirectory(showId,
showname, data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File normal = new File(
assetDirectory.getAbsolutePath(), "/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(),
"/Normal." + getExtention(largeUrl));
if (Constants.DEBUG)
Log.i("Normal File path: ",
normalFile.getAbsolutePath());
doInBackground(this, largeUrl,
normalFile.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
} else // "5" Link
{
if (Constants.DEBUG)
Log.d(TAG, "This is Web Link");
}
}
}
}
}
private String getLoginFolders() {
// TODO Auto-generated method stub
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
File f = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/.nomedia");
f.mkdirs();
file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/" + sotcPref.getString("domain", "") + "/"
+ sotcPref.getString("user_id", ""));
file.mkdirs();
}
return file.getAbsolutePath();
}
private File createAssetDirectory(String showid, String showname,
String data, String assetID, String assetType) {
// TODO Auto-generated method stub
if (Constants.DEBUG)
Log.d(TAG, "Offline step 10 " + "createAssetDirectory");
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
if (DownloadAssets.TOTAL_ASSET_COUNT != 0) {
/**
* From to concept here is to avoid duplication of new offline
* shows when show is updated. So, we are here renaming previous
* offline show's folder name with updated asset count.
*/
boolean isRenameSuccess = false;
File f = new File(getLoginFolders());
if (!f.exists())
f.mkdirs();
File[] fileArray = f.listFiles();
File f2 = new File(getLoginFolders(), "/" + showid.trim() + ","
+ showname.trim() + "," + data);
for (File from : fileArray) {
String s1 = from.getName().substring(0,
from.getName().lastIndexOf(","));
if (Constants.DEBUG)
Log.i(TAG, "s1: " + s1);
if (f2.getName().equalsIgnoreCase(s1)) {
// Rename
File to = new File(getLoginFolders(), "/"
+ showid.trim() + "," + showname.trim() + ","
+ data + "," + noofFiles);
if (Constants.DEBUG)
Log.i(TAG, "from existence: " + from.exists());
try {
isRenameSuccess = from.renameTo(to);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Constants.DEBUG)
Log.i(TAG, "isRenameSuccess: " + isRenameSuccess);
break;
}
}
file = new File(getLoginFolders(), "/" + showid.trim() + ","
+ showname.trim() + "," + data + "," + noofFiles
+ "/File_" + assetID + "," + assetType.trim());
}
if (file != null)
if (!file.exists())
file.mkdirs();
}
return file;
}
public static String getExtention(String url) {
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return extension;
}
boolean doInBackground(Context context, String urlPath,
String destinationPath, Messenger messenger) {
final String desti = destinationPath;
final String url = urlPath;
final Messenger messengerCopy = messenger;
final Context cntxt = context;
/*
* new Thread(new Runnable() {
*
* #Override public void run() {
*/
if (Constants.DEBUG)
Log.d(TAG, "Offline step 9 " + "doInBackground");
// boolean isDownloaded = false;
int lastPercent = 0;
File destination = new File(desti);
if (Constants.DEBUG)
Log.i("DestinationFile", destination.getAbsolutePath());
if (!destination.exists()) {
if (chkConnectionStatus()) {
InputStream stream = null;
FileOutputStream fos = null;
try {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
stream = conn.getInputStream();
int contentLength = conn.getContentLength();
if (Constants.DEBUG)
Log.i(TAG, "contentLength : " + contentLength);
if (contentLength == 0) {
result = DownloadService.NO_FILE;
destination.delete();
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.Text_NoFile),
1000).show();
} else if (contentLength > availablestorageOnExternalDir()) {
// No Space Available
result = DownloadService.LOW_SPACE;
destination.delete();
Toast.makeText(
getApplicationContext(),
getResources().getString(
R.string.Text_NoSpaceShow), 1000)
.show();
} else {
fos = new FileOutputStream(destination.getPath());
long total = 0l;
final int buffer_size = 4 * 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = stream.read(bytes, 0, buffer_size);
if (count == -1)
break;
fos.write(bytes, 0, count);
total += count;
int percent = (int) ((total * 100) / contentLength);
if (percent > lastPercent) {
if (Constants.DEBUG)
Log.i("Percent", "" + percent);
contentView.setProgressBar(
R.id.progressBar1, 100, percent,
false);
notification.contentView = contentView;
lastPercent = percent;
if (Constants.DEBUG)
Log.i("DownloadingPercent", ""
+ percent);
}
}
if (destination.length() < contentLength) {
result = DownloadService.PARTIALLY_DOWNLOADED;
destination.delete();
} else {
if (Constants.DEBUG)
Log.e(TAG,
"Sucessful downloaded-------------------------------------------------"
+ downloadCount++);
// Sucessful finished
if (Constants.DEBUG)
Log.e(TAG,
"Sucessful downloaded-------------------------------------------------"
+ downloadCount);
result = Activity.RESULT_OK;
}
} catch (Exception ex) {
}
// To track the offline event
JSONObject properties = new JSONObject();
try {
properties.put("User Name",
myPrefs.getString("email_id", null));
properties.put("MAIL",
myPrefs.getString("email_id", null));
} catch (JSONException e) {
}
mMixpanel.identify(myPrefs.getString("email_id", null));
mMixpanel.getPeople().set(properties);
mMixpanel.track("mA_Show Offline End", properties);
}
conn.disconnect();
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messengerCopy.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(),
"Exception sending message", e1);
}
if (Constants.DEBUG)
Log.v(TAG, "Completed.............. ");
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
// / no network connection
result = DownloadService.NETWORK_PROBLEM;
notification.setLatestEventInfo(cntxt,
"Please check your network connection", "",
contentIntent);
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messengerCopy.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(),
"Exception sending message", e1);
}
}
} else {
result = DownloadService.ASSERT_EXISIT;
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messengerCopy.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
/*
* }
*
* }).start();
*/
return true;
}
public long availablestorageOnExternalDir() // Get Available space(in Bytes)
{
StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
long bytesAvailable = (long) stat.getBlockSize()
* (long) stat.getAvailableBlocks();
long megAvailable = bytesAvailable / (1024 * 1024);
if (Constants.DEBUG)
Log.e("", "Available MB : " + megAvailable);
if (Constants.DEBUG)
Log.e("", "Available Bytes : " + bytesAvailable);
return bytesAvailable;
}
public boolean chkConnectionStatus() {
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
if (wifi.isConnected())
return true;
return false;
} else if (mobile.isAvailable()) {
if (mobile.isConnected())
return true;
return false;
} else
return false;
}
}
My queries :
1.Is anything need to check additionally?
2.Is the folder structure is different in many android devices?
3.If the android devices having different folder structure or storage options(internal or external) how can I look forward?
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.
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);
}
}