Related
Hi in the below code I was implemented table layout contains table rows named as Title,File name,View/Download in the last row View/Download added a row named as Preview If user click on the preview I want to pass the path name and show into some pdf format .
Can any one help me it is giving me blank screen
java:
String operation = "getRelatedDocuments";
String module = "Documents";
final String record=opportunitywon_id;
Log.d("record",record);
final APIService service = RetroClass.getRetrofitInstance().create(APIService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<DocumentModel> call = service.GetDocumentList(operation, sessionId, module,record);
/**Log the URL called*/
Log.i("URL Called", call.request().url() + "");
call.enqueue(new Callback<DocumentModel>() {
#Override
public void onResponse(Call<DocumentModel> call, Response<DocumentModel> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
DocumentModel documentModel = response.body();
// Gson g = new Gson();
//String jsonAllDocuments = g.toJson(documentModel);
// tinyDB.putString("jsonAllDocuments", jsonAllDocuments);
String success = documentModel.getSuccess();
if (success.equals("true")) {
ClosedwonResults closedwonResults = documentModel.getResult();
panModel = closedwonResults.getPan();
id = panModel.getId();
Log.d("docid", id);
filename = panModel.getFilename();
Log.d("filename", filename);
path = panModel.getPath();
Log.d("path", path);
GSTModel gstModel=closedwonResults.getGst();
gstId = gstModel.getId();
gstFilename=gstModel.getFilename();
gstpath=gstModel.getPath();
Purchase_orderModel purchase_orderModel=closedwonResults.getPurchase_order();
purchaseId=purchase_orderModel.getId();
purchaseFilename=purchase_orderModel.getFilename();
purchasePath=purchase_orderModel.getPath();
AdharModel adharModel=closedwonResults.getAdhar();
adharId=adharModel.getId();
adharFilename=adharModel.getFilename();
adharPath=adharModel.getPath();
ChecqueModel checqueModel=closedwonResults.getChecque();
checqueId=checqueModel.getId();
checqueFilename=checqueModel.getFilename();
checquepath=checqueModel.getPath();
Doc_oneModel doc_oneModel = closedwonResults.getDoc_one();
doc_oneid = doc_oneModel.getId();
Log.d("doc_oneid", doc_oneid);
doc_onefilename = doc_oneModel.getFilename();
Log.d("doc_onefilename", doc_onefilename);
doc_onepath = doc_oneModel.getPath();
Log.d("doc_onepath", doc_onepath);
Doc_twoModel doc_twoModel = closedwonResults.getDoc_two();
doc_twoid = doc_twoModel.getId();
Log.d("doc_twoid", doc_twoid);
doc_twofilename = doc_twoModel.getFilename();
Log.d("doc_twofilename", doc_twofilename);
doc_twopath = doc_twoModel.getPath();
Log.d("doc_twopath", doc_twopath);
docModel = new DocModel(filename,adharFilename,gstFilename,purchaseFilename,checqueFilename,doc_onefilename,doc_twofilename,path,adharPath,gstpath,checquepath,purchasePath,doc_onepath,doc_twopath);
closedwonList.add(docModel);
}
// DocModel docModel1=closedwonList.get(position);
documentIDS = docModel.getFilename() + "," + docModel.getDoc_onefilename() + "," + docModel.getDoc_twofilename() + "," +
docModel.getAdharfilename() + "," + docModel.getChecquefilename() + "," + docModel.getGstfilename() + "," + docModel.getPurchasefilename();
Paths=docModel.getPath()+","+docModel.getGstpath()+","+docModel.getChecquepath()+","+
docModel.getAdharpath()+","+docModel.getPurchasepath()+","+docModel.getDoc_onepath()+","+docModel.getDoctwopath();
String[] stringArray2 = {"PAN","AADHAR","GST","PURCHASE ORDER","CHECQUE","dOC ONE","DOC TWO"};
TableRow tbrowdoc = new TableRow(getContext());
Resources resourcedoc = getContext().getResources();
tbrowdoc.setLayoutParams(getLayoutParams());
tbrowdoc.addView(getTextView(0, "Title", Color.WHITE, resourcedoc.getColor(R.color.tabs1)));
tbrowdoc.addView(getTextView(0, "File Name", Color.WHITE, resourcedoc.getColor(R.color.tabs1)));
tbrowdoc.addView(getTextView(0, "View/Download", Color.WHITE,resourcedoc.getColor(R.color.tabs1)));
documents.addView(tbrowdoc, getLayoutParams());
String[] IDSList = documentIDS.split(",");
String[] PathList=Paths.split(",");
url="http://XXXXXXX/".concat(String.valueOf(PathList));
int arrayDoc = stringArray2.length;
for (int i = 0; i < arrayDoc; i++) {
final TableRow tbrowdocdetails = new TableRow(getContext());
tbrowdocdetails.setLayoutParams(getLayoutParams());
tbrowdocdetails.addView(getTextView(i + arrayDoc, stringArray2[i], Color.BLACK, ContextCompat.getColor(getContext(), R.color.back_blue)));
tbrowdocdetails.addView(getTextView(i + arrayDoc, IDSList[i], Color.BLACK, ContextCompat.getColor(getContext(), R.color.back_blue)));
tbrowdocdetails.addView(getTextView1(i + arrayDoc, "Preview", Color.BLACK, ContextCompat.getColor(getContext(), R.color.back_blue),position));
documents.addView(tbrowdocdetails);
}
}
else{
Toast.makeText(getContext(),"Something went wrong",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<DocumentModel> call, Throwable t) {
Log.d("error", t.getMessage());
}
});
private TextView getTextView1(int id, final String title, int color, int bgColor, final int position) {
lblClick = new TextView(getContext());
lblClick.setId(id);
lblClick.setText(title.toLowerCase());
lblClick.setTextColor(color);
lblClick.setGravity(Gravity.CENTER);
lblClick.setPadding(10, 10, 10, 10);
lblClick.setBackgroundColor(bgColor);
lblClick.setTag(url);
lblClick.setLayoutParams(getLayoutParams());
lblClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String path=v.getTag().toString();
Toast.makeText(getContext(),path,Toast.LENGTH_LONG).show();
myPDfItemClick(position);
}
});
return lblClick;
}
Method:
#Override
public void myPDfItemClick(int position) {
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, 112);
if (!hasPermissions(getContext(), PERMISSIONS)) {
Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");
Toast t = Toast.makeText(getContext().getApplicationContext(), "You don't have read access !", Toast.LENGTH_LONG);
t.show();
} else {
File d = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); // -> filename = maven.pdf
String url_path = listSalesStageOpportunity.get(position).getPdf_link();
///Log.d("url_path", url_path);
String file_name = url_path.substring(url_path.lastIndexOf('/') + 1);
//Log.d("file_name", file_name);
File pdfFile = new File(d, file_name);
Log.v(TAG, "view() Method pdfFile " + pdfFile.getAbsolutePath());
if (pdfFile != null) {
Uri path = GenericFileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", pdfFile);
Log.v(TAG, "view() Method path " + url_path);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
// }
}
Log.v(TAG, "view() Method completed ");
// download(v);
}
download(position);
request(position);
}
public void request(int position) {
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, 112);
}
public void download(int position) {
Log.v(TAG, "download() Method invoked ");
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, 112);
if (!hasPermissions(getContext(), PERMISSIONS)) {
Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");
Toast t = Toast.makeText(getContext().getApplicationContext(), "You don't have write access !", Toast.LENGTH_LONG);
t.show();
} else {
Log.v(TAG, "download() Method HAVE PERMISSIONS ");
String url_path = listSalesStageOpportunity.get(position).getPdf_link();
Log.d("url_path", url_path);
String file_name = url_path.substring(url_path.lastIndexOf('/') + 1);
Log.d("file_name", file_name);
new DownloadFile().execute(url_path, file_name);
}
Log.v(TAG, "download() Method completed ");
}
I am trying to make an android app for RFID card reader (i am not using NFC), for this i connect one high frquency RFID card reader through OTG cable and i am using EditText where card number is displaying. it is working fine, but problem is sometime it detects multiple time card number.
1- Any idea how can i resolve this (i cannot put size limit condition because card number length is not fixed)?
2- One more problem when i am using ultra high frequency card reader then card is showing different value, any idea how can i make an android app which supports both frequency card readers.
Rfid continue reading tag its not one time reading so from this repetition you have to manage to your side. Check its reading data or not if yes then ignore.Below the call Where implement Rfid methods and its reading data handle.
public class ReaderListener implements RfidEventListener {
private RfidReader reader;
private ReadInventory eventForm;
//private ItemTransfer eventFormitm;
private final ToneGenerator tg = new ToneGenerator(5, 100);
private boolean isEnabled;
private Map<String, Long> scannedItemsMap = new TreeMap<String, Long>();
public ReaderListener(ReadInventory frm, String make, String macid) throws ReaderConnectionException, LicenseExpiryException, IOException, GeneralSecurityException {
Log.d("Test1", " "+make.toString().trim()+" "+ macid.toString().trim());
reader = RfidFactory.getInstance().getRfidReader(make.toString().trim(), macid.toString().trim(),
PlatformConnector.AndroidConnector.getPlatformName());
Log.d("Test2", " "+reader+" ");
//reader.removeAllListeners();
reader.registerListener(this);
setEnabled(true);
this.eventForm = frm;
}
#Override
public void handleData(String tagid, int arg1, int arg2) {
synchronized (scannedItemsMap) {
if (!scannedItemsMap.containsKey(tagid)) {
System.out.println("got data............ :" + tagid);
scannedItemsMap.put(tagid, System.currentTimeMillis());
if (eventForm != null) {
eventForm.handleData(tagid);
//this.tg.startTone(25);
Log.d("tagid", " " + tagid + " ");
}
/*if (eventFormitm != null) {
eventFormitm.handleData(tagid);
}*/
} else if (scannedItemsMap.containsKey(tagid)) {
scannedItemsMap.put(tagid, System.currentTimeMillis());
}
}
}
#Override
public void handleError(String msg) {
if (eventForm != null) {
eventForm.handleError(msg);
}
}
#Override
public boolean isEnabled() {
return isEnabled;
}
#Override
public void setEnabled(boolean arg0) {
this.isEnabled = arg0;
}
public boolean startScan(int power,int speed) throws ReaderConnectionException {
if (reader != null && !reader.isScanning()) {
reader.setSession(RfidSession.ONE);
reader.setPower(power);
reader.setScanSpeed(speed);
reader.startScan();
}
return true;
}
public void stopScan() throws ReaderConnectionException {
if (reader.isScanning())
reader.stopScan();
}
public boolean isScanning() {
return reader.isScanning();
}
public boolean isConnected() {
return reader.isConnected();
}
public void removeAll() {
scannedItemsMap.clear();
}
public void remove(String tagid) {
scannedItemsMap.remove(tagid);
}
public int getBatteryLevel(){
try {
return reader.getBatteryLevel();
}catch (Exception e){
return 0;
}
}
#Override
public void handleReaderEvent(ReaderEvent arg0) {
// TODO Auto-generated method stub
}
}
Now Handle The data in activity ....
Show in below method.
public void handleData(final String tagid) {
// TODO Auto-generated method stub
try {
final String Code_samplecode = convertHexToString(tagid);
// Log.e("Name", "Itemcode" + Code_samplecode);
if (SampleCode.contains(Code_samplecode)&& !p_SampleCode.contains(Code_samplecode)) {
// Scann items count
tgf.startTone(25);
int ind_val = SampleCode.indexOf(Code_samplecode);
if (ind_val != -1) {
final String SampleNo1 = SampleNo.get(ind_val);
final String StyleNo1 = StyleNo.get(ind_val);
final String SampleCode1 = SampleCode.get(ind_val);
final String StyleCode1 = StyleCode.get(ind_val);
//final String CartStyleCode1 = CartStyleCode.get(ind_val);
// final String CartStyleNo1 = CartStyleNo.get(ind_val);
SampleNo.remove(ind_val);
StyleNo.remove(ind_val);
SampleCode.remove(ind_val);
StyleCode.remove(ind_val);
runOnUiThread(new Runnable() {
#Override
public void run() {
// p_Code.add(Code.get(ind_val));
p_SampleNo.add(SampleNo1);
p_StyleNo.add(StyleNo1);
p_SampleCode.add(SampleCode1);
p_StyleCode.add(StyleCode1);
//Code.remove(ind_val);
// adapter3.notifyDataSetChanged();
// adapter1.notifyDataSetChanged();
total_item.setAdapter(null);
adapter3 = new Adapter_for_Inventoryitem(ReadInventory.this,
StyleNo, SampleNo);
total_item.setAdapter(adapter3);
present_item.setAdapter(null);
adapter1 = new Adapter_for_Inventoryitem(ReadInventory.this,
p_StyleNo, p_SampleNo);
present_item.setAdapter(adapter1);
textvie.setText("Total " + p_SampleNo.size() + " Found Styles");
textvi.setText("Total " + SampleNo.size() + " Available Styles");
List<Inventory> c = db.get_all_data_INVENTARY_Query("SELECT * FROM Inventory_n WHERE SampleCode ='" + SampleCode1 + "'");
if (c.size() > 0) {
db.execute_query("INSERT INTO Inventory_p (Code, SampleNo,StyleNo,SampleCode,StyleCode,CartStyleNo,CartStyleCode) VALUES ('" + c.get(0).getCode() + "' , \"" +
c.get(0).getSampleNo() + "\" , \"" + c.get(0).getStyleNo() + "\" , '" +
c.get(0).getSampleCode() + "' , '" + c.get(0).getStyleCode() + "' , \"" +
c.get(0).getCartStyleNo() + "\" , '" + c.get(0).getCartStyleCode() + "')");
}
db.execute_query("DELETE FROM Inventory_n WHERE SampleCode ='" + SampleCode1 + "'");
}
});
}
} else {
if (!SampleCode.contains(Code_samplecode) && !p_SampleCode.contains(Code_samplecode)
&& !not_fount_items.contains(Code_samplecode)) {
tgn.startTone(20);
scanneditems_unkown = scanneditems_unkown + 1;
runOnUiThread(new Runnable() {
#Override
public void run() {
not_fount_items.add(Code_samplecode);
not_fount_items_txt.setText("Total " + not_fount_items.size() + " Unknown Styles");
}
});
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
scan_counts.setText("Total " + p_SampleNo.size() + " Scanned");
scan_counts_unknown.setText("Total " + scanneditems_unkown + " Unknown");
last_scanned_items.setText("Item : " + Code_samplecode);
}
});
} catch (Exception e) {
e.printStackTrace();
Message message = new Message();
message.what = READEREXCEPTION;
itemDetectedHandler.sendMessage(message);
}
}
You need to Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
//To get the characters (One By one)
event.getDisplayLabel();
}
And use Debounce (I'll recommend using RX Java) if the card numbers are of different length.
What debounce does is, it will wait for a particular amount of time after a keyevent happens, So you can concat the whole string and then use it.
I'm having Problem in updating JSON parsed informations in my Views. Nothing is problem with getting JSON text from internet it works fine. I hope parsing process also looks good. Im having problem with Displaying contents in the Views.
package rev.app.revlearningdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class JsonFromInternet extends Activity {
String jsonText, name, weather_main, description, lon, lat, temp, pressure,
humidity, temp_min, temp_max, speed, deg;
long dt, sunrise, sunset;
TextView area, info, main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather);
area = (TextView) findViewById(R.id.weatherAreaName);
info = (TextView) findViewById(R.id.weatherInfo);
main = (TextView) findViewById(R.id.weatherMain);
Thread net = new Thread() {
public void run() {
URL url;
BufferedReader buff = null;
StringBuilder build = new StringBuilder();
try {
url = new URL(
"http://api.openweathermap.org/data/2.5/weather?q=Madurai,in");
buff = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
for (String l; (l = buff.readLine()) != null;)
build.append(l.trim());
} catch (IOException e1) {
Log.e("REV DEMO", "ERROR");
} finally {
if (buff != null)
try {
buff.close();
} catch (IOException e) {
Log.e("REV DEMO", "ERROR");
}
jsonText = build.toString();
interrupt();
}
};
};
net.start();
if (net.getState()==Thread.State.TERMINATED) {
parseJsonText(jsonText);
area.setText(name);
info.setText(description + "\n" + "Longitude, Lattitude " + lon
+ ", " + lat + "\nTemperature " + temp + "\n(Min:"
+ temp_min + ", Max:" + temp_max + ")\nPressure "
+ pressure + "\nHumidity " + humidity + "\nWind Speed "
+ speed + ", direction " + deg);
main.setText(weather_main);
}
}
private void parseJsonText(String jsonFromInternet) {
JSONObject root, coord, main, wind, sys, weather;
try {
root = new JSONObject(jsonFromInternet);
coord = root.getJSONObject("coord");
lon = coord.optString("lon");
lat = coord.optString("lat");
main = root.getJSONObject("main");
temp = main.optString("temp");
pressure = main.optString("pressure");
humidity = main.optString("humidity");
temp_min = main.optString("temp_min");
temp_max = main.optString("temp_max");
wind = root.getJSONObject("wind");
speed = wind.optString("speed");
deg = wind.optString("deg");
sys = root.getJSONObject("sys");
sunrise = sys.optLong("sunrise");
sunset = sys.optLong("sunset");
dt = root.optLong("dt");
name = root.optString("name");
weather = root.optJSONArray("weather").getJSONObject(0);
weather_main = weather.optString("main");
description = weather.optString("description");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You start asynchronous Thread to download the JSON and it means that your views are getting updated immediately (when your jsonText is not initialized yet).
Move updating your views into the end of run() method and update your views when you finished parsing data, not earlier. Warning: to call setText from thread you will have to use runOnUiThread method.
Thread net = new Thread() {
public void run() {
URL url;
BufferedReader buff = null;
StringBuilder build = new StringBuilder();
try {
url = new URL(
"http://api.openweathermap.org/data/2.5/weather?q=Madurai,in");
buff = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
for (String l; (l = buff.readLine()) != null;)
build.append(l.trim());
// parse and update views now:
jsonText = build.toString();
parseJsonText(jsonText);
runOnUiThread(new Runnable() {
#Override
public void run() {
area.setText(name);
info.setText(description + "\n" + "Longitude, Lattitude " + lon
+ ", " + lat + "\nTemperature " + temp + "\n(Min:"
+ temp_min + ", Max:" + temp_max + ")\nPressure "
+ pressure + "\nHumidity " + humidity + "\nWind Speed "
+ speed + ", direction " + deg);
main.setText(weather_main);
}
});
} catch (IOException e1) {
Log.e("REV DEMO", "ERROR");
} finally {
if (buff != null)
try {
buff.close();
} catch (IOException e) {
Log.e("REV DEMO", "ERROR");
}
interrupt();
}
};
};
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
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().