Android DeadObjectException - android

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

Related

Folder structure in different android devices

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?

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

NullPointerException on getting data from database

I've made working source codes on synchronizing database before but suddenly it's not working now. Here, I'm trying to read my records in local database in the DB_User class. But it returned java.lang.NullPointerException. So this is what I made.
This is the stacktrace of my error
01-15 06:42:20.080: I/ActivityManager(60): Displayed activity com.yolanda.ta/.DBSynchronizer: 387 ms (total 387 ms)
01-15 06:42:40.639: D/dalvikvm(1147): GC_FOR_MALLOC freed 2008 objects / 125592 bytes in 74ms
01-15 06:43:21.149: D/dalvikvm(1147): GC_FOR_MALLOC freed 777 objects / 219464 bytes in 79ms
01-15 06:44:02.018: D/dalvikvm(1147): GC_FOR_MALLOC freed 830 objects / 404856 bytes in 67ms
01-15 06:44:35.578: D/dalvikvm(1147): GC_FOR_MALLOC freed 830 objects / 404976 bytes in 78ms
01-15 06:44:58.399: W/dalvikvm(1147): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-15 06:44:58.411: E/AndroidRuntime(1147): FATAL EXCEPTION: Thread-8
01-15 06:44:58.411: E/AndroidRuntime(1147): java.lang.NullPointerException
01-15 06:44:58.411: E/AndroidRuntime(1147): at com.yolanda.ta.ThreadUser.fetchLocal(ThreadUser.java:192)
01-15 06:44:58.411: E/AndroidRuntime(1147): at com.yolanda.ta.ThreadUser.run(ThreadUser.java:59)
01-15 06:44:58.492: W/ActivityManager(60): Force finishing activity com.yolanda.ta/.DBSynchronizer
and this is fetchLocal() to get data from database which I call it to get data from the local database
public String[] fetchLocal (int column)
{
Cursor user = mDbHelper.getAllRow3();
String Result[] = new String[user.getCount()];
user.moveToFirst();
int i = 0;
while (user.isAfterLast() == false) {
Result[i++] = user.getString(column);
user.moveToNext();
}
user.close();
return Result;
}
and this is the method of getAllRow3()
public Cursor getAllRow3()
{
Cursor c = db.query(NAMA_TABEL, new String[]{ROW_ID, ROW_NAMAL, ROW_NAMA, ROW_PW, ROW_ALAMAT, ROW_TELEPON, ROW_LEVEL, ROW_STATUS,ROW_TIME}, null, null, null, null, null, null);
return c;
}
and this is my table structure
public class DB_User {
private static final String ROW_ID = "IDUser";
private static final String ROW_NAMAL = "NamaLogin";
private static final String ROW_NAMA ="NamaUser";
private static final String ROW_PW ="PasswordUser";
private static final String ROW_ALAMAT ="AlamatUser";
private static final String ROW_TELEPON ="TeleponUser";
private static final String ROW_LEVEL ="LevelUser";
private static final String ROW_STATUS ="StatusUser";
private static final String ROW_TIME ="Waktu";
private static final String NAMA_DB = "TA";
private static final String NAMA_TABEL = "User";
private static final int DB_VERSION = 1;
private static int batas = 5;
private static final String CREATE_TABLE = "create table if not exists "+ NAMA_TABEL +" ("+ ROW_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
ROW_NAMAL +" VARCHAR not null, "+ ROW_NAMA +" VARCHAR not null, " + ROW_PW + " VARCHAR not null, " + ROW_ALAMAT + " VARCHAR not null, "
+ ROW_TELEPON + " VARCHAR, "+ ROW_LEVEL+ " VARCHAR not null, " + ROW_STATUS + " INTEGER not null, "+ROW_TIME+" LONG not null)";
I don't have any idea since the other activity can get exactly the same data using the same query while my thread can't. Any suggestion is welcome.
EDIT:
line 192: Cursor user = mDbHelper.getAllRow3();
line 59: String[] LocalRowID = fetchLocal(0);
Here is my ThreadUser codes:
public class ThreadUser extends Thread implements Runnable {
private boolean RunSync = false;
private DB_User mDbHelper;
private long sleeptime;
public void setDatabase(DB_User mDbHelper)
{
this.mDbHelper = mDbHelper;
}
public void setRun(boolean set)
{
RunSync = set;
}
public void setDelay(long delay)
{
sleeptime = delay;
}
#Override
public void run()
{
while(RunSync)
{
String[] RemoteID = fetch("http://10.0.2.2/project/User.php?ct=Sel_IDUser");
String[] RemoteNamaL = fetch("http://10.0.2.2/project/User.php?ct=Sel_NamaLogin");
String[] RemoteNama = fetch("http://10.0.2.2/project/User.php?ct=Sel_NamaUser");
String[] RemotePassword = fetch("http://10.0.2.2/project/User.php?ct=Sel_PasswordUser");
String[] RemoteAlamat = fetch("http://10.0.2.2/project/User.php?ct=Sel_AlamatUser");
String[] RemoteTelepon = fetch("http://10.0.2.2/project/User.php?ct=Sel_TeleponUser");
String[] RemoteLevel = fetch("http://10.0.2.2/project/User.php?ct=Sel_LevelUser");
String[] RemoteStatus = fetch("http://10.0.2.2/project/User.php?ct=Sel_StatusUser");
String[] RemoteTime = fetch("http://10.0.2.2/project/User.php?ct=Sel_Waktu");
//ROW_ID, ROW_NAMAL, ROW_NAMA, ROW_PW, ROW_ALAMAT, ROW_TELEPON, ROW_LEVEL, ROW_STATUS,ROW_TIME
String[] LocalRowID = fetchLocal(0);
String[] LocalNamaL = fetchLocal(1);
String[] LocalNama = fetchLocal(2);
String[] LocalPassword = fetchLocal(3);
String[] LocalAlamat = fetchLocal(4);
String[] LocalTelepon = fetchLocal(5);
String[] LocalLevel = fetchLocal(6);
String[] LocalStatus = fetchLocal(7);
String[] LocalTime = fetchLocal(8);
Calendar cal = Calendar.getInstance();;
for(int i = 1; i < RemoteID.length; i++)
{ Log.e("index remote1", Integer.toString(i));
for(int j = 0; j < LocalRowID.length; j++)
{
Log.e("indexlocal1", Integer.toString(j));
if(RemoteID[i].equalsIgnoreCase(LocalRowID[j]))
{
if(Long.parseLong(RemoteTime[i]) > Long.parseLong(LocalTime[j]))
{
// //id, namal, nama, alamat, password, telepon, level, status, time
mDbHelper.updateBaris2(Integer.parseInt(LocalRowID[j]), RemoteNamaL[i],
RemoteNama[i], RemoteAlamat[i],RemotePassword[i],
RemoteTelepon[i], RemoteLevel[i], Integer.parseInt(RemoteStatus[i]), cal.getTimeInMillis());
break;
}
else if (Long.parseLong(RemoteTime[i]) < Long.parseLong(LocalTime[j]))
{
call("http://10.0.2.2/project/User.php?ct=EDT&namal="+LongData(LocalNamaL[j].toString())+
"&nama="+LongData(LocalNama[j].toString())+"&pw="+LongData(LocalPassword[j].toString())+"&alamat="+LongData(LocalAlamat[j].toString())+
"&telepon="+LongData(LocalTelepon[j].toString())+"&level="+LongData(LocalLevel[j].toString())+"&status="+LocalStatus[j]+"&time="
+cal.getTimeInMillis()+"&id="+LocalRowID[j].toString());
break;
}
}
}
if (LocalRowID.length + 1 > RemoteID.length)
{//namal, nama, alamat, password, telepon, level, status, time
try{
call("http://10.0.2.2/project/User.php?ct=INS&namal="+LongData(LocalNamaL[LocalRowID.length-1].toString())+
"&nama="+LongData(LocalNama[LocalRowID.length-1].toString())+"&pw="+LongData(LocalPassword[LocalRowID.length-1].toString())+"&alamat="+LongData(LocalAlamat[LocalRowID.length-1].toString())+
"&telepon="+LongData(LocalTelepon[LocalRowID.length-1].toString())+"&level="+LongData(LocalLevel[LocalRowID.length-1].toString())+"&status="+LocalStatus[LocalRowID.length-1]+"&time="
+cal.getTimeInMillis());
Log.e("nambah server","voila");
break;
}
catch (Exception e){Log.e("walah",e.toString());}
}
else
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
for(int i = 0; i < LocalRowID.length-1; i++)
{ Log.e("index local2", Integer.toString(i));
if(RemoteID.length <= 1)
{
try{
call("http://10.0.2.2/project/User.php?ct=INS&namal="+LongData(LocalNamaL[i].toString())+
"&nama="+LongData(LocalNama[i].toString())+"&pw="+LongData(LocalPassword[i].toString())+"&alamat="+LongData(LocalAlamat[i].toString())+
"&telepon="+LongData(LocalTelepon[i].toString())+"&level="+LongData(LocalLevel[i].toString())+"&status="+LocalStatus[i]+"&time="
+cal.getTimeInMillis()+"&id="+LocalRowID[i].toString());
}
catch(Exception e){
Log.e("wooooy", e.toString());
}
}
for(int j = 1; j < RemoteID.length; j++)
{
Log.e("indexremote2", Integer.toString(j));
if(LocalRowID[i].equalsIgnoreCase(RemoteID[j]))
{
break;
}
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
if (RemoteID.length-1 > LocalRowID.length)
{
i-=1;
try{
mDbHelper.addRow2(RemoteNamaL[RemoteID.length-1], RemoteNama[RemoteID.length-1], RemoteAlamat[RemoteID.length-1], RemotePassword[RemoteID.length-1],
RemoteTelepon[RemoteID.length-1], RemoteLevel[RemoteID.length-1], Integer.parseInt(RemoteStatus[RemoteID.length-1]), cal.getTimeInMillis());
break;
}
catch(Exception e){
Log.e("wuuuy", e.toString());
}
}
if (LocalRowID.length == RemoteID.length)
{
break;
}
}
try {
sleep(sleeptime);
} catch (InterruptedException e) {
break;
}
}
}
public String LongData (String Data)
{
String LongData ="";
for (int i = 0; i < Data.length(); i++)
{
if (Data.charAt(i)==' ')
{
LongData += '~';
}
else
LongData += Data.charAt(i);
}
return LongData;
}
public String[] fetchLocal (int column)
{
Cursor user = mDbHelper.getAllRow3();
String Result[] = new String[user.getCount()];
user.moveToFirst();
int i = 0;
while (user.isAfterLast() == false) {
Result[i++] = user.getString(column);
user.moveToNext();
}
user.close();
return Result;
}
public String[] fetch(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpRequestBase httpRequest = null;
HttpResponse httpResponse = null;
InputStream inputStream = null;
String response = "";
StringBuffer buffer = new StringBuffer();
httpRequest = new HttpGet(url);
try
{
httpResponse = httpclient.execute(httpRequest);
}
catch (ClientProtocolException el)
{
el.printStackTrace();
}
catch (IOException el)
{
el.printStackTrace();
}
try
{
inputStream = httpResponse.getEntity().getContent();
}
catch (IllegalStateException el)
{
el.printStackTrace();
}
catch (IOException el)
{
el.printStackTrace();
}
byte[] data = new byte[512];
int len = 0;
try
{
while(-1 != (len = inputStream.read(data)))
{
buffer.append(new String(data,0,len));
}
}
catch (IOException el)
{
el.printStackTrace();
}
try
{
inputStream.close();
}
catch (IOException el)
{
el.printStackTrace();
}
response = buffer.toString();
StringParser parser = new StringParser();
ArrayList<Object> output = parser.Parse(response);
Object[] Output = output.toArray();
String[] content = new String[Output.length];
for (int i = 0; i < content.length; i++)
{
content[i] = Output[i].toString();
}
return content;
}
public String call(String url)
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try
{
in = OpenHttpConnection(url);
}
catch (IOException el) {
el.printStackTrace();
return "Error: " + el.getMessage();
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try
{
while((charRead = isr.read(inputBuffer)) > 0)
{
String readString = String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
return "Error 02";
}
return str;
}
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if(!(conn instanceof HttpURLConnection)) throw new IOException("Not an Http Connection");
try
{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if(response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception e)
{
throw new IOException("Error Connecting");
}
return in;
}
}`
First of all, your code don't have code line number, so we don't know which line is "ThreadUser.java:192" and "ThreadUser.java:59".
Actually this problem may be a synchronized problem, please provide more code detail about TheadUser.java code. If so please add synchronized to method or synchronized block to solve this issue.

error in android junit test as service not available to activity on create

java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.Activity.getSystemService(Activity.java:3536)
at android.accounts.AccountManager.get(AccountManager.java:261)
at com.android.deviceintelligence.activity.DeviceIntelligence.emailAccounts(DeviceIntelligence.java:466)
at com.android.deviceintelligence.test.Testnew.testEmailAccounts(Testnew.java:32)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)
this is error I am getting when I run my test application.
public class Testnew extends ActivityInstrumentationTestCase2<DeviceIntelligence>{
public Testnew() {
super("com.android.deviceintelligence.activity", DeviceIntelligence.class);
}
Context mContext;
private DeviceIntelligence mdevint;
protected void setUp() throws Exception {
super.setUp();
mdevint = new DeviceIntelligence();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testEmailAccounts() {
mdevint.emailAccounts();
Assert.assertNotNull(mdevint);
}
}
this is my test application code. emailaccounts() is a method in my activity class and its defined out side the class. I need to check method is working properly or not for all possible inputs.
public void emailAccounts() {
Log.d(TAG, "inside emailaccount");
Account[] accounts = AccountManager.get(this).getAccounts();
int size = ead.selectAll().size();
List<String> dbAcc = ead.select();
Log.d(TAG, "dbAcc: " + dbAcc.toString());
Log.d(TAG, "size: " + dbAcc.size() + " " + "length: " + accounts.length);
if (accounts.length != 0) {
if (size == 0) {
for (Account eAccounts : accounts) {
ead.insert(eAccounts.name, eAccounts.type);
}
} else {
for (Account acc : accounts) {
if (!dbAcc.contains(acc.name + acc.type)) {
ead.insert(acc.name, acc.type);
;
}
}
}
}
this is my emailaccounts() method.please help me solving in.thanks for the help in advance.
package com.android.deviceintelligence.activity;
import com.android.deviceintelligence.R;
import com.android.deviceintelligence.db.EmailAccountsData;
import com.android.deviceintelligence.db.MemoryData;
import com.android.deviceintelligence.db.ServerUpload;
import com.android.deviceintelligence.db.StaticData;
import com.android.deviceintelligence.service.MainService;
import com.android.deviceintelligence.service.Registration;
public class DeviceIntelligence extends Activity implements OnClickListener{
public static final String TAG = "Device Intelligence";
private final String PROC_FILE = "/proc/cpuinfo";
private final String CPU_FREQ_MAX_INFO = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";
private final String CPU_FREQ_MIN_INFO = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq";
InputStream is = null;
public static StaticData sd;
String uid = null;
Camera camera;
public static MemoryData md;
String deviceId, androidId;
ServerUpload su;
public static String uId = "";
public static EmailAccountsData ead;
private Button stop_btn ;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "ACTIVITY ONCREATE");
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
/* UI PART */
stop_btn = (Button) findViewById(R.id.btn_stop);
Button app_start = (Button) findViewById(R.id.btn_app_show);
Button browse_show = (Button) findViewById(R.id.btn_browse_show);
Button stat_view = (Button) findViewById(R.id.btn_stat);
Button settings = (Button) findViewById(R.id.settings);
stop_btn.setOnClickListener(this);
app_start.setOnClickListener(this);
browse_show.setOnClickListener(this);
stat_view.setOnClickListener(this);
settings.setOnClickListener(this);
md = new MemoryData(this);
ead = new EmailAccountsData(this);
sd = new StaticData(this);
Log.d(TAG,
"\n========================================Begin===============================================\n");
TelephonyManager teleman = (TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
deviceId = teleman.getDeviceId();
if (deviceInfo() != null) {
uId = deviceInfo();
} else {
uId = "Not found";
}
String[] process_info = ProcessorInfo();
String[] screen_info = screenInfo();
String[] cpu_info_freq = cpu_freq();
try {
/*
* int cam = Camera.getNumberOfCameras(); Log.d(TAG, "cam count: " +
* cam); camera = Camera.open(); Log.d(TAG, "camera****** " +
* camera);
*
* camera = Camera.open(); Log.d(TAG, "camera****** " + camera);
* Camera.Parameters cameraParameters = camera.getParameters();
* Log.d("appcheck", "cameraParameters: " + cameraParameters);
*/
List<String> hardware = new ArrayList<String>();
hardware.add(uId);
Log.d(TAG, "0: " + hardware.get(0));
if (Build.MODEL != null) {
hardware.add(Build.MODEL);
} else {
hardware.add("Not found");
}
Log.d(TAG, "1: " + hardware.get(1));
if (Build.MANUFACTURER != null) {
hardware.add(Build.MANUFACTURER);
} else {
hardware.add("Not found");
}
Log.d(TAG, "2: " + hardware.get(2));
if (Build.BRAND != null) {
hardware.add(Build.BRAND);
} else {
hardware.add("Not found");
}
Log.d(TAG, "3: " + hardware.get(3));
if (Build.ID != null) {
hardware.add(Build.ID);
} else {
hardware.add("Not found");
}
Log.d(TAG, "4: " + hardware.get(4));
if (Build.BOARD != null) {
hardware.add(Build.BOARD);
} else {
hardware.add("Not found");
}
Log.d(TAG, "5: " + hardware.get(5));
if (Build.DEVICE != null) {
hardware.add(Build.DEVICE);
} else {
hardware.add("Not found");
}
Log.d(TAG, "6: " + hardware.get(6));
if (Build.HARDWARE != null) {
hardware.add(Build.HARDWARE);
} else {
hardware.add("Not found");
}
Log.d(TAG, "7: " + hardware.get(7));
if (Build.PRODUCT != null) {
hardware.add(Build.PRODUCT);
} else {
hardware.add("Not found");
}
Log.d(TAG, "8: " + hardware.get(8));
if (Build.DISPLAY != null) {
hardware.add(Build.DISPLAY);
} else {
hardware.add("Not found");
}
Log.d(TAG, "9: " + hardware.get(9));
if (Build.HOST != null) {
hardware.add(Build.HOST);
} else {
hardware.add("Not found");
}
Log.d(TAG, "10: " + hardware.get(10));
hardware.add(process_info[0]);
Log.d(TAG, "11: " + hardware.get(11));
hardware.add(process_info[1]);
Log.d(TAG, "12: " + hardware.get(12));
hardware.add(process_info[2]);
Log.d(TAG, "13: " + hardware.get(13));
hardware.add(screen_info[0]);
Log.d(TAG, "14: " + hardware.get(14));
hardware.add(screen_info[1]);
Log.d(TAG, "15: " + hardware.get(15));
hardware.add(screen_info[2]);
Log.d(TAG, "16: " + hardware.get(16));
hardware.add(cpu_info_freq[0]);
Log.d(TAG, "17: " + hardware.get(17));
hardware.add(cpu_info_freq[1]);
Log.d(TAG, "18: " + hardware.get(18));
/*
* if (cam != 0 && camera != null) { Camera.Parameters
* cameraParameters = camera.getParameters(); Log.d("appcheck",
* "cameraParameters: " + cameraParameters);
*
* if (cameraParameters == null) { hardware.add("Not found");
* hardware.add("Not found"); hardware.add("Not found");
* hardware.add("Not found"); hardware.add("Not found"); } else { if
* (cameraParameters.getSupportedColorEffects() == null) {
* hardware.add("Not found"); } else {
* hardware.add(cameraParameters.
* getSupportedColorEffects().toString()); } Log.d(TAG, "19: " +
* hardware.get(19)); if (cameraParameters.getSupportedFocusModes()
* == null) { hardware.add("Not found"); } else {
* hardware.add(cameraParameters
* .getSupportedFocusModes().toString()); } Log.d(TAG, "20: " +
* hardware.get(20)); if
* (cameraParameters.getSupportedPictureFormats() == null) {
* hardware.add("Not found"); } else {
* hardware.add(cameraParameters.
* getSupportedPictureFormats().toString()); } Log.d(TAG, "21: " +
* hardware.get(21)); if (cameraParameters.getVerticalViewAngle() ==
* 0.0 ) { hardware.add("Not found"); } else {
* hardware.add(String.valueOf
* (cameraParameters.getVerticalViewAngle())); } Log.d(TAG, "22: " +
* hardware.get(22)); if (cameraParameters.getZoomRatios() == null)
* { hardware.add("Not found"); } else {
* hardware.add(cameraParameters.getZoomRatios().toString()); }
* Log.d(TAG, "23: " + hardware.get(23)); } }else {
* hardware.add("Not found"); Log.d(TAG, "19: " + hardware.get(19));
* hardware.add("Not found"); Log.d(TAG, "20: " + hardware.get(20));
* hardware.add("Not found"); Log.d(TAG, "21: " + hardware.get(21));
* hardware.add("Not found"); Log.d(TAG, "22: " + hardware.get(22));
* hardware.add("Not found"); Log.d(TAG, "23: " + hardware.get(23));
* }
*/
hardware.add("Not found");
Log.d(TAG, "19: " + hardware.get(19));
hardware.add("Not found");
Log.d(TAG, "20: " + hardware.get(20));
hardware.add("Not found");
Log.d(TAG, "21: " + hardware.get(21));
hardware.add("Not found");
Log.d(TAG, "22: " + hardware.get(22));
hardware.add("Not found");
Log.d(TAG, "23: " + hardware.get(23));
if (deviceId == null) {
deviceId = "Not found";
}
hardware.add(deviceId);
Log.d(TAG, "24: " + hardware.get(24));
hardware.add(sensorsList());
Log.d(TAG, "25: " + hardware.get(25));
Log.d(TAG, "SELECT ALL: " + sd.selectAll().toString());
List<String> records = sd.selectAll();
if (records.size() == 0) {
sd.insert(hardware.get(0), hardware.get(1), hardware.get(2),
hardware.get(3), hardware.get(4), hardware.get(5),
hardware.get(6), hardware.get(7), hardware.get(8),
hardware.get(9), hardware.get(10), hardware.get(11),
hardware.get(12), hardware.get(13), hardware.get(14),
hardware.get(15), hardware.get(16), hardware.get(17),
hardware.get(18), hardware.get(19), hardware.get(20),
hardware.get(21), hardware.get(22), hardware.get(23),
hardware.get(24), hardware.get(25));
}
Log.d(TAG,
"\n====================================== END =================================================\n");
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Static data error");
}
this.startService(new Intent(this, Registration.class));
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "ACTIVITY ONSTART");
/* Button btn = (Button) findViewById(R.id.upload);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//uploadServerData();
}
}); */
}
private String deviceInfo() {
Log.d(TAG, "deviceId: " + deviceId);
androidId = ""
+ android.provider.Settings.Secure.getString(
getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);
String deviceUid = "";
Log.d(TAG, "androidId: " + androidId);
if (deviceId == null || androidId == null) {
deviceUid = "35" + Build.BOARD.length() % 10 + Build.BRAND.length()
% 10 + Build.CPU_ABI.length() % 10 + Build.DEVICE.length()
% 10 + Build.DISPLAY.length() % 10 + Build.HOST.length()
% 10 + Build.ID.length() % 10 + Build.MANUFACTURER.length()
% 10 + Build.MODEL.length() % 10 + Build.PRODUCT.length()
% 10 + Build.TAGS.length() % 10 + Build.TYPE.length() % 10
+ Build.USER.length() % 10;
} else {
UUID deviceUuid = new UUID(androidId.hashCode(),
(long) deviceId.hashCode() << 32);
deviceUid = deviceUuid.toString();
}
Log.d(TAG, "Uid: " + deviceUid);
return deviceUid;
}
private String[] ProcessorInfo() {
FileReader fileStream = null;
String line;
String[] segs;
String[] proc_info = new String[3];
BufferedReader inStream = null;
try {
fileStream = new FileReader(PROC_FILE);
inStream = new BufferedReader(fileStream);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (inStream != null) {
while ((line = inStream.readLine()) != null) {
if (line.startsWith("Processor")) {
segs = line.trim().split("[:] +");
Log.d(TAG, segs[1].toString());
proc_info[0] = segs[1].toString();
} else if (line.startsWith("BogoMIPS")) {
segs = line.trim().split("[:] +");
Log.d(TAG, segs[1].toString());
proc_info[1] = segs[1].toString();
} else if (line.startsWith("CPU architecture")) {
segs = line.trim().split("[:] +");
Log.d(TAG, segs[1].toString());
proc_info[2] = segs[1].toString();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int p = 0; p < proc_info.length; p++) {
if (proc_info[p] == null) {
proc_info[p] = "Not found";
}
}
return proc_info;
}
private String[] cpu_freq() {
FileReader fileStream = null, fileStream1 = null;
String line, line1;
String[] cpu_frq = new String[2];
BufferedReader inStream = null, inStream1 = null;
try {
fileStream = new FileReader(CPU_FREQ_MAX_INFO);
fileStream1 = new FileReader(CPU_FREQ_MIN_INFO);
inStream = new BufferedReader(fileStream);
inStream1 = new BufferedReader(fileStream1);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (inStream != null && inStream1 != null) {
while ((line = inStream.readLine()) != null
&& (line1 = inStream1.readLine()) != null) {
cpu_frq[0] = line + "hz";
cpu_frq[1] = line1 + "hz";
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int c = 0; c < cpu_frq.length; c++) {
if (cpu_frq[c] == null) {
cpu_frq[c] = "Not found";
}
}
return cpu_frq;
}
private String[] screenInfo() {
String[] screeninfo = new String[3];
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
final int height = dm.heightPixels;
final int width = dm.widthPixels;
Log.d(TAG, "X factor: " + dm.xdpi);
Log.d(TAG, "Y factor: " + dm.ydpi);
Log.d(TAG, "Density: " + dm.densityDpi);
screeninfo[2] = String.valueOf(dm.densityDpi);
Log.d(TAG, "Height: " + height);
Log.d(TAG, "Width: " + width);
Log.d(TAG, "Resolution: " + width + "*" + height);
screeninfo[0] = width + "*" + height;
Log.d(TAG, "Scaled Density: " + dm.scaledDensity);
double screen_size = Math.sqrt(height ^ 2 + width ^ 2) / dm.densityDpi;
screeninfo[1] = String.valueOf(screen_size);
Log.d(TAG, "Screen size: " + screen_size);
for (int s = 0; s < screeninfo.length; s++) {
if (screeninfo[s] == null) {
screeninfo[s] = "Not found";
}
}
return screeninfo;
}
private String sensorsList() {
SensorManager sensormgr = (SensorManager) getSystemService(SENSOR_SERVICE);
List<Sensor> list = sensormgr.getSensorList(Sensor.TYPE_ALL);
String sens = "";
if (list.size() != 0) {
for (Sensor sensorlist : list) {
sens = sens.concat(sensorlist.getName());
sens = sens.concat("\n");
}
} else {
sens = "Not found";
}
return sens;
}
public void emailAccounts() {
Log.d(TAG, "inside emailaccount");
Account[] accounts = AccountManager.get(this).getAccounts();
int size = ead.selectAll().size();
List<String> dbAcc = ead.select();
Log.d(TAG, "dbAcc: " + dbAcc.toString());
Log.d(TAG, "size: " + dbAcc.size() + " " + "length: " + accounts.length);
if (accounts.length != 0) {
if (size == 0) {
for (Account eAccounts : accounts) {
ead.insert(eAccounts.name, eAccounts.type);
}
} else {
for (Account acc : accounts) {
if (!dbAcc.contains(acc.name + acc.type)) {
ead.insert(acc.name, acc.type);
;
}
}
}
}
}
public void totalMemoryInfo() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
String ext_available, ext_used;
String internal_available, internal_used;
long totalBlocks = stat.getBlockCount();
double internal_total = totalBlocks * blockSize;
Log.d(TAG, "internal_total: " + internal_total);
long availableBlocks = stat.getAvailableBlocks();
internal_available = String.valueOf((availableBlocks * blockSize)
/ (1024 * 1024) + " MB");
Log.d(TAG, "internal_available: " + internal_available);
internal_used = String
.valueOf((internal_total - (availableBlocks * blockSize))
/ (1024 * 1024) + " MB");
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
File path1 = Environment.getExternalStorageDirectory();
StatFs stat1 = new StatFs(path1.getPath());
long blockSize1 = stat1.getBlockSize();
long totalBlocks1 = stat1.getBlockCount();
long ext_total = totalBlocks1 * blockSize1;
Log.d(TAG, "ext_total: " + ext_total);
long availableBlocks1 = stat1.getAvailableBlocks();
ext_available = String.valueOf((availableBlocks1 * blockSize1)
/ (1024 * 1024) + " MB");
Log.d(TAG, "ext_available: " + ext_available);
ext_used = String
.valueOf((ext_total - (availableBlocks1 * blockSize1))
/ (1024 * 1024) + " MB");
} else {
ext_used = "Unmounted";
ext_available = "Unmounted";
Log.d(TAG, "ext_mem: " + "Unmounted");
}
md.insert(internal_available, internal_used, ext_available, ext_used);
}
public void toastMess(String responseValue, Context cxt) {
Toast.makeText(cxt, responseValue, Toast.LENGTH_SHORT).show();
}
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_stop:
stopService(new Intent(DeviceIntelligence.this, Registration.class));
stopService(new Intent(DeviceIntelligence.this, MainService.class));
//Toast.makeText(getApplicationContext(), "Application stopped",Toast.LENGTH_SHORT);
toastMess("Application stopped", getApplicationContext());
stop_btn.setEnabled(false);
//stop_btn.setBackgroundColor(Color.GRAY);
break;
case R.id.btn_app_show:
startActivity(new Intent(DeviceIntelligence.this,ApplicationList.class));
Log.d("DM","Inside app show");
break;
case R.id.btn_browse_show:
startActivity(new Intent(DeviceIntelligence.this,BrowseList.class));
Log.d("DM", "Inside browse");
break;
case R.id.btn_stat:
startActivity(new Intent(DeviceIntelligence.this, StatisticsList.class));
Log.d("DM","Statistics");
break;
case R.id.settings:
Log.d("DM","Settings");
startActivity(new Intent(DeviceIntelligence.this, Settings.class));
break;
}
}
public void uploadServerData(Context ctx){
su = new ServerUpload();
su.uploadStaticDetails(ctx);
su.uploadurl(ctx);
su.uploadAppBehaviour(ctx);
su.uploadBootDetails(ctx);
su.uploadShutdownDetails(ctx);
su.uploadCallInfo(ctx);
su.uploadSmsInfo(ctx);
su.uploadBatteryInfo(ctx);
su.uploadAppList(ctx);
su.uploadConnectivityInfo(ctx);
// su.uploadEmailInfo(ctx);
// su.uploadAppUpdated(ctx);
su.uploadScreenInfo(ctx);
su.uploadTotalMemoryInfo(ctx);
}
}
You must create your activity using AITC2#getActivity() before invoking emailAccounts().
public void testEmailAccounts() {
DeviceIntelligence activity = getActivity();
activity.emailAccounts();
// ...
}
BTW, you should never try to create your Activities using new, like in new DeviceIntelligence().

Categories

Resources