I've got a couple of activities.
The app is running out of memory. I tried to gc.clean() in all activities (in onDestroy), null references, launchMode="singleTop" but without any success.
In MAT I've found out that I have multiple objects of the same activity and it's a default behaviour, if I'm not mistaken.
For example, at first launch I will have the main activity, if I quit and launch again, I will have 2 instances.
This makes the VM grow until the force close dialog is shown.
Example of my code:
public class Splash extends Activity
{
private static Handler handler;
private static Thread splashThread;
private MyProgressDialog dialog;
private Netroads netroads;
private int debug;
private AsyncTask<Void,Void,Void> mConnectionTask;
private boolean checkInternetConnection = false;
private SharedPreferences ref;
private SharedPreferences.Editor ed;
private boolean firstOperationKey = false;
private boolean userPay = false;
private String macAddress = "";
private String answer = "";
private String extra = "";
private int status = Consts.STATUS_SERVER_BUSY;
private String paymentType = "";
private boolean paymentStatus = false;
private String versionName = "";
private RelativeLayout splash_layout;
private RelativeLayout welcome_message_layout;
private TextView welcome_message_text;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_layout);
getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
netroads = ((Netroads)getApplicationContext());
ref = getSharedPreferences("NETROADS",MODE_PRIVATE);
ed = ref.edit();
//ed.putString("userID","2");
//ed.putBoolean("LOGOUT",false);
//ed.commit();
//change background by LANGUAGEMODENUMBER
splash_layout = (RelativeLayout)findViewById(R.id.splash_layout);
welcome_message_layout = (RelativeLayout)findViewById(R.id.welcome_message_layout);
//welcome_message_layout = new RelativeLayout(getApplicationContext());
welcome_message_text = (TextView)findViewById(R.id.welcome_message_text);
//welcome_message_text = new TextView(getApplicationContext().);
if(ref.getBoolean("LANGUAGEMODECHANGE",false))
{
welcome_message_layout.setBackgroundResource(R.drawable.welcome_message);
welcome_message_text.setText(getString(R.string.welcome));
switch(ref.getInt("LANGUAGEMODENUMBER",Consts.DEFAULT))
{
case Consts.HEBREW:
splash_layout.setBackgroundResource(R.drawable.welcome_hebrew);
break;
case Consts.ENGLISH:
splash_layout.setBackgroundResource(R.drawable.welcome_english);
break;
case Consts.RUSSIAN:
splash_layout.setBackgroundResource(R.drawable.welcome_russian);
break;
case Consts.ARABIC:
splash_layout.setBackgroundResource(R.drawable.welcome_arabic);
break;
default:
splash_layout.setBackgroundResource(R.drawable.bg);
break;
}//close switch
}
if(ref.getBoolean("LANGUAGEMODECHANGE",false))
{
ed.putBoolean("LANGUAGEMODECHANGE",false);
ed.commit();
}
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isWifiEnabled())
{
WifiInfo info = wifiManager.getConnectionInfo();
macAddress = info.getMacAddress();
}
else
{
wifiManager.setWifiEnabled(true);
WifiInfo info = wifiManager.getConnectionInfo();
macAddress = info.getMacAddress();
wifiManager.setWifiEnabled(false);
}
PackageInfo pinfo;
try {
pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
versionName = pinfo.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
handler = new Handler();
splashThread = (Thread) getLastNonConfigurationInstance();
if (splashThread != null && splashThread.isAlive())
{
dialog = MyProgressDialog.show(this,"","");
}
}//close onCreate
public void onResume()
{
super.onResume();
debug = 0;
if(debug == 1)
{
Intent intent = new Intent(Splash.this, Main.class);
startActivity(intent);
Splash.this.finish();
}
else
{
dialog = MyProgressDialog.show(this,"","");
if(netroads.checkGPS(Splash.this))
{
mConnectionTask = new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
for(int i=0;i<3;i++)
{
HttpGet requestForTest = new HttpGet("http://m.google.com");
try
{
new DefaultHttpClient().execute(requestForTest);
checkInternetConnection = true;
}
catch (Exception e)
{
checkInternetConnection = false;
}
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
dialog.dismiss();
mConnectionTask = null;
if(checkInternetConnection)
{
dialog = MyProgressDialog.show(Splash.this,"","");
startSplashThread();
}
else
{
netroads.showRegularDialog(getString(R.string.connection_problem), getString(R.string.internet_connection_problem), getString(R.string.ok), Splash.this);
}
}
};
mConnectionTask.execute(null, null, null);
}
else
{
dialog.dismiss();
netroads.showGPSAlert(Splash.this);
}
}
}//close onResume
public void startSplashThread()
{
splashThread = new splashThread();
splashThread.start();
}//close splashThread
// Save the thread
#Override
public Object onRetainNonConfigurationInstance() {
return splashThread;
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (dialog != null)
{
dialog.dismiss();
dialog = null;
}
netroads.unbindDrawables(findViewById(R.id.splash_layout));
System.gc();
}//close onDestroy
public class splashThread extends Thread
{
#Override
public void run()
{
try
{
if(ConnectionDetector.checkInternetConnection())
{
if(ref.getString("userID","").equalsIgnoreCase("") || ref.getBoolean("LOGOUT",false))
firstOperationKey = true; //first operation after download from google play
else
{
checkUserActive();
netroads.getUsersCount(Splash.this);
}
handler.post(new splashRunnable());
}
}
finally
{
splashThread.interrupt();
}
}
}//close splashThread
public class splashRunnable implements Runnable
{
public void run()
{
dialog.dismiss();
if(firstOperationKey)
{
Intent intent = new Intent(Splash.this,AppDescription.class);
startActivity(intent);
finish();
}
else if(status == Consts.STATUS_OPERATION_SUCCESSFUL)
{
if(netroads.answerFromServerIsOK(answer))
{
Intent intent = new Intent(Splash.this,Main.class);
startActivity(intent);
finish();
}
else
{
Log.e(Consts.TAG,"STATUS = OK, ANSWER = -2 (CLEAR SESSION)");
clearSession();
}
}
else if(status == Consts.STATUS_USER_UNEXISTS)
{
clearSession();
}
else
{
netroads.answerFromServerIsOK(answer);
netroads.serverException(Splash.this,status);
}
}
}//close splashRunnable
public void clearSession()
{
ed.putBoolean("LOGOUT",true);
ed.commit();
startSplashThread();
}//close clearSession
public boolean checkUserActive()
{
Log.e(Consts.TAG,"checkUserActive()");
String url = new String(Consts.SERVER + "checkUserActive");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userID",ref.getString("userID","")));
nameValuePairs.add(new BasicNameValuePair("MAC",macAddress));
httppost.addHeader("appPassword",Consts.APP_PASSWORD);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
String xmlString = EntityUtils.toString(httpEntity);
Log.d(Consts.TAG,xmlString);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlString));
Document doc = db.parse(inStream);
NodeList nodeList;
boolean normalize = false;
try
{
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("Client");
normalize = true;
}
catch(Exception e)
{
nodeList = null;
}
if(normalize)
if(nodeList.getLength() > 0)
{
for(int i=0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
Element firstElement = (Element) node;
try{
NodeList myNodeList = firstElement.getElementsByTagName("userID");
Element myElement = (Element)myNodeList.item(0);
myNodeList = myElement.getChildNodes();
Log.d(Consts.TAG,"checkUserActive - userID:"+myNodeList.item(0).getNodeValue());
myNodeList = firstElement.getElementsByTagName("status");
myElement = (Element)myNodeList.item(0);
myNodeList = myElement.getChildNodes();
status = Integer.parseInt(myNodeList.item(0).getNodeValue());
myNodeList = firstElement.getElementsByTagName("answer");
myElement = (Element)myNodeList.item(0);
myNodeList = myElement.getChildNodes();
answer = myNodeList.item(0).getNodeValue();
myNodeList = firstElement.getElementsByTagName("extra");
myElement = (Element)myNodeList.item(0);
myNodeList = myElement.getChildNodes();
extra = myNodeList.item(0).getNodeValue();
Netroads.paymentKey = extra;
}catch(Exception e){e.printStackTrace();}
}//close for
return true;
}//close if
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return false;
}//close checkUserActive
#Override
protected void onActivityResult(int requestCode,int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//if user is google play, paypal,...
if(resultCode == Consts.PAYMENT_STATUS_IAP)
{
Log.e(Consts.TAG,"onActivityResult() - Splash");
try
{
paymentStatus = data.getExtras().getBoolean("paymentStatus");
}
catch(Exception e){paymentStatus = false;}
if(paymentStatus)
{
paymentType = data.getExtras().getString("paymentType");
netroads.startSetUser(Splash.this,paymentType,"1","2",macAddress,versionName,ref.getString("userID",""));//TODO Chane to auto function
}
else
{
netroads.showRegularDialog(getString(R.string.netroads_server),getString(R.string.user_cancel_purchase),getString(R.string.ok),Splash.this);
}
}
}//close onActivityResult
}//close Splash
Where is the leak?
EDIT:
Here are the photos:
Could it be ralated to WifiManager that is not releasing a Context reference?
http://code.google.com/p/android/issues/detail?id=43945
I think you may be looking at this the wrong way.
What is the crash exactly? Does it lead to one of the splash_layout.setBackgroundResource(...) calls?
If yes, it is possible that your images are way too big (how much to they weight?).
If that is the case you should consider resizing the images and maybe look at http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
Related
I know that there is a lot of questions about this, but I'm desperated...
I'm trying to show a Dialog while doing an AsyncTask, that must be easy but I'm no able to do it...
I had tried with .execute() and .get() and I had put a for to make the task take a long time, but nothing..
Here is my class:
public class OrdenNuevaActivity extends Activity {
#Override
protected void onCreate(Bundle bundle) {
Log.v("FLUJO", this.getClass().toString());
super.onCreate(bundle);
setContentView(R.layout.activity_orden_nueva);
aceptarOrdenNuevaButton = (Button) findViewById(R.id.aceptarOrdenNuevaButton);
aceptarOrdenNuevaButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase tareaCambiarEstadoOrdenEnBDServer = new TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase(idOrden, Estados.ACEPTADO,OrdenNuevaActivity.this);
try {
tareaCambiarEstadoOrdenEnBDServer.execute();
} catch (Exception e) {
e.printStackTrace();
}
Toast toast1 = Toast.makeText(getApplicationContext(), "Orden Aceptada", Toast.LENGTH_SHORT);
toast1.show();
NotificationManager notifManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancelAll();
UtilsVictor.addPuebloAlAceptarOrden(context,terminoOrdenAceptadaDetalleTV.getText().toString());
finish();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(OrdenNuevaActivity.this).create();
alertDialog.setTitle("ERROR!");
alertDialog.setMessage("NO hay cobertura, vuelva a intentarlo mas tarde");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setIcon(R.drawable.common_signin_btn_icon_normal_light);
alertDialog.show();
}
}
});
}
public class TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase extends AsyncTask<String,Integer,Boolean>{
private static final String TAG = "AppMovil";
private Integer mOrdenId;
private String mEstadoString;
boolean resul = true;
boolean tareaRealizada = false;
boolean catchPasado = false;
private Context mContext;
private ProgressDialog mPD;
public TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase(Integer idO ,String estadoO, Context cntx) {
mContext = cntx;
mOrdenId = idO;
mEstadoString = estadoO;
mPD = new ProgressDialog(mContext);
}
public boolean getResultado(){
return resul;
}
public boolean getTareaRealizada(){
return tareaRealizada;
}
public boolean getCatchPasado(){
return catchPasado;
}
#Override
protected void onPreExecute() {
mPD.setTitle("Please Wait..");
mPD.setMessage("Loading...");
mPD.setCancelable(false);
mPD.show();
}
#Override
protected Boolean doInBackground(String... params) {
for(int i=0; i<999999;i++){
Log.v("A", "A");
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("id", mOrdenId);
jsonObject.put("estado", mEstadoString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URIS.URI_TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoString);
post.setHeader("content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(jsonObject.toString());
post.setEntity(stringEntity);
HttpResponse response = httpClient.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode >200 & responseCode < 400) {
Log.v(TAG, "Orden Enviada OK a nuestro Server");
tareaRealizada = true;
resul = true;
} else {
Log.v(TAG, "FALLO al Enviar Orden a nuestro Server");
resul = false;
tareaRealizada = true;
}
} catch (Exception e) {
catchPasado = true;
resul = false;
e.printStackTrace();
}
return resul;
}
#Override
protected void onCancelled() {
if(mPD.isShowing()){
mPD.dismiss();
}
}
#Override
protected void onPostExecute(Boolean result) {
if(mPD.isShowing()){
mPD.dismiss();
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}
Where is the mistake?
I am new to android programming,I got a chance to work with (wifi printers).In my application I have a pdf file which needs to be taken a printout by using wifi printer
I didnt have much idea on this,but after doing a research I got that,there are 3 things to be done for doing this
1)getting the list of devices which are connected to wifi network which my mobile is using right now.
2) Then,select a device and make a connection with that device.
3) Transfer data to a printer
I hope these are the steps which I need to use.
I worked on first point,but I am getting the (Wifi networks like Tata communications,vonline etc) but not the devices which are connecting to that networks.
Here is the code I used.........
public class WiFiDemo extends Activity implements OnClickListener
{
WifiManager wifi;
ListView lv;
TextView textStatus;
Button buttonScan;
int size = 0;
List<ScanResult> results;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
lv = (ListView)findViewById(R.id.list);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
lv.setAdapter(this.adapter);
registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
public void onClick(View view)
{
arraylist.clear();
wifi.startScan();
checkWifi();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try
{
size = size - 1;
while (size >= 0)
{
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY, results.get(size).SSID + " " + results.get(size).capabilities);
arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{ }
}
private void checkWifi(){
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
final WifiManager wifiManager =
(WifiManager)this.getSystemService(Context.WIFI_SERVICE);;
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.d("wifi","Open Wifimanager");
String scanList = wifiManager.getScanResults().toString();
Log.d("wifi","Scan:"+scanList);
}
},filter);
wifiManager.startScan();
}
}
please suggest for the solution
Thanks in advance friends
Refer this Android-wifi-print - Github, Which contains a demo application I created for the same.
Edit :
As #NileshThakkar said. we may lost connection to that link in future so, I am posting code here.. with flow.
checks connectivity.
If connected in WiFi.. am storing that WiFi configuration.
Now checking whether I already have printer's information (WiFi configuration of WiFi printer) is available or not. If available, I'll scan and get list of WiFi ScanResults and connects to that else.. It'll showing list of WiFi and clicking on that, user will connect to printer and stores that WiFi configuration for future printing jobs.
After print job completes, I'm connecting to my previous WiFi or Mobile data connection.
Now going back to 2nd step.
If user connected in Mobile data, I'm just enabling WiFi and following 3rd step.
After Print job completes, I'm just disabling WiFi. so that, We'll be connected back to Mobile data connection. (That is android default).
Libraries : gson-2.2.4, itextpdf-5.4.3
MyActivity.java
public class MyActivity extends Activity implements PrintCompleteService {
private Button mBtnPrint;
private WifiConfiguration mPrinterConfiguration, mOldWifiConfiguration;
private WifiManager mWifiManager;
private List<ScanResult> mScanResults = new ArrayList<ScanResult>();
private WifiScanner mWifiScanner;
private PrintManager mPrintManager;
private List<PrintJob> mPrintJobs;
private PrintJob mCurrentPrintJob;
private File pdfFile;
private String externalStorageDirectory;
private Handler mPrintStartHandler = new Handler();
private Handler mPrintCompleteHandler = new Handler();
private String connectionInfo;
private boolean isMobileDataConnection = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
externalStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(externalStorageDirectory, Constants.CONTROLLER_RX_PDF_FOLDER);
pdfFile = new File(folder, "Print_testing.pdf");
} catch (Exception e) {
e.printStackTrace();
}
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mWifiScanner = new WifiScanner();
mBtnPrint = (Button) findViewById(R.id.btnPrint);
mBtnPrint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connectionInfo = Util.connectionInfo(MyActivity.this);
if (connectionInfo.equalsIgnoreCase(Constants.CONTROLLER_MOBILE)) {
isMobileDataConnection = true;
if (mWifiManager.isWifiEnabled() == false) {
Toast.makeText(getApplicationContext(), "Enabling WiFi..", Toast.LENGTH_LONG).show();
mWifiManager.setWifiEnabled(true);
}
mWifiManager.startScan();
printerConfiguration();
} else if (connectionInfo.equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
Util.storeCurrentWiFiConfiguration(MyActivity.this);
printerConfiguration();
} else {
Toast.makeText(MyActivity.this, "Please connect to Internet", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
registerReceiver(mWifiScanner, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.startScan();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
try {
unregisterReceiver(mWifiScanner);
} catch (Exception e) {
e.printStackTrace();
}
}
private void printerConfiguration() {
mPrinterConfiguration = Util.getWifiConfiguration(MyActivity.this, Constants.CONTROLLER_PRINTER);
if (mPrinterConfiguration == null) {
showWifiListActivity(Constants.REQUEST_CODE_PRINTER);
} else {
boolean isPrinterAvailable = false;
mWifiManager.startScan();
for (int i = 0; i < mScanResults.size(); i++) {
if (mPrinterConfiguration.SSID.equals("\"" + mScanResults.get(i).SSID + "\"")) {
isPrinterAvailable = true;
break;
}
}
if (isPrinterAvailable) {
connectToWifi(mPrinterConfiguration);
doPrint();
} else {
showWifiListActivity(Constants.REQUEST_CODE_PRINTER);
}
}
}
private void connectToWifi(WifiConfiguration mWifiConfiguration) {
mWifiManager.enableNetwork(mWifiConfiguration.networkId, true);
}
private void showWifiListActivity(int requestCode) {
Intent iWifi = new Intent(this, WifiListActivity.class);
startActivityForResult(iWifi, requestCode);
}
#Override
public void onMessage(int status) {
mPrintJobs = mPrintManager.getPrintJobs();
mPrintCompleteHandler.postDelayed(new Runnable() {
#Override
public void run() {
mPrintCompleteHandler.postDelayed(this, 2000);
if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_COMPLETED) {
for (int i = 0; i < mPrintJobs.size(); i++) {
if (mPrintJobs.get(i).getId() == mCurrentPrintJob.getId()) {
mPrintJobs.remove(i);
}
}
switchConnection();
mPrintCompleteHandler.removeCallbacksAndMessages(null);
} else if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_FAILED) {
switchConnection();
Toast.makeText(MyActivity.this, "Print Failed!", Toast.LENGTH_LONG).show();
mPrintCompleteHandler.removeCallbacksAndMessages(null);
} else if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_CANCELED) {
switchConnection();
Toast.makeText(MyActivity.this, "Print Cancelled!", Toast.LENGTH_LONG).show();
mPrintCompleteHandler.removeCallbacksAndMessages(null);
}
}
}, 2000);
}
public void switchConnection() {
if (!isMobileDataConnection) {
mOldWifiConfiguration = Util.getWifiConfiguration(MyActivity.this, Constants.CONTROLLER_WIFI);
boolean isWifiAvailable = false;
mWifiManager.startScan();
for (int i = 0; i < mScanResults.size(); i++) {
if (mOldWifiConfiguration.SSID.equals("\"" + mScanResults.get(i).SSID + "\"")) {
isWifiAvailable = true;
break;
}
}
if (isWifiAvailable) {
connectToWifi(mOldWifiConfiguration);
} else {
showWifiListActivity(Constants.REQUEST_CODE_WIFI);
}
} else {
mWifiManager.setWifiEnabled(false);
}
}
public void printDocument(File pdfFile) {
mPrintManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
String jobName = getString(R.string.app_name) + " Document";
mCurrentPrintJob = mPrintManager.print(jobName, new PrintServicesAdapter(MyActivity.this, pdfFile), null);
}
public void doPrint() {
mPrintStartHandler.postDelayed(new Runnable() {
#Override
public void run() {
Log.d("PrinterConnection Status", "" + mPrinterConfiguration.status);
mPrintStartHandler.postDelayed(this, 3000);
if (mPrinterConfiguration.status == WifiConfiguration.Status.CURRENT) {
if (Util.computePDFPageCount(pdfFile) > 0) {
printDocument(pdfFile);
} else {
Toast.makeText(MyActivity.this, "Can't print, Page count is zero.", Toast.LENGTH_LONG).show();
}
mPrintStartHandler.removeCallbacksAndMessages(null);
} else if (mPrinterConfiguration.status == WifiConfiguration.Status.DISABLED) {
Toast.makeText(MyActivity.this, "Failed to connect to printer!.", Toast.LENGTH_LONG).show();
mPrintStartHandler.removeCallbacksAndMessages(null);
}
}
}, 3000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.REQUEST_CODE_PRINTER && resultCode == Constants.RESULT_CODE_PRINTER) {
mPrinterConfiguration = Util.getWifiConfiguration(MyActivity.this, Constants.CONTROLLER_PRINTER);
doPrint();
}
}
public class WifiScanner extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
mScanResults = mWifiManager.getScanResults();
Log.e("scan result size", "" + mScanResults.size());
}
}
}
WiFiListActivity.java
public class WifiListActivity extends Activity implements View.OnClickListener {
private ListView mListWifi;
private Button mBtnScan;
private WifiManager mWifiManager;
private WifiAdapter adapter;
private WifiListener mWifiListener;
private List<ScanResult> mScanResults = new ArrayList<ScanResult>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_list);
mBtnScan = (Button) findViewById(R.id.btnNext);
mBtnScan.setOnClickListener(this);
mListWifi = (ListView) findViewById(R.id.wifiList);
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (mWifiManager.isWifiEnabled() == false) {
Toast.makeText(getApplicationContext(), "wifi is disabled.. making it enabled", Toast.LENGTH_LONG).show();
mWifiManager.setWifiEnabled(true);
}
mWifiListener = new WifiListener();
adapter = new WifiAdapter(WifiListActivity.this, mScanResults);
mListWifi.setAdapter(adapter);
mListWifi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
connectToWifi(i);
}
});
}
#Override
public void onClick(View view) {
mWifiManager.startScan();
Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
try {
registerReceiver(mWifiListener, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.startScan();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
try {
unregisterReceiver(mWifiListener);
} catch (Exception e) {
e.printStackTrace();
}
}
private void connectToWifi(int position) {
final ScanResult item = mScanResults.get(position);
String Capabilities = item.capabilities;
if (Capabilities.contains("WPA")) {
AlertDialog.Builder builder = new AlertDialog.Builder(WifiListActivity.this);
builder.setTitle("Password:");
final EditText input = new EditText(WifiListActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String m_Text = input.getText().toString();
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + item.SSID + "\"";
wifiConfiguration.preSharedKey = "\"" + m_Text + "\"";
wifiConfiguration.hiddenSSID = true;
wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // For WPA
wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
int res = mWifiManager.addNetwork(wifiConfiguration);
boolean b = mWifiManager.enableNetwork(res, true);
finishActivity(wifiConfiguration, res);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else if (Capabilities.contains("WEP")) {
AlertDialog.Builder builder = new AlertDialog.Builder(WifiListActivity.this);
builder.setTitle("Title");
final EditText input = new EditText(WifiListActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String m_Text = input.getText().toString();
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + item.SSID + "\"";
wifiConfiguration.wepKeys[0] = "\"" + m_Text + "\"";
wifiConfiguration.wepTxKeyIndex = 0;
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
int res = mWifiManager.addNetwork(wifiConfiguration);
Log.d("WifiPreference", "add Network returned " + res);
boolean b = mWifiManager.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b);
finishActivity(wifiConfiguration, res);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else {
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + item.SSID + "\"";
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
int res = mWifiManager.addNetwork(wifiConfiguration);
Log.d("WifiPreference", "add Network returned " + res);
boolean b = mWifiManager.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b);
finishActivity(wifiConfiguration, res);
}
}
private void finishActivity(WifiConfiguration mWifiConfiguration, int networkId) {
mWifiConfiguration.networkId = networkId;
Util.savePrinterConfiguration(WifiListActivity.this, mWifiConfiguration);
Intent intent = new Intent();
setResult(Constants.RESULT_CODE_PRINTER, intent);
finish();
}
public class WifiListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
mScanResults = mWifiManager.getScanResults();
Log.e("scan result size ", "" + mScanResults.size());
adapter.setElements(mScanResults);
}
}
}
WifiAdapter.java
public class WifiAdapter extends BaseAdapter {
private Activity mActivity;
private List<ScanResult> mWifiList = new ArrayList<ScanResult>();
public WifiAdapter(Activity mActivity, List<ScanResult> mWifiList) {
this.mActivity = mActivity;
this.mWifiList = mWifiList;
}
#Override
public int getCount() {
return mWifiList.size();
}
#Override
public Object getItem(int i) {
return mWifiList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.custom_wifi_list_item, null);
TextView txtWifiName = (TextView) view.findViewById(R.id.txtWifiName);
txtWifiName.setText(mWifiList.get(i).SSID);
return view;
}
public void setElements(List<ScanResult> mWifis) {
this.mWifiList = mWifis;
notifyDataSetChanged();
}
}
PrintCompleteService.java
public interface PrintCompleteService {
public void onMessage(int status);
}
PrintServiceAdapter.java
public class PrintServicesAdapter extends PrintDocumentAdapter {
private Activity mActivity;
private int pageHeight;
private int pageWidth;
private PdfDocument myPdfDocument;
private int totalpages = 1;
private File pdfFile;
private PrintCompleteService mPrintCompleteService;
public PrintServicesAdapter(Activity mActivity, File pdfFile) {
this.mActivity = mActivity;
this.pdfFile = pdfFile;
this.totalpages = Util.computePDFPageCount(pdfFile);
this.mPrintCompleteService = (PrintCompleteService) mActivity;
}
#Override
public void onLayout(PrintAttributes oldAttributes,
PrintAttributes newAttributes,
CancellationSignal cancellationSignal,
LayoutResultCallback callback,
Bundle metadata) {
myPdfDocument = new PrintedPdfDocument(mActivity, newAttributes);
pageHeight =
newAttributes.getMediaSize().getHeightMils() / 1000 * 72;
pageWidth =
newAttributes.getMediaSize().getWidthMils() / 1000 * 72;
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
if (totalpages > 0) {
PrintDocumentInfo.Builder builder = new PrintDocumentInfo
.Builder(pdfFile.getName())
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(totalpages);
PrintDocumentInfo info = builder.build();
callback.onLayoutFinished(info, true);
} else {
callback.onLayoutFailed("Page count is zero.");
}
}
#Override
public void onWrite(final PageRange[] pageRanges,
final ParcelFileDescriptor destination,
final CancellationSignal cancellationSignal,
final WriteResultCallback callback) {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(pdfFile);
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
} catch (FileNotFoundException ee) {
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
#Override
public void onCancel() {
mPrintCompleteService.onMessage(Constants.PRINTER_STATUS_CANCELLED);
}
});
}
#Override
public void onFinish() {
mPrintCompleteService.onMessage(Constants.PRINTER_STATUS_COMPLETED);
}
}
Util.java
public class Util {
public static String connectionInfo(Activity mActivity) {
String result = "not connected";
ConnectivityManager cm = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
if (ni.isConnected()) {
result = Constants.CONTROLLER_WIFI;
break;
}
} else if (ni.getTypeName().equalsIgnoreCase(Constants.CONTROLLER_MOBILE)) {
if (ni.isConnected()) {
result = Constants.CONTROLLER_MOBILE;
break;
}
}
}
return result;
}
public static void saveWifiConfiguration(Activity mActivity, WifiConfiguration mWifiConfiguration) {
Gson mGson = new Gson();
Type mType = new TypeToken<WifiConfiguration>() {
}.getType();
String sJson = mGson.toJson(mWifiConfiguration, mType);
SharedPreferences mSharedPrefs = mActivity.getSharedPreferences(Constants.DEMO_PREFERENCES, Context.MODE_PRIVATE);
mSharedPrefs.edit().putString(Constants.CONTROLLER_WIFI_CONFIGURATION, sJson).commit();
}
public static void savePrinterConfiguration(Activity mActivity, WifiConfiguration mPrinterConfiguration) {
Gson mGson = new Gson();
Type mType = new TypeToken<WifiConfiguration>() {
}.getType();
String sJson = mGson.toJson(mPrinterConfiguration, mType);
SharedPreferences mSharedPrefs = mActivity.getSharedPreferences(Constants.DEMO_PREFERENCES, Context.MODE_PRIVATE);
mSharedPrefs.edit().putString(Constants.CONTROLLER_PRINTER_CONFIGURATION, sJson).commit();
}
public static WifiConfiguration getWifiConfiguration(Activity mActivity, String configurationType) {
WifiConfiguration mWifiConfiguration = new WifiConfiguration();
Gson mGson = new Gson();
SharedPreferences mSharedPrefs = mActivity.getSharedPreferences(Constants.DEMO_PREFERENCES, Context.MODE_PRIVATE);
Type mWifiConfigurationType = new TypeToken<WifiConfiguration>() {
}.getType();
String mWifiJson = "";
if (configurationType.equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
mWifiJson = mSharedPrefs.getString(Constants.CONTROLLER_WIFI_CONFIGURATION, "");
} else if (configurationType.equalsIgnoreCase(Constants.CONTROLLER_PRINTER)) {
mWifiJson = mSharedPrefs.getString(Constants.CONTROLLER_PRINTER_CONFIGURATION, "");
}
if (!mWifiJson.isEmpty()) {
mWifiConfiguration = mGson.fromJson(mWifiJson, mWifiConfigurationType);
} else {
mWifiConfiguration = null;
}
return mWifiConfiguration;
}
public static void storeCurrentWiFiConfiguration(Activity mActivity) {
try {
WifiManager wifiManager = (WifiManager) mActivity.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) {
WifiConfiguration mWifiConfiguration = new WifiConfiguration();
mWifiConfiguration.networkId = connectionInfo.getNetworkId();
mWifiConfiguration.BSSID = connectionInfo.getBSSID();
mWifiConfiguration.hiddenSSID = connectionInfo.getHiddenSSID();
mWifiConfiguration.SSID = connectionInfo.getSSID();
// store it for future use -> after print is complete you need to reconnect wifi to this network.
saveWifiConfiguration(mActivity, mWifiConfiguration);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static int computePDFPageCount(File file) {
RandomAccessFile raf = null;
int pages = 0;
try {
raf = new RandomAccessFile(file, "r");
RandomAccessFileOrArray pdfFile = new RandomAccessFileOrArray(
new RandomAccessSourceFactory().createSource(raf));
PdfReader reader = new PdfReader(pdfFile, new byte[0]);
pages = reader.getNumberOfPages();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return pages;
}
}
I have trouble using thread.join in my code below. It should wait for the thread to finish before executing the codes after it, right? It was behaving differently on different occasions.
I have three cases to check if my code goes well
App is used for the first time - works as expected but the loading page don't appear while downloading
App is used the second time (db is up to date) - works okay
App is used the third time (db is outdated, must update) - won't update, screen blacks out, then crashes
I think I have problems with this code on onCreate method:
dropOldSchedule();
dropThread.join();
triggerDownload();
Based on the logs, the code works until before this part... What can be the problem?
MainActivity.java
public class MainActivity extends Activity {
final static int INDEX_ACCTTYPE = 0;
final static int INDEX_ECN = 1;
final static int INDEX_TLN = 2;
final static int INDEX_SIN = 3;
final static int INDEX_MOBILE = 4;
final static int INDEX_CITY = 5;
final static int INDEX_START_DATE = 6;
final static int INDEX_START_TIME = 7;
final static int INDEX_END_DATE = 8;
final static int INDEX_END_TIME = 9;
final static int INDEX_REASON = 10;
final static int INDEX_DETAILS = 11;
DatabaseHandler db;
String str;
ProgressDialog pd;
TextView homeText1, homeText2, homeText3, homeText4;
final private String csvFile = "http://www.meralco.com.ph/pdf/pms/pms_test.csv";
final private String uploadDateFile = "http://www.meralco.com.ph/pdf/pms/UploadDate_test.txt";
Thread dropThread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.dropOldSchedule();
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
db.close();
pd.dismiss();
}
});
}
});
Thread getUploadDateThread = new Thread(new Runnable() {
public void run() {
try {
URL myURL = new URL(uploadDateFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
str = output;
}
else {
break;
}
}
so.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
pd.dismiss();
}
});
}
});
Thread downloadThread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.beginTransaction();
try {
URL url = new URL(csvFile);
Log.i("dl", "start");
InputStream input = url.openStream();
CSVReader reader = new CSVReader(new InputStreamReader(input));
Log.i("dl", "after reading");
String [] sched;
while ((sched = reader.readNext()) != null) {
if(sched[INDEX_CITY].equals("")) sched[INDEX_CITY]="OTHERS";
try {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
sched[INDEX_DETAILS], sched[INDEX_REASON]);
} catch (IndexOutOfBoundsException e) {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
"", sched[INDEX_REASON]);
//e.printStackTrace();
}
}
input.close();
Log.i("dl", "finished");
} catch (MalformedURLException e) {
e.printStackTrace();
db.endTransaction();
} catch (IOException e) {
e.printStackTrace();
db.endTransaction();
}
Log.d("Count", ""+db.count());
db.setTransactionSuccessful();
db.endTransaction();
writeUploadDateInTextFile();
}
});
#SuppressWarnings("unqualified-field-access")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pms_main);
Button home = (Button) findViewById(R.id.home);
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MeralcoSuite_TabletActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
homeText1 = (TextView) findViewById(R.id.home_text1);
homeText2 = (TextView) findViewById(R.id.home_text2);
homeText3 = (TextView) findViewById(R.id.home_text3);
homeText4 = (TextView) findViewById(R.id.home_text4);
homeText1.setVisibility(View.INVISIBLE);
homeText2.setVisibility(View.INVISIBLE);
homeText3.setVisibility(View.INVISIBLE);
homeText4.setVisibility(View.INVISIBLE);
getUploadDate();
try {
getUploadDateThread.join(); //wait for upload date
Log.d("getUploadDate","thread died, upload date=" + str);
if(dbExists()){
db = new DatabaseHandler(MainActivity.this);
Log.d("Count", "" + db.count());
db.close();
if(!uploadDateEqualsDateInFile()){
dropOldSchedule();
dropThread.join();
triggerDownload();
}
showDisclaimer();
Log.i("oncreate", "finished!");
return;
}
triggerDownload();
showDisclaimer();
Log.i("oncreate", "finished!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void dropOldSchedule(){
if(pd!=null && pd.isShowing())
pd.setTitle("Getting upload date...");
else
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
dropThread.start();
}
public void triggerDownload() {
if (!checkInternet()) {
showAlert("An internet connection is required to perform an update, please check that you are connected to the internet");
return;
}
if(pd!=null && pd.isShowing())
pd.setTitle("Getting upload date...");
else
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
downloadThread.start();
}
public void getUploadDate() {
Log.d("getUploadDate", "getting upload date of schedule");
if(pd!=null && pd.isShowing())
pd.setTitle("Getting upload date...");
else
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
getUploadDateThread.start();
}
public void writeUploadDateInTextFile() {
Log.d("writeUploadDateTextFile", "writing:"+str);
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
"update.txt", 0));
out.write(str);
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public void showDisclaimer() {
Log.d("ShowDisclaimer", "showing disclaimer");
homeText3
.setText("..." + str
+ "...");
homeText1.setVisibility(View.VISIBLE);
homeText2.setVisibility(View.VISIBLE);
homeText3.setVisibility(View.VISIBLE);
homeText4.setVisibility(View.VISIBLE);
Log.d("showDisclaimer", "finished showing disclaimer");
}
public boolean uploadDateEqualsDateInFile() {
Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates");
try {
String recordedDate = "";
InputStream instream = openFileInput("update.txt");
if (instream != null) { // if file the available for reading
Log.d("uploadDateEqualsDateInFile","update.txt found!");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line = null;
while ((line = buffreader.readLine()) != null) {
recordedDate = line;
Log.d("uploadDateEqualsDateInFile","recorded:"+recordedDate);
}
Log.d("uploadDateEqualsDateInFile","last upload date: " + str + ", recorded:" +recordedDate);
if(str.equals(recordedDate)) return true;
return false;
}
Log.d("uploadDateEqualsDateInFile","update.txt is null!");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public boolean checkInternet() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo infos[] = cm.getAllNetworkInfo();
for (NetworkInfo info : infos)
if (info.getState() == NetworkInfo.State.CONNECTED
|| info.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}
public boolean dbExists() {
File database=getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME);
if (!database.exists()) {
Log.i("Database", "Not Found");
return false;
}
Log.i("Database", "Found");
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (db != null) {
db.close();
}
}
#Override
protected void onPause() {
super.onPause();
if (db != null) {
db.close();
}
}
}
Sorry but I couldn't find mistakes or problems in your code. But I would strongly recommend you to use AsyncTask for doing something in different thread. AsyncTask is very easy to use and I would say that it is one of the biggest advantages of java. I really miss it in obj-c.
http://labs.makemachine.net/2010/05/android-asynctask-example/
http://marakana.com/s/video_tutorial_android_application_development_asynctask_preferences_and_options_menu,257/index.html
check those links hope that will help you.
It was already mentioned that AsyncTask is the better alternative. However, it may be the case, that your call to join will throw InterruptedException. Try to use it like this:
while(getUploadDateThread.isRunning()){
try{
getUploadDateThread.join();
} catch (InterruptedException ie){}
}
// code after join
I think the problem that your facing is that you are blocking the UI thread when you call join in the onCreate() method. You should move this code into another thread which should execute in the background and once its done you can update the UI.
Here is a sample code:
final Thread t1 = new Thread();
final Thread t2 = new Thread();
t1.start();
t2.start();
new Thread(new Runnable() {
#Override
public void run() {
// Perform all your thread joins here.
try {
t1.join();
t2.join();
} catch (Exception e) {
// TODO: handle exception
}
// This thread wont move forward unless all your threads
// mentioned above are executed or timed out.
// ------ Update UI using this method
runOnUiThread(new Runnable() {
#Override
public void run() {
// Update UI code goes here
}
});
}
}).start();
My code worked but it does not work suddenly. The code is as follows.
public class AndroidDnssdDiscoveryTestActivity extends Activity {
/** Called when the activity is first created. */
android.net.wifi.WifiManager.MulticastLock lock;
android.os.Handler handler = new android.os.Handler();
final Context context = this;
AlertDialog alert=null;
public void onCreate(Bundle savedInstanceState) {
/*
* StrictMode.ThreadPolicy was introduced since API Level 9 and the default thread policy had been changed since API Level 11,
* which in short, does not allow network operation (include HttpClient and HttpUrlConnection) get executed on UI thread.
* if you do this, you get NetworkOnMainThreadException. It needs to add the following 3 lines.
*/
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler.postDelayed(new Runnable() {
public void run() {
setUp();
}
}, 1000);
}
private String type = "_http._tcp.local.";
private JmDNS jmdns = null;
private String Servername ="test._http._tcp.local.";
private boolean _findSECE = false;
private ServiceListener listener = null;
private HttpClient httpclient = new DefaultHttpClient();
private ServiceInfo serviceInfo;
//private ServiceInfo serviceInfo;
private void setUp() {
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
lock = wifi.createMulticastLock("mylockthereturn");
lock.setReferenceCounted(true);
lock.acquire();
try {
jmdns = JmDNS.create();
notifyUser("create");
jmdns.addServiceListener(type, listener = new ServiceListener() {
public void serviceResolved(ServiceEvent ev) {
final String getName = ev.getInfo().getQualifiedName();
final String getUrl = ev.getInfo().getURLs()[0];
if(getName.equalsIgnoreCase(servername))
{
Log.d("getName",getName);
Log.d("getUrl",getUrl);
// show alert
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
alertDialog(getName,getUrl);
}
});
}else{
notifyUser("Name: " + getName+"\nURL: " + getUrl);
Log.d("getName",getName);
Log.d("getUrl",getUrl);
}
}
public void serviceRemoved(ServiceEvent ev) {
notifyUser("Service removed: " + ev.getName());
}
public void serviceAdded(ServiceEvent event) {
// Required to force serviceResolved to be called again (after the first search)
jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
});
serviceInfo = ServiceInfo.create("_http._tcp.local.", "AndroidTest", 0, "plain test service from android");
jmdns.registerService(serviceInfo);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
public void alertDialog(final String getName, final String getUrl){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("SECE service found! Do you want to control the light?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("ACTION","BUTTON Pressed");
SendHttpPost(getName,getUrl);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alert = builder.create();
alert.show();
}
private void SendHttpPost(String getName, String getUrl){
HttpGet httpget = new HttpGet(getUrl);
try {
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
byte buffer[] = new byte[1024] ;
InputStream is = entity.getContent() ;
int numBytes = is.read(buffer) ;
is.close();
String entityContents = new String(buffer,0,numBytes) ;
Log.d("getName",getName);
Log.d("getUrl",getUrl);
Log.d("replay",entityContents);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void notifyUser(final String msg) {
handler.postDelayed(new Runnable() {
public void run() {
TextView t = (TextView)findViewById(R.id.text);
t.setText("\n===========\n"+t.getText());
t.setText(msg+t.getText());
}
}, 1);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
if (jmdns != null) {
if (listener != null) {
jmdns.removeServiceListener(type, listener);
listener = null;
}
jmdns.unregisterAllServices();
try {
jmdns.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jmdns = null;
}
lock.release();
super.onStop();
}
}
And I got error like this below
"
04-23 21:56:25.031: E/WifiService(94): Multicaster binderDied
04-23 21:56:25.041: E/WifiStateMachine(94): Error! unhandled message{ what=131156 when=-9ms }
04-23 21:56:34.562: E/WifiStateMachine(94): Error! unhandled message{ what=131157 when=-3ms }
04-23 21:56:53.952: A/NetworkStats(94): problem reading network stats
04-23 21:56:53.952: A/NetworkStats(94): java.lang.IllegalStateException: problem parsing idx 1
....
"
Do you have any idea?
You could try double checking your network permissions haven't disappeared/changed.
android.permission.ACCESS_NETWORK_STATE
android.permission.ACCESS_WIFI_STATE
android.permission.INTERNET
android.permission.CHANGE_WIFI_MULTICAST_STATE
I'm making an app that sends a notification to the status bar, it sends the notification when stepping through the code in the debugger, however it never sends the notification when run in realtime.
Here is my runnable that generates the notification, again when stepping through this code in the debugger the notification runs however in realtime nothing happens.
public class NewsEvents_Service extends Service {
private static final String NEWSEVENTS = "newsevents";
private static final String KEYWORDS = "keywords";
private NotificationManager mNM;
private ArrayList<NewsEvent> neList;
private int count;
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
neList = new ArrayList<NewsEvent>();
getKeywords();
//getNewsEvents();
Thread thr = new Thread(null, mTask, "NewsEvents_Service");
thr.start();
Log.d("Thread", "IT STARTED!!!!!!????!!!!!!!!!!!!!!!?!!?");
}
#Override
public void onDestroy() {
// Cancel the notification -- we use the same ID that we had used to start it
mNM.cancel(R.string.ECS);
// Tell the user we stopped.
Toast.makeText(this, "Service Done", Toast.LENGTH_SHORT).show();
}
/**
* The function that runs in our worker thread
*/
Runnable mTask = new Runnable() {
public void run() {
getNewsEventsFromWeb();
for(NewsEvent ne : neList){
Log.d("Thread Running", "Service Code running!!!!!!!!!!!!!!!");
String body = ne.getBody().replaceAll("\\<.*?>", "");
String title = ne.getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
ne.setInterested(true);
}
}
if(ne.isInterested() == true ){
Notification note = new Notification(R.drawable.icon,
"New ECS News Event", System.currentTimeMillis());
Intent i = new Intent(NewsEvents_Service.this, FullNewsEvent.class);
i.putExtra("ne", ne);
PendingIntent pi = PendingIntent.getActivity(NewsEvents_Service.this, 0,
i, 0);
note.setLatestEventInfo(NewsEvents_Service.this, "New Event", ne.getTitle(), pi);
note.flags = Notification.FLAG_AUTO_CANCEL;
mNM.notify(R.string.ECS, note);
}
}
}
};
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* Show a notification while this service is running.
*/
private void getNewsEventsFromWeb() {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(getString(R.string.jsonnewsevents));
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private ArrayList<String> keyWordList;
public void getNewsEvents(){
try {
InputStream fi = openFileInput(NEWSEVENTS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
neList = (ArrayList<NewsEvent>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(neList == null){
neList = new ArrayList<NewsEvent>();
}
}
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
/**
* This is the object that receives interactions from clients. See RemoteService
* for a more complete example.
*/
private final IBinder mBinder = new Binder() {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
Here is my activity that schedules the service to run
public class NewsEvents extends ListActivity{
private URL JSONNewsEvents;
private ArrayList<NewsEvent> neList;
private ArrayList<String> keyWordList;
private Worker worker;
private NewsEvents ne;
public static final String KEYWORDS = "keywords";
private static final String NEWSEVENTS = "newsevents";
public static final int ONE_ID = Menu.FIRST+1;
private PendingIntent newsAlarm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsevents);
ne = this;
neList = new ArrayList<NewsEvent>();
try {
JSONNewsEvents = new URL(getString(R.string.jsonnewsevents));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
worker = new Worker(handler, this);
setListAdapter(new IconicAdapter());
getKeywords();
worker.execute(JSONNewsEvents);
}
#Override
protected void onStop() {
super.onStop();
writeNewsEvents() ;
}
#Override
protected void onPause(){
super.onPause();
writeNewsEvents();
}
private void writeNewsEvents() {
try {
OutputStream fi = openFileOutput(NEWSEVENTS, 0);
if (fi!=null) {
ObjectOutputStream out = new ObjectOutputStream(fi);
out.writeObject(neList);
out.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
}
/**
* #return
*/
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
startFullNewsEvent(neList.get(position));
}
/**
* #param newsEvent
*/
public void startFullNewsEvent(NewsEvent ne) {
Intent intent = new Intent(this, FullNewsEvent.class);
intent.putExtra("ne", ne);
this.startActivity(intent);
finish();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ne.setListAdapter(new IconicAdapter());
}
};
public class IconicAdapter extends ArrayAdapter<NewsEvent> {
IconicAdapter() {
super(NewsEvents.this, R.layout.rownews, neList);
}
public View getView(int position, View convertView,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.rownews, parent, false);
TextView label=(TextView)row.findViewById(R.id.label);
ImageView image= (ImageView)row.findViewById(R.id.icon);
String body = neList.get(position).getBody();
body.replaceAll("\\<.*?>", "");
String title = neList.get(position).getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
neList.get(position).setInterested(true);
}
}
if(neList.get(position).isInterested() == true){
image.setImageResource(R.drawable.star);
}
label.setText(neList.get(position).getTitle());
return(row);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
populateMenu(menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return(applyMenuChoice(item) || super.onOptionsItemSelected(item));
}
//Creates our activity to menus
private void populateMenu(Menu menu) {
menu.add(Menu.NONE, ONE_ID, Menu.NONE, "Home");
}
private boolean applyMenuChoice(MenuItem item) {
switch (item.getItemId()) {
case ONE_ID: startHome(); return(true);
}
return(false);
}
public void startHome() {
Intent intent = new Intent(this, ECS.class);
this.startActivity(intent);
finish();
}
}
Race conditions, I'm making an HTTP Request and then handing it off to a handler, immediately following that I iterator through the array list, which at full speed is empty because the HTTP hasn't completed. In debugging it all slows down so the HTTP is complete and all works well.
Threads and Network Connections, a deadly combination.