Folder structure in different android devices - android

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?

Related

Table layout On row item clicklistner not working in android

Hi in the below code I was implemented table layout contains table rows named as Title,File name,View/Download in the last row View/Download added a row named as Preview If user click on the preview I want to pass the path name and show into some pdf format .
Can any one help me it is giving me blank screen
java:
String operation = "getRelatedDocuments";
String module = "Documents";
final String record=opportunitywon_id;
Log.d("record",record);
final APIService service = RetroClass.getRetrofitInstance().create(APIService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<DocumentModel> call = service.GetDocumentList(operation, sessionId, module,record);
/**Log the URL called*/
Log.i("URL Called", call.request().url() + "");
call.enqueue(new Callback<DocumentModel>() {
#Override
public void onResponse(Call<DocumentModel> call, Response<DocumentModel> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
DocumentModel documentModel = response.body();
// Gson g = new Gson();
//String jsonAllDocuments = g.toJson(documentModel);
// tinyDB.putString("jsonAllDocuments", jsonAllDocuments);
String success = documentModel.getSuccess();
if (success.equals("true")) {
ClosedwonResults closedwonResults = documentModel.getResult();
panModel = closedwonResults.getPan();
id = panModel.getId();
Log.d("docid", id);
filename = panModel.getFilename();
Log.d("filename", filename);
path = panModel.getPath();
Log.d("path", path);
GSTModel gstModel=closedwonResults.getGst();
gstId = gstModel.getId();
gstFilename=gstModel.getFilename();
gstpath=gstModel.getPath();
Purchase_orderModel purchase_orderModel=closedwonResults.getPurchase_order();
purchaseId=purchase_orderModel.getId();
purchaseFilename=purchase_orderModel.getFilename();
purchasePath=purchase_orderModel.getPath();
AdharModel adharModel=closedwonResults.getAdhar();
adharId=adharModel.getId();
adharFilename=adharModel.getFilename();
adharPath=adharModel.getPath();
ChecqueModel checqueModel=closedwonResults.getChecque();
checqueId=checqueModel.getId();
checqueFilename=checqueModel.getFilename();
checquepath=checqueModel.getPath();
Doc_oneModel doc_oneModel = closedwonResults.getDoc_one();
doc_oneid = doc_oneModel.getId();
Log.d("doc_oneid", doc_oneid);
doc_onefilename = doc_oneModel.getFilename();
Log.d("doc_onefilename", doc_onefilename);
doc_onepath = doc_oneModel.getPath();
Log.d("doc_onepath", doc_onepath);
Doc_twoModel doc_twoModel = closedwonResults.getDoc_two();
doc_twoid = doc_twoModel.getId();
Log.d("doc_twoid", doc_twoid);
doc_twofilename = doc_twoModel.getFilename();
Log.d("doc_twofilename", doc_twofilename);
doc_twopath = doc_twoModel.getPath();
Log.d("doc_twopath", doc_twopath);
docModel = new DocModel(filename,adharFilename,gstFilename,purchaseFilename,checqueFilename,doc_onefilename,doc_twofilename,path,adharPath,gstpath,checquepath,purchasePath,doc_onepath,doc_twopath);
closedwonList.add(docModel);
}
// DocModel docModel1=closedwonList.get(position);
documentIDS = docModel.getFilename() + "," + docModel.getDoc_onefilename() + "," + docModel.getDoc_twofilename() + "," +
docModel.getAdharfilename() + "," + docModel.getChecquefilename() + "," + docModel.getGstfilename() + "," + docModel.getPurchasefilename();
Paths=docModel.getPath()+","+docModel.getGstpath()+","+docModel.getChecquepath()+","+
docModel.getAdharpath()+","+docModel.getPurchasepath()+","+docModel.getDoc_onepath()+","+docModel.getDoctwopath();
String[] stringArray2 = {"PAN","AADHAR","GST","PURCHASE ORDER","CHECQUE","dOC ONE","DOC TWO"};
TableRow tbrowdoc = new TableRow(getContext());
Resources resourcedoc = getContext().getResources();
tbrowdoc.setLayoutParams(getLayoutParams());
tbrowdoc.addView(getTextView(0, "Title", Color.WHITE, resourcedoc.getColor(R.color.tabs1)));
tbrowdoc.addView(getTextView(0, "File Name", Color.WHITE, resourcedoc.getColor(R.color.tabs1)));
tbrowdoc.addView(getTextView(0, "View/Download", Color.WHITE,resourcedoc.getColor(R.color.tabs1)));
documents.addView(tbrowdoc, getLayoutParams());
String[] IDSList = documentIDS.split(",");
String[] PathList=Paths.split(",");
url="http://XXXXXXX/".concat(String.valueOf(PathList));
int arrayDoc = stringArray2.length;
for (int i = 0; i < arrayDoc; i++) {
final TableRow tbrowdocdetails = new TableRow(getContext());
tbrowdocdetails.setLayoutParams(getLayoutParams());
tbrowdocdetails.addView(getTextView(i + arrayDoc, stringArray2[i], Color.BLACK, ContextCompat.getColor(getContext(), R.color.back_blue)));
tbrowdocdetails.addView(getTextView(i + arrayDoc, IDSList[i], Color.BLACK, ContextCompat.getColor(getContext(), R.color.back_blue)));
tbrowdocdetails.addView(getTextView1(i + arrayDoc, "Preview", Color.BLACK, ContextCompat.getColor(getContext(), R.color.back_blue),position));
documents.addView(tbrowdocdetails);
}
}
else{
Toast.makeText(getContext(),"Something went wrong",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<DocumentModel> call, Throwable t) {
Log.d("error", t.getMessage());
}
});
private TextView getTextView1(int id, final String title, int color, int bgColor, final int position) {
lblClick = new TextView(getContext());
lblClick.setId(id);
lblClick.setText(title.toLowerCase());
lblClick.setTextColor(color);
lblClick.setGravity(Gravity.CENTER);
lblClick.setPadding(10, 10, 10, 10);
lblClick.setBackgroundColor(bgColor);
lblClick.setTag(url);
lblClick.setLayoutParams(getLayoutParams());
lblClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String path=v.getTag().toString();
Toast.makeText(getContext(),path,Toast.LENGTH_LONG).show();
myPDfItemClick(position);
}
});
return lblClick;
}
Method:
#Override
public void myPDfItemClick(int position) {
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, 112);
if (!hasPermissions(getContext(), PERMISSIONS)) {
Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");
Toast t = Toast.makeText(getContext().getApplicationContext(), "You don't have read access !", Toast.LENGTH_LONG);
t.show();
} else {
File d = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); // -> filename = maven.pdf
String url_path = listSalesStageOpportunity.get(position).getPdf_link();
///Log.d("url_path", url_path);
String file_name = url_path.substring(url_path.lastIndexOf('/') + 1);
//Log.d("file_name", file_name);
File pdfFile = new File(d, file_name);
Log.v(TAG, "view() Method pdfFile " + pdfFile.getAbsolutePath());
if (pdfFile != null) {
Uri path = GenericFileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", pdfFile);
Log.v(TAG, "view() Method path " + url_path);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
// }
}
Log.v(TAG, "view() Method completed ");
// download(v);
}
download(position);
request(position);
}
public void request(int position) {
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, 112);
}
public void download(int position) {
Log.v(TAG, "download() Method invoked ");
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, 112);
if (!hasPermissions(getContext(), PERMISSIONS)) {
Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");
Toast t = Toast.makeText(getContext().getApplicationContext(), "You don't have write access !", Toast.LENGTH_LONG);
t.show();
} else {
Log.v(TAG, "download() Method HAVE PERMISSIONS ");
String url_path = listSalesStageOpportunity.get(position).getPdf_link();
Log.d("url_path", url_path);
String file_name = url_path.substring(url_path.lastIndexOf('/') + 1);
Log.d("file_name", file_name);
new DownloadFile().execute(url_path, file_name);
}
Log.v(TAG, "download() Method completed ");
}

Handling Multiple Downloads With Notifications Using Retrofit Library

I'm following a tutorial to download files using the Retrofit library.
My app's UI has several different buttons which download different files using the above method. The problem is when someone presses another button after pressing the first, it's queued and starts after the first finishes. I want it to start right away simultaneously.
Here's the code for the DownloadService:
public class DownloadService extends IntentService {
public DownloadService() {
super("Download Service");
}
private int totalFileSize;
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
#Override
protected void onHandleIntent(Intent intent) {
MyApp x = (MyApp)getApplicationContext();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_file_download_deep_orange_a400_18dp)
.setContentTitle("Downloading")
.setContentText("Please wait...")
.setAutoCancel(true);
notificationManager.notify(x.ID, notificationBuilder.build());
Log.i("Paras", "onHandleIntent: " + x.filename + x.url);
initDownload(x.filename,x.url,x.ID);
}
private void initDownload(String filename, String url, int id) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://dl.dropboxusercontent.com/")
.build();
RequestInterface.RetrofitInterface retrofitInterface = retrofit.create(RequestInterface.RetrofitInterface.class);
Call<ResponseBody> request = retrofitInterface.downloadFile(url);
try {
downloadFile(request.execute().body(),filename,id);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void downloadFile(ResponseBody body, String filename,int id) throws IOException {
int count;
byte data[] = new byte[1024 * 4];
long fileSize = body.contentLength();
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
OutputStream output = new FileOutputStream(outputFile);
long total = 0;
long startTime = System.currentTimeMillis();
int timeCount = 1;
while ((count = bis.read(data)) != -1) {
total += count;
totalFileSize = (int) (fileSize / (Math.pow(1, 2))) / 1000;
double current = Math.round(total / (Math.pow(1, 2))) / 1000;
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
if (currentTime > 1000 * timeCount) {
download.setCurrentFileSize((int) current);
download.setProgress(progress);
sendNotification(download,id);
timeCount++;
}
output.write(data, 0, count);
}
onDownloadComplete(filename,id);
output.flush();
output.close();
bis.close();
}
private void sendNotification(Download download, int id) {
sendIntent(download);
notificationBuilder.setProgress(100, download.getProgress(), false);
notificationBuilder.setContentText("Downloading file " + download.getCurrentFileSize() + "/" + totalFileSize + " KB");
notificationManager.notify(id, notificationBuilder.build());
}
private void sendIntent(Download download) {
Intent intent = new Intent(subject.MESSAGE_PROGRESS);
intent.putExtra("download", download);
LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
}
private void onDownloadComplete(String filename,int id) {
try {
Download download = new Download();
download.setProgress(100);
sendIntent(download);
notificationManager.cancel(id);
notificationBuilder.setProgress(0, 0, false);
notificationBuilder.setContentText("Tap to open");
notificationManager.notify(id, notificationBuilder.build());
String path1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + filename;
File file = new File(path1);
Uri uri_path = Uri.fromFile(file);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
(MimeTypeMap.getFileExtensionFromUrl(path1));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
String string = filename;
notificationBuilder
.setContentIntent(pIntent)
.setAutoCancel(true)
.setContentTitle(string + " Downloaded");
Log.i("Paras", "onDownloadComplete: " + string);
notificationManager.notify(id, notificationBuilder.build());
} catch (Exception ex) {
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
}
}
Then I read about IntentService and Service classes. Do Service classes allow simultaneous downloads? I tried something like this:
public class DownloadService extends Service {
public DownloadService() {
super();
}
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
MyApp x = (MyApp)getApplicationContext();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.drawable.ic_file_download_deep_orange_a400_18dp)
.setContentTitle("Downloading")
.setContentText("Please wait...")
.setAutoCancel(true);
notificationManager.notify(x.ID, notificationBuilder.build());
Log.i("Paras", "onHandleIntent: " + x.filename + x.url);
initDownload(x.filename,x.url,x.ID);
}
}
#Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
MyApp x = (MyApp)getApplicationContext();
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj= intent.putExtra("ID",x.ID);
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private int totalFileSize;
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
private void initDownload(String filename, String url, int id) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://dl.dropboxusercontent.com/")
.build();
RequestInterface.RetrofitInterface retrofitInterface = retrofit.create(RequestInterface.RetrofitInterface.class);
Call<ResponseBody> request = retrofitInterface.downloadFile(url);
try {
downloadFile(request.execute().body(),filename,id);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void downloadFile(ResponseBody body, String filename,int id) throws IOException {
int count;
byte data[] = new byte[1024 * 4];
long fileSize = body.contentLength();
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
OutputStream output = new FileOutputStream(outputFile);
long total = 0;
long startTime = System.currentTimeMillis();
int timeCount = 1;
while ((count = bis.read(data)) != -1) {
total += count;
totalFileSize = (int) (fileSize / (Math.pow(1, 2))) / 1000;
double current = Math.round(total / (Math.pow(1, 2))) / 1000;
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
if (currentTime > 1000 * timeCount) {
download.setCurrentFileSize((int) current);
download.setProgress(progress);
sendNotification(download,id);
timeCount++;
}
output.write(data, 0, count);
}
onDownloadComplete(filename,id);
output.flush();
output.close();
bis.close();
}
private void sendNotification(Download download, int id) {
sendIntent(download);
notificationBuilder.setProgress(100, download.getProgress(), false);
notificationBuilder.setContentText("Downloading file " + download.getCurrentFileSize() + "/" + totalFileSize + " KB");
notificationManager.notify(id, notificationBuilder.build());
}
private void sendIntent(Download download) {
Intent intent = new Intent(subject.MESSAGE_PROGRESS);
intent.putExtra("download", download);
LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
}
private void onDownloadComplete(String filename,int id) {
try {
Download download = new Download();
download.setProgress(100);
sendIntent(download);
notificationManager.cancel(id);
notificationBuilder.setProgress(0, 0, false);
notificationBuilder.setContentText("Tap to open");
notificationManager.notify(id, notificationBuilder.build());
String path1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + filename;
File file = new File(path1);
Uri uri_path = Uri.fromFile(file);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
(MimeTypeMap.getFileExtensionFromUrl(path1));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
String string = filename;
notificationBuilder
.setContentIntent(pIntent)
.setAutoCancel(true)
.setContentTitle(string + " Downloaded");
Log.i("Paras", "onDownloadComplete: " + string);
notificationManager.notify(id, notificationBuilder.build());
} catch (Exception ex) {
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
}
}
But it didn't work. Any clues what I should do? I'm ready to give more details if required.
Edit 1: DownloadService runs on a function "startDownload" which is executed by various buttons. As you can see in 2nd code, class Extends Service. There is one thread which handles all those button clicks. If you look in comments, it's suggested that I should use Service and different threads for all those clicks. Now how can I make so many threads programmatically. There are almost 40 buttons which make use of DownloadService.
Thanks to #Lxu, I have got it working. So IntentServiceis meant to do one task at a time and can't do multiple tasks simultaneously. We should use Serviceinstead. It allows multiple tasks to be performed simultaneously. We can create multiple threads inside the Service which will be executed simultaneously. My problem got solved by putting all the code of onCreate() to onStartCommand(). When a service is called for the first time, onCreate() is called and after that, it's not called anymore no matter how many times service is called. On every service call, onStartCommand() is executed which creates new thread every time. That's it.
Here's the complete code:
public class DownloadService extends Service {
public DownloadService() {
super();
}
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
int id1;
int id2;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
MyApp x = (MyApp)getApplicationContext();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_file_download_deep_orange_a400_18dp)
.setContentTitle("Downloading")
.setContentText("Please wait...")
.setAutoCancel(true);
notificationManager.notify(x.ID, notificationBuilder.build());
Log.i("Paras", "onHandleIntent: " + x.filename + x.url + " " + x.ID);
initDownload(x.filename,x.url,x.ID);
}
}
#Override
public void onCreate() {
// Get the HandlerThread's Looper and use it for our Handler
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
MyApp x = (MyApp)getApplicationContext();
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private int totalFileSize;
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
private void initDownload(String filename, String url, int id) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://dl.dropboxusercontent.com/")
.build();
RequestInterface.RetrofitInterface retrofitInterface = retrofit.create(RequestInterface.RetrofitInterface.class);
Call<ResponseBody> request = retrofitInterface.downloadFile(url);
try {
downloadFile(request.execute().body(),filename,id);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void downloadFile(ResponseBody body, String filename,int id) throws IOException {
int count;
byte data[] = new byte[1024 * 4];
long fileSize = body.contentLength();
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
OutputStream output = new FileOutputStream(outputFile);
long total = 0;
long startTime = System.currentTimeMillis();
int timeCount = 1;
while ((count = bis.read(data)) != -1) {
total += count;
totalFileSize = (int) (fileSize / (Math.pow(1, 2))) / 1000;
double current = Math.round(total / (Math.pow(1, 2))) / 1000;
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
if (currentTime > 1000 * timeCount) {
download.setCurrentFileSize((int) current);
download.setProgress(progress);
sendNotification(download,id);
timeCount++;
}
output.write(data, 0, count);
}
onDownloadComplete(filename,id);
output.flush();
output.close();
bis.close();
}
private void sendNotification(Download download, int id) {
sendIntent(download,id);
notificationBuilder.setProgress(100, download.getProgress(), false)
.setContentTitle("Downloading");
notificationBuilder.setContentText("Downloading file " + download.getCurrentFileSize() + "/" + totalFileSize + " KB");
notificationManager.notify(id, notificationBuilder.build());
}
private void sendIntent(Download download, int id) {
Intent intent = new Intent(subject.MESSAGE_PROGRESS);
intent.putExtra("download", download);
LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
}
private void onDownloadComplete(String filename,int id) {
try {
Download download = new Download();
download.setProgress(100);
sendIntent(download,id);
notificationManager.cancel(id);
notificationBuilder.setProgress(0, 0, false);
notificationBuilder.setContentText("Tap to open");
notificationManager.notify(id, notificationBuilder.build());
String path1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + filename;
File file = new File(path1);
Uri uri_path = Uri.fromFile(file);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
(MimeTypeMap.getFileExtensionFromUrl(path1));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);
PendingIntent pIntent = PendingIntent.getActivity(this,(int) System.currentTimeMillis(), intent, 0);
String string = filename;
notificationBuilder
.setContentIntent(pIntent)
.setAutoCancel(true)
.setContentTitle(string + " Downloaded");
Log.i("Paras", "onDownloadComplete: " + string);
notificationManager.notify(id, notificationBuilder.build());
}catch (Exception ex){
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
}
}

Download Manager failed the download

I am using DownloadManager to download the following url:
http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
But the downloading is failed. I even hit the url on browser and it works properly. Is it the problem of url parsing?
Code: DDownloadService.java
public class DDownloadService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
Context conte;
// NotificationManager notificationManager;
// NotificationCompat.Builder mBuilder;
boolean playing = false;
Runnable runnable;
SharedPreferences pre;
static int countOfCurrent = 0;
String downloadName, downloadUrl;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
// ..
static int downloadNumber = 0;
DownloadManager mgr[] = new DownloadManager[100];
long downloadIds[] = new long[100];
BroadcastReceiver cancelDownload;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
downloadNumber++;
downloadName = pre.getString("downloadname", "");
downloadName = viewSD(downloadName);
downloadUrl = pre.getString("downloadurl", "");
downloadName = downloadName.toLowerCase();
pre.edit()
.putString(
"songsInDownload",
pre.getString("songsInDownload", "") + "|"
+ downloadName).commit();
pre.edit().putInt(downloadName + "no", +downloadNumber).commit();
mgr[downloadNumber] = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
try {
countOfCurrent++;
downloadIds[downloadNumber] = mgr[downloadNumber]
.enqueue(new DownloadManager.Request(Uri
.parse(downloadUrl))
.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("Downloading")
.setDescription(downloadName)
.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_HIDDEN)
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_MUSIC,
downloadName)
.setVisibleInDownloadsUi(false));
pre.edit()
.putLong(downloadName + "id",
downloadIds[downloadNumber]).commit();
Timer myTimer = new Timer();
myTimer.schedule(new RegrowCornAnimate(downloadNumber,
downloadName), 0, 10);
} catch (IllegalStateException e) {
Toast.makeText(getBaseContext(), "No storage found!",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(getBaseContext(), " Something wrong happened!",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
#Override
public void onCreate() {
conte = this;
pre = getSharedPreferences("download", 0);
downloadName = pre.getString("downloadname", "");
downloadUrl = pre.getString("downloadurl", "");
cancelDownload = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
try {
mgr[pre.getInt(arg1.getExtras().getString("name") + "no", 0)]
.remove(pre.getLong(
arg1.getExtras().getString("name") + "id",
0));
} catch (Exception e) {
e.printStackTrace();
}
}
};
registerReceiver(cancelDownload, new IntentFilter("cancelIt"));
notificationManager = (NotificationManager) conte
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Downloading in progress").setContentText("");
startForeground(55, mBuilder.build());
notificationManager.cancel(55);
HandlerThread thread = new HandlerThread("ServiceStartArguments", 0);
// //..................
// notificationManager = (NotificationManager) conte
// .getSystemService(Context.NOTIFICATION_SERVICE);
// mBuilder = new NotificationCompat.Builder(conte);
// RemoteViews remoteViews = new RemoteViews(getPackageName(),
// R.layout.notification_layout);
// try {
// mBuilder.setSmallIcon(R.drawable.icon);
// mBuilder.setAutoCancel(false).setOngoing(true)
// .setContent(remoteViews);
// Uri uri = RingtoneManager
// .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// mBuilder.setSound(uri);
// notificationManager.notify(Mp3Constants.NOTIFICATION_NUMBER,
// mBuilder.build());
// } catch (Exception e) {
// e.printStackTrace();
// }
// //...................
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// online = intent.getExtras().getString("online");
// link = intent.getExtras().getString("link");
// name = intent.getExtras().getString("name");
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(cancelDownload);
}
class RegrowCornAnimate extends TimerTask {
private final int serial;
private final String name_of_da;
boolean startFlag = true, errorFlag = true;
RegrowCornAnimate(int serial, String name) {
this.serial = serial;
this.name_of_da = name;
}
public void run() {
// Do stuff
int dl_progress = 0;
try {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadIds[serial]);
Cursor c = mgr[serial].query(q);
c.moveToFirst();
long bytes_downloaded = c
.getInt(c
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
long bytes_total = c
.getInt(c
.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
dl_progress = (int) ((bytes_downloaded * 100) / bytes_total);
pre.edit().putInt(name_of_da, dl_progress).commit();
switch (c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
case DownloadManager.STATUS_FAILED:
// msg = "Download failed!";
// Toast.makeText(getBaseContext(), "Url Broken!",
// Toast.LENGTH_SHORT).show();
sendNotification(1, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
case DownloadManager.STATUS_PAUSED:
// msg = "Download paused!";
if (errorFlag) {
errorFlag = false;
sendNotification(7, serial, name_of_da, dl_progress);
}
break;
case DownloadManager.STATUS_PENDING:
// msg = "Download pending!";
sendNotification(0, serial, name_of_da, dl_progress);
break;
case DownloadManager.STATUS_RUNNING:
// msg = "Download in progress!";
errorFlag = true;
if (startFlag) {
if (verifyFromSD(name_of_da)) {
startFlag = false;
sendBroadcast(new Intent("start"));
}
}
sendNotification(0, serial, name_of_da, dl_progress);
break;
case DownloadManager.STATUS_SUCCESSFUL:
// msg = "Download complete!";
pre.edit()
.putString(
"songsInDownload",
pre.getString("songsInDownload", "")
.replace("|" + name_of_da, ""))
.commit();
pre.edit().putInt(name_of_da, 100);
sendNotification(0, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
default:
// msg = "Download is nowhere in sight";
sendNotification(10, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
}
c.close();
} catch (Exception e) {
e.printStackTrace();
sendNotification(7, serial, name_of_da, dl_progress);
cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
}
}
}
public void sendNotification(int tmout, int nin, String name, int progress) {
if (tmout == 0) {
// notificationManager.notify(nin, mBuilder.build());
if (progress >= 100) {
// notificationManager.cancel(nin);
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Completed").setContentText(name)
.setAutoCancel(true).setOngoing(false)
.setProgress(100, 100, false);
Uri ttt = Uri.parse(Environment.getExternalStorageDirectory()
.toString() + "/Music/" + name);
pre.edit().putInt("retry", 1).commit();
Intent inten = new Intent(Intent.ACTION_VIEW, ttt);
String arr[] = name.split("\\.");
inten.setDataAndType(ttt, "audio/" + arr[arr.length - 1]);
PendingIntent i = PendingIntent.getActivity(getBaseContext(),
0, inten, 0);
mBuilder.setContentIntent(i);
notificationManager.notify(nin, mBuilder.build());
} else {
mBuilder.setContentTitle("Downloading: " + name)
.setContentText(progress + " %")
.setSmallIcon(R.drawable.icon).setAutoCancel(false)
.setOngoing(true);
mBuilder.setProgress(100, progress, false);
notificationManager.notify(nin, mBuilder.build());
}
} else {
if (tmout == 1) {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Failed: " + name)
.setContentText(progress + " %").setAutoCancel(true)
.setProgress(100, progress, false).setOngoing(false);
// Intent intnt = new Intent(Mp3Constants.NOTIFICATION);
// intnt.putExtra("resume", "1");
// intnt.putExtra("url", urlD);
// intnt.putExtra("name", name);
// intnt.putExtra("nin", nin);
// PendingIntent i = PendingIntent
// .getBroadcast(conte, 0, intnt, 0);
// mBuilder.setContentIntent(i);
} else if (tmout == 7) {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Cancelled: " + name)
.setAutoCancel(true).setProgress(100, progress, false)
.setOngoing(false);
// Intent intnt = new Intent(Mp3Constants.NOTIFICATION);
// intnt.putExtra("resume", "1");
// intnt.putExtra("url", urlD);
// intnt.putExtra("name", name);
// intnt.putExtra("nin", nin);
// PendingIntent i = PendingIntent
// .getBroadcast(conte, 0, intnt, 0);
// mBuilder.setContentIntent(i);
} else {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Interrupted: " + name)
.setContentText("No storage found").setAutoCancel(true)
.setOngoing(false);
}
notificationManager.notify(nin, mBuilder.build());
}
}
private String viewSD(String naame) {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return naame;
}
while (true) {
String newName = naame;
naame = relooper(files, newName);
if (newName.equals(naame))
break;
}
return naame;
}
public String relooper(File[] files, String name) {
int send = files.length;
for (int i = 0; i < send; i++) {
File file = files[i];
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
if (name.equalsIgnoreCase(myfile))
return "copy_of_" + name;
}
return name;
}
private boolean verifyFromSD(String naame) {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return false;
}
int send = files.length;
for (int i = 0; i < send; i++) {
File file = files[i];
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
if (naame.equalsIgnoreCase(myfile))
return true;
}
return false;
}
}
EDIT: I found the problem from logcat:
01-07 11:47:37.313: W/DownloadManager(18893): Exception for id 285: Illegal character in path at index 115: http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
01-07 11:47:37.313: W/DownloadManager(18893): java.lang.IllegalArgumentException: Illegal character in path at index 115: http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
01-07 11:47:37.313: W/DownloadManager(18893): at java.net.URI.create(URI.java:727)
01-07 11:47:37.313: W/DownloadManager(18893): at android.net.Proxy.getProxy(Proxy.java:113)
01-07 11:47:37.313: W/DownloadManager(18893): at android.net.Proxy.getPreferredHttpHost(Proxy.java:218)
01-07 11:47:37.313: W/DownloadManager(18893): at com.android.providers.downloads.DownloadThread.run(DownloadThread.java:174)
But I still need to know which format to use to parse url for DownloadManager.
The IllegalArgumentException occurs when the URL contains illegal characters such as [ ]. As mentioned in the comments, you need to encode such characters using URLEncoder.
I implemented it this way in my code -
private String checkUrl(String url) {
if(url.contains("[")) {
String[] a = url.split("\\[");
String b = "[" + a[1]; //contains text after [ e.g. [DJKANG.Com].mp3
url = a[0] + URLEncoder.encode(b, "UTF-8"); // encodes illegal characters
}
return url;
}

downloading files from server using IntentService in android

I am trying to download files using IntentService.My downloading queue is interrupted.
I am using the following code to start a service
Intent intent = new Intent(ViewShowList.this, DownloadService.class);
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
intent.putExtra("url", url);
intent.putExtra("share_id", showID);
intent.putExtra("showname", name);
intent.putExtra("showdatecreated", dateCreated);
intent.putExtra("noofFiles", noofFiles);
startService(intent);
Handler for communication back
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
public void handleMessage(Message message) {
Log.d(TAG, "handleMessage.....................");
//Object path = message.obj;
if (message.arg1 == DownloadService.COMPLETED) {
Toast.makeText(mContext, getResources().getString(R.string.Text_MadeOffline), Toast.LENGTH_SHORT).show();
createOfflineShowsList();
syncShowAssets();
if (showListadapter != null) {
showListadapter.notifyDataSetChanged();
}
} else {
Log.e(TAG, "Download Failed...");
}
}
};
DownloadService.java
This is service class which extend IntentService
public class DownloadService
extends IntentService {
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<HashMap<String, String>> showAssetList;
private SharedPreferences sotcPref;
PendingIntent contentIntent;
int i = 1;
String url;
String showname;
String showdatecreated;
String showId;
Messenger messenger;
int noofFiles;
public DownloadService() {
super("DownloadService");
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 5 " + "DownloadService()constructor");
}
if (Constants.DEBUG) {
Log.d(TAG, "DownloadService... Constructor");
}
OFFSET = 0;
LIMIT = 3;
}
#SuppressWarnings("deprecation")
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 6 " + "onHandleIntent");
}
connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
sotcPref = getApplicationContext().getSharedPreferences("SOTCPref", MODE_PRIVATE);
if (Constants.DEBUG) {
Log.d(TAG, "onHandleIntent.........");
}
Bundle extras = intent.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");
}
if (Constants.DEBUG) {
System.out.println(data);
}
} else {
data = showdatecreated;
if (Constants.DEBUG) {
System.out.println("date in else");
}
if (Constants.DEBUG) {
System.out.println(showdatecreated);
}
if (Constants.DEBUG) {
System.out.println(data);
}
}
showId = extras.getString("share_id");
noofFiles = extras.getInt("noofFiles");
messenger = (Messenger) extras.get("MESSENGER");
Intent notificationIntent = new Intent();
contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
notification = new Notification(R.drawable.sotc_notification_icon, "", System.currentTimeMillis());
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
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);
if (Constants.DEBUG) {
Log.i("FOO", "Notification started");
}
if (showname.length() > 18) {
showname = showname.substring(0, 17);
}
if (DownloadAssets.TOTAL_ASSET_COUNT == 0) {
downloadSetofAssets(OFFSET, LIMIT, url);
if (DownloadAssets.TOTAL_ASSET_COUNT > LIMIT) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 8 " + "if(DownloadAssets.TOTAL_ASSET_COUNT > LIMIT)");
}
for (OFFSET = LIMIT; OFFSET < DownloadAssets.TOTAL_ASSET_COUNT; ) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 8.1 " + "if(DownloadAssets.TOTAL_ASSET_COUNT > LIMIT)");
}
downloadSetofAssets(OFFSET, LIMIT, url);
OFFSET = OFFSET + LIMIT;
}
}
}
if (i > 1) {
result = DownloadService.COMPLETED;
notification.setLatestEventInfo(DownloadService.this, "Downloaded Successfully", "", contentIntent);
Message msg = Message.obtain();
msg.arg1 = result;
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
} else {
result = DownloadService.FAILED;
notification.setLatestEventInfo(DownloadService.this, "Downloaded Failed", "", contentIntent);
if (Constants.DEBUG) {
Log.e(TAG, "Download Failed...");
}
}
notification.contentView.setImageViewResource(R.id.image, R.drawable.icon);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
}
private void downloadSetofAssets(int OFFSET, int LIMIT, String url) {
// TODO Auto-generated method stub
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 7 " + "downloadSetofAssets");
}
try {
url = url.replace("value1", URLEncoder.encode("" + OFFSET, "UTF-8"));
url = url.replace("value2", URLEncoder.encode("" + LIMIT, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Constants.DEBUG) {
Log.i(TAG, "Show offline -- Asset URL: " + url);
}
showAssetList = DownloadAssets.hit(getApplicationContext(), url);
for (HashMap<String, String> asset : showAssetList) {
String thumbUrl = asset.get("thumb_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);
}
boolean isDownloaded = false;
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());
}
isDownloaded = 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());
}
isDownloaded = doInBackground(this, normalUrl, normalFile.getAbsolutePath(), messenger);
}
} 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());
}
isDownloaded = 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());
}
isDownloaded = doInBackground(this, mp4Url, mp4File.getAbsolutePath(), messenger);
} 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());
}
isDownloaded = 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());
}
isDownloaded = doInBackground(this, normalUrl, normalFile.getAbsolutePath(), messenger);
}
} 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());
}
isDownloaded = 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());
}
isDownloaded = doInBackground(this, normalUrl, normalFile.getAbsolutePath(), messenger);
} else { //"5" Link
if (Constants.DEBUG) {
Log.d(TAG, "This is Web Link");
}
isDownloaded = true;
}
}
}
}
}
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;
}
#SuppressWarnings({"deprecation", "deprecation"})
boolean doInBackground(Context context, String urlPath, String destinationPath, Messenger messenger) {
boolean isDownloaded = false;
int lastPercent = 0;
File destination = new File(destinationPath);
if (!destination.exists()) {
if (chkConnectionStatus()) {
InputStream stream = null;
FileOutputStream fos = null;
try {
URL imageUrl = new URL(urlPath);
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();
isDownloaded = false;
Toast.makeText(getApplicationContext(), getResources().getString(R.string.Text_NoFile), 1000).show();
} else if (contentLength > availablestorageOnExternalDir()) {
//No Space Available
result = DownloadService.LOW_SPACE;
destination.delete();
isDownloaded = false;
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) {
notification.contentView.setProgressBar(R.id.progressBar1, 100, percent, false);
lastPercent = percent;
}
}
if (destination.length() < contentLength) {
result = DownloadService.PARTIALLY_DOWNLOADED;
destination.delete();
isDownloaded = false;
} else {
if (Constants.DEBUG) {
Log.e(TAG, "Sucessful downloaded-------------------------------------------------" + i++);
}
// Sucessful finished
//i++;
result = Activity.RESULT_OK;
isDownloaded = true;
}
} catch (Exception ex) {
}
}
conn.disconnect();
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messenger.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(context, "Please check your network connection", "", contentIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
isDownloaded = true;
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messenger.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 {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
isDownloaded = true;
}
return isDownloaded;
}
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;
}
}
}
DownloadAssets.java
//To download
//files into
//created folders
public class DownloadAssets {
private static final String TAG = "DownloadAssets";
public static int TOTAL_ASSET_COUNT;
static synchronized ArrayList<HashMap<String, String>> hit(Context context, String url) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 9 " + "hit url" + url);
}
ArrayList<HashMap<String, String>> mList = new ArrayList<HashMap<String, String>>();
String message = null;
String result = null;
try {
result = Constants.queryRESTurl(url);
if (result != null) {
if (result.equals("timeout")) {
message = context.getResources().getString(R.string.Text_TimeOut);
} else {
JSONObject json = Constants.convertStringtoJsonObject(result);
try {
JSONObject results = json.getJSONObject(ThumbnailFragment.JSON_RESPONSE_ATTR_RESULTSET);
String totalAssetCount = results.getString(ThumbnailFragment.JSON_RESPONSE_ATTR_ASSET_COUNT);
TOTAL_ASSET_COUNT = Integer.parseInt(totalAssetCount);
if (Constants.DEBUG) {
Log.i("5" + TAG, "totalAssetCount : " + totalAssetCount);
}
if (TOTAL_ASSET_COUNT != 0) {
JSONArray assetData = results.getJSONArray(ThumbnailFragment.JSON_RESPONSE_ATTR_ASSET_ARRAY);
if (Constants.DEBUG) {
Log.i(TAG, "6Madhu " + assetData.toString());
}
int nObjects = assetData.length();
if (Constants.DEBUG) {
Log.i(TAG, "7Madhu " + nObjects);
}
if (nObjects != 0) {
for (int i = 0; i < nObjects; i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = assetData.getJSONObject(i);
map.put("id", "" + e.getString("assets_id"));
map.put("asset_name", "" + e.getString("asset_name"));
map.put("thumb_url", "" + e.getString("thumb_url"));
map.put("asset_type", "" + e.getString("asset_type"));
map.put("large_url", "" + e.getString("large_url"));
map.put("mp4_url", "" + e.getString("mp4_url"));
map.put("normal_url", "" + e.getString("normal_url"));
map.put("description", "" + e.getString("description"));
map.put("filetype", "" + e.getString("filetype"));
map.put("filename", "" + e.getString("original_filename"));
map.put("filesize", "" + e.getString("filesize"));
mList.add(map);
if (Constants.DEBUG) {
Log.i(TAG, "Size in Loop " + mList.size());
}
}
} else if (Constants.DEBUG) {
Log.i(TAG, "EXECUTING ELSE nObjects");
}
} else if (Constants.DEBUG) {
Log.i(TAG, "EXECUTING ELSE count");
}
} catch (JSONException e) {
if (Constants.DEBUG) {
Log.e("8log_tag", "Error parsing data " + e.toString());
}
message = context.getResources().getString(R.string.Text_InvalidResponse);
} catch (Exception e) {
if (Constants.DEBUG) {
Log.e("8log_tag", "Error parsing data " + e.toString());
}
message = context.getResources().getString(R.string.Text_InvalidResponse);
e.printStackTrace();
}
}
} else {
if (Constants.DEBUG) {
Log.i(TAG, "EXECUTING ELSE result");
}
message = context.getResources().getString(R.string.Text_InvalidResponse);
}
} catch (Exception e) {
// TODO Auto-generated catch block
message = context.getResources().getString(R.string.Text_ServerProblem);
e.printStackTrace();
}
if (Constants.DEBUG) {
Log.e(TAG, "Message : " + message);
}
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 9 End " + "hit return " + mList);
}
return mList;
}
}
My queries are
Files are downloading but not all files at first time from server.If I download more folders for example Folder1,Folder2 then Folder3, Folder1 and Folder2 interrupted(i.e 1 file is downloaded) but Folder3 downloaded fully...
How can I keep the queue of files/folders to be downloaded? !
For speed up and maintaining the queue of intent follow the below approach
protected void onHandleIntent(Intent intent) {
synchronized (intent) {
final Intent intentCpy=intent;
new Thread(new Runnable() {
#Override
public void run() {
//onHandleIntent code which is in question post
}
}
}
Use ConcurrentHashMap for Thread-Safty in following method
private synchronized void downloadSetofAssets(int OFFSET , int LIMIT , String url)
for more details about ConcurrentHashMap please visit
http://www.cs.umd.edu/class/spring2013/cmsc433/Notes/14-CMSC433-ConcurrentCollections.pdf

Android DeadObjectException

I have developed my mobile Application based on GSM SMS Communication through the Service Implementation in Android called SmsService.java which use a Receiver as an inner class. In SmsService we use android service that run all time during application runtime. I use it through the use BinderProxy via the use of aidl (Interface Language) it works fine but after some time it will show the Exception Message.I tag the message as well as code for SmsService.java class. Sir please help me how to resolve. thanks in advance and sorry for bad English if not understand..
The Exception log is..
04-24 12:53:04.230: E/SMSReceiver(980): Failed to notify listener aidl.com.services.MessageListener$Stub$Proxy#40528870
04-24 12:53:04.230: E/SMSReceiver(980): android.os.DeadObjectException
04-24 12:53:04.230: E/SMSReceiver(980): at android.os.BinderProxy.transact(Native Method)
04-24 12:53:04.230: E/SMSReceiver(980): at aidl.com.services.MessageListener$Stub$Proxy.handleNewMessage(MessageListener.java:76)
04-24 12:53:04.230: E/SMSReceiver(980): at com.services.SmsService$SMSReceiver.onReceive(SmsService.java:227)
04-24 12:53:04.230: E/SMSReceiver(980): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:709)
04-24 12:53:04.230: E/SMSReceiver(980): at android.os.Handler.handleCallback(Handler.java:587)
04-24 12:53:04.230: E/SMSReceiver(980): at android.os.Handler.dispatchMessage(Handler.java:92)
04-24 12:53:04.230: E/SMSReceiver(980): at android.os.Looper.loop(Looper.java:130)
04-24 12:53:04.230: E/SMSReceiver(980): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-24 12:53:04.230: E/SMSReceiver(980): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 12:53:04.230: E/SMSReceiver(980): at java.lang.reflect.Method.invoke(Method.java:507)
04-24 12:53:04.230: E/SMSReceiver(980): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-24 12:53:04.230: E/SMSReceiver(980): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-24 12:53:04.230: E/SMSReceiver(980): at dalvik.system.NativeStart.main(Native Method)
finally the code for the SmsService.java
public class SmsService extends Service {
private SMSReceiver mSMSreceiver;
private IntentFilter mIntentFilter;
private DataBaseAdapter dba;
private String Tag = SmsService.class.getSimpleName();
public final Object latestSearchResultLock = new Object();
public List<MessageListener> listeners = new ArrayList<MessageListener>();
private static BufferedWriter out;
private static int id = 0;
private static int msgId= 0;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
if(SmsService.class.getName().equals(arg0.getAction())){
Log.d(Tag, "Binding Complete" + arg0);
return apiEndpoint;
}else
return null;
}
public SmsService(){
/*dba = new DataBaseAdapter(this);*/
/*dba = DataBaseAdapter.getInstance(this);*/
mSMSreceiver = new SMSReceiver(this);
Log.i("On Constructor", "Assign Service");
}
private final Object findLatest = new Object();
private MessageQueue<newItem> msgQueue = new MessageQueue<newItem>();
public SmsService getService(){
return SmsService.this;
}
private MessageReceiverApi.Stub apiEndpoint = new MessageReceiverApi.Stub(){
#Override
public void addListener(MessageListener listener) throws RemoteException {
// TODO Auto-generated method stub
synchronized(listeners){
listeners.add(listener);
}
}
#Override
public void removeListener(MessageListener listener) throws RemoteException {
// TODO Auto-generated method stub
synchronized (listeners) {
listeners.remove(listener);
}
}
#Override
public MessageQueue<newItem> getMessageQueueUpdated()
throws RemoteException {
// TODO Auto-generated method stub
synchronized(findLatest){
return msgQueue;
}
}
};
#Override
public void onCreate(){
super.onCreate();
Log.i(Tag, "Service is creating");
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(ConstantClass.SMS_RECEIVED);
registerReceiver(mSMSreceiver,mIntentFilter);
Log.i(Tag, "Service is creating Successfully");
}
#Override
public int onStartCommand(Intent intent , int flags, int type){
return START_STICKY;
}
#Override
public void onDestroy(){
super.onDestroy();
unregisterReceiver(mSMSreceiver);
/*if(dba!=null)
DataBaseAdapter.getInstance(this).closeConnection();*/
}
public class SMSReceiver extends BroadcastReceiver {
/*private DataBaseAdapter dba;*/
private Context context;
#SuppressWarnings("unused")
private String Strsql;
private SMSSync sync;
private UtilityFunction utility;
private boolean isCrdMatch;
private String address,Phnumber, msg=null/*,panId =null*/,curMsg=null,mtemp=null;
private String devid,incAddr;
#SuppressWarnings("unused")
private Handler handle;
private MessageQueue<newItem> list;
private newItem item;
private String Tag = SMSReceiver.class.getSimpleName();
public SMSReceiver(Context ctx){
this.context = ctx;
list=new MessageQueue <newItem>();
}
#Override
public void onReceive(Context context,final Intent intents){
/*dba = new DataBaseAdapter(context); */
dba = DataBaseAdapter.getInstance(this.context);
utility = new UtilityFunction(context);
sync = new SMSSync(context);
if (intents.getAction().equals(ConstantClass.SMS_RECEIVED)) {
try{
Bundle bundle = intents.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
for (SmsMessage message : messages) {
msg = message.getMessageBody();
incAddr = message.getOriginatingAddress();
}
/*Thread.sleep(50);*/
mtemp = getMessage(msg);
if(mtemp!=null){
item = new newItem(mtemp);
list.enqueue(item);
while(!list.isEmpty()){
curMsg = list.peek().getItem();
if(curMsg.startsWith("<") && curMsg.endsWith(">")){
msgId = 0;
char mid = curMsg.charAt(3);
msgId = (int )mid;
Log.i(Tag, "message id:="+ msgId);
//dba.SetSynchronization();
if(msgId==50 || msgId == 54 || msgId == 56 || msgId==65 || msgId == 67 || msgId == 69 || msgId == 75 || msgId == 76){
utility.displayNotification(this.context,curMsg);
}else{
devid = curMsg.substring(4, 20);
/*if(!dba.IsConOpenOrClose())
dba.openRead();*/
Cursor cur = dba.getRecordAcToID(DeviceStorage.TABLE_DEVICE, new String[]{DeviceStorage.Key_AlarmTime },
DeviceStorage.Key_DevID , devid);
if(cur.getCount()>0){
cur.moveToFirst();
int almTime = Integer.valueOf(cur.getString(0));
if(almTime==0)
utility.displayNotification(this.context,curMsg);
}
}
/*if(!dba.IsConOpenOrClose())
dba.Open();*/
int count = dba.getDeviceCount(DeviceCurrent.TABLE_CURRENT);
if(count<=0){
dba.InsertCurrentCoord(id,id);
}else{
dba.updateCommon(DeviceCurrent.TABLE_CURRENT, DeviceCurrent.Key_ReceiverCoord, DeviceCurrent.Key_ID , Integer.toString(id), Integer.toString(1));
dba.updateCommon(CoordStore.TABLE_COORD, CoordStore.Key_IsReceiverUpdate, CoordStore.Key_MBID, Integer.toString(1), Integer.toString(id));
Log.i(Tag, "Updateing Coordinator for Receiver");
}
/*sid = dba.CurrentWorkingCoordinator(DeviceCurrent.Key_SendCoord, 1);*/
Log.i(Tag, "Updateing DataBase Only for Record");
ConstantClass.IsReadLog=false;
sync.smsProcess(curMsg);
/*if(msgId==50 && sid == id){
panId = curMsg.substring(22, 26);
authority = utility.getAuthority();
if(authority.equals("A") && panId.equals("3000")){
ConstantClass.Clear_Main_Screen=false;
ConstantClass.isMainOpen = false;
Intent intent = new Intent(this.context,SettingScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
context.startActivity(intent);
}
} */
utility.getLicense();
Log.i(Tag, "ConstantClass Log " + String.valueOf(ConstantClass.LOGS));
if(ConstantClass.LOGS){
WriteOnLog(curMsg,1);
}
abortBroadcast();
/************Now deleting the SMS from the Inbox*********************/
removeMessage(this.context, Phnumber);
list.dequeue();
synchronized(listeners){
for (MessageListener listener : listeners) {
try {
/*listener.notify();*/
listener.handleNewMessage();
/*listener.asBinder();*/
} catch (RemoteException e){
Log.e(Tag, "Failed to notify listener " , e);
}
}
}
}
}
}
}
}catch(Exception e){
Toast.makeText(this.context, "On SMS Receiver" + e.getMessage(), Toast.LENGTH_LONG).show();
WriteOnLog(curMsg,0);
} /*catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/finally{
/*if(dba.IsConOpenOrClose())
dba.close();
dba=null;*/
utility = null;
sync=null;
}
}
if(ConstantClass.Clear_Main_Screen==true && ConstantClass.isMainOpen == true){
Intent intent = new Intent(context,ZigbeeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
private void removeMessage(Context context, String fromAddress) {
Uri uriSMS = Uri.parse("content://sms/inbox");
Cursor cursor = null;
/*if(!dba.IsConOpenOrClose())
dba.Open();*/
try{
cursor = context.getContentResolver().query(uriSMS, null, null, null, null);
cursor.moveToFirst();
if(cursor.getCount() > 0){
int ThreadId = cursor.getInt(1);
context.getContentResolver().delete(Uri.parse("content://sms/conversations/"+ThreadId), "address=?",new String[]{fromAddress});
Log.d("Message Thread Deleted", fromAddress);
}
}catch(Exception e){
Log.e("remove Message", e.getMessage());
}finally{
if(cursor!=null)
cursor.close();
/*if(dba.IsConOpenOrClose())
dba.close();*/
}
}
private String getMessage(String msg){
String newMsg = null;
try{
int tl = incAddr.length();
int l = tl - ConstantClass.NO;
address = incAddr.substring(l,tl);
isCrdMatch = MatchCoord(address);
if(isCrdMatch == true) {
if(msg.startsWith("<") && msg.contains(">")){
int len = Integer.valueOf(msg.substring(1, 3), 16).intValue();
int index = msg.indexOf(">");
Log.i(Tag, "Value is:" + len);
Log.i(Tag, "index value is:" + index);
if(len==index+1){
newMsg = msg.substring(0, len); //getting the length of the whole message and except the Garbage /
Log.i(Tag, "receiving msg length is:=" + len);
Log.i(Tag, "receiving msg is:=" + newMsg);
return newMsg;
}else{
Toast.makeText(this.context, "message Corrupt" + address, Toast.LENGTH_LONG).show();
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return newMsg;
}
private boolean MatchCoord(String no){
boolean isMatched = false;
String crdNo = null;
Cursor cursor = null;
try{
cursor = dba.SelectCommon(CoordStore.TABLE_COORD, new String[]{CoordStore.Key_MBID,CoordStore.Key_MbNo},
CoordStore.Key_MbNo , new String[]{no});
if(cursor.getCount()>0)
cursor.moveToFirst();
do{
crdNo = cursor.getString(cursor.getColumnIndex(CoordStore.Key_MbNo));
if(crdNo.equals(no)){
id = cursor.getInt(cursor.getColumnIndex(CoordStore.Key_MBID));
Phnumber = crdNo;
Log.i(Tag, "Crd No is:" + Phnumber);
isMatched = true;
break;
}
}while(cursor.moveToNext());
}catch(Exception e){
Log.e(Tag, e.getMessage());
}finally{
if(cursor!=null)
cursor.close();
}
return isMatched;
}
private void WriteOnLog(String msg,int crpt){
File exportDir = new File("/sdcard/CIH");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
String fileName;
fileName = "log" + ".txt";
File file = new File(exportDir,fileName);
String txt=null ;
try {
if(!file.exists()){
file.createNewFile();
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
txt = "Date Time |" + " Send/Receive |" + " Controller No |" + " Success |" +" Message " + " | Corrupt";
out.write( txt + "\r\n" );
out.flush();
out.close();
}
/*FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);*/
//txt = "Date Time |" + " Send/Receive |" + " Controller No |" +" Message " ;
String header = "Date Time |" + " Send/Receive |" + " Controller No |" + " Success |" +" Message " + "| Corrupt \r\n" ;
String dd=null,mm=null,yy=null,hh=null,min=null,ss=null,dt=null;
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
yy = newtime.substring(2, 4);
mm = newtime.substring(5, 7);
dd = newtime.substring(8, 10);
hh = newtime.substring(11, 13);
min = newtime.substring(14, 16);
ss = newtime.substring(17);
dt = dd+"-"+mm+"-"+yy +" " + hh + ":" + min +":"+ ss;
if(crpt == 0)
txt = dt + " | " +" Receive " + "| " + address + " | " + " Successfull |" + msg.toUpperCase() +" | " + " Yes \r\n" ;
else
txt = dt + " | " +" Receive " + "| " + address + " | " + " Successfull |" + msg.toUpperCase() + "| No \r\n";
prepend(file.getAbsolutePath(),txt,header);
/*out.write( txt + "\n");
out.flush();*/
}
catch(IOException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
}
public void prepend(String filename,String data,String Header) throws IOException{
BufferedReader in = new BufferedReader(new FileReader(filename));
StringBuilder reply = new StringBuilder();
String str = new String();
reply.append(Header);
//////////now appending the data that current sms /////////
reply.append(data);
int i = 0;
while( (str = in.readLine())!=null ){
if(i!=0)
reply.append(str + "\r\n");
i++;
}
str = reply.toString();
BufferedWriter out= new BufferedWriter(new FileWriter(filename));
out.write(str);
if(in !=null){
try{
in.close();
} catch(IOException e){
e.printStackTrace();
}
if(out!=null)
try{
out.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
}
}

Categories

Resources