// EGL functions public static boolean initEGL(int majorVersion, int minorVersion, int[] attribs) { try { if (SDLActivity.mEGLDisplay == null) { Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion); EGL10 egl = (EGL10) EGLContext.getEGL(); EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(dpy, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; if (!egl.eglChooseConfig(dpy, attribs, configs, 1, num_config) || num_config[0] == 0) { Log.e("SDL", "No EGL config available"); return false; } EGLConfig config = configs[0]; SDLActivity.mEGLDisplay = dpy; SDLActivity.mEGLConfig = config; SDLActivity.mGLMajor = majorVersion; SDLActivity.mGLMinor = minorVersion; } return SDLActivity.createEGLSurface(); } catch (Exception e) { Log.v("SDL", e + ""); for (StackTraceElement s : e.getStackTrace()) { Log.v("SDL", s.toString()); } return false; } }
public List parsePage(String pageCode) { List sections = new ArrayList(); List folders = new ArrayList(); List files = new ArrayList(); int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\""); int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\""); String usefulSection = ""; if (start != -1 && end != -1) { usefulSection = pageCode.substring(start, end); } else { debug("Could not parse page"); } try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(usefulSection)); Document doc = db.parse(is); NodeList divs = doc.getElementsByTagName("div"); for (int i = 0; i < divs.getLength(); i++) { Element div = (Element) divs.item(i); boolean isFolder = false; if (div.getAttribute("class").equals("filename")) { NodeList imgs = div.getElementsByTagName("img"); for (int j = 0; j < imgs.getLength(); j++) { Element img = (Element) imgs.item(j); if (img.getAttribute("class").indexOf("folder") > 0) { isFolder = true; } else { isFolder = false; // it's a file } } NodeList anchors = div.getElementsByTagName("a"); Element anchor = (Element) anchors.item(0); String attr = anchor.getAttribute("href"); String fileName = anchor.getAttribute("title"); String fileURL; if (isFolder && !attr.equals("#")) { folders.add(attr); folders.add(fileName); } else if (!isFolder && !attr.equals("#")) { // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be // sneaky here. fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1"; files.add(fileURL); files.add(fileName); } } } } catch (Exception e) { debug(e.toString()); } sections.add(files); sections.add(folders); return sections; }
public boolean sendEmail(String subject, String body, String address) { try { GmailSender sender = new GmailSender("*****@*****.**", "hackapart4ever"); sender.sendMail(subject, body, "*****@*****.**", address); return true; } catch (Exception e) { Log.d("SendMail", e.getMessage(), e); return false; } }
private boolean obbIsCorrupted(String f, String main_pack_md5) { try { InputStream fis = new FileInputStream(f); // Create MD5 Hash byte[] buffer = new byte[16384]; MessageDigest complete = MessageDigest.getInstance("MD5"); int numRead; do { numRead = fis.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); } } while (numRead != -1); fis.close(); byte[] messageDigest = complete.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String s = Integer.toHexString(0xFF & messageDigest[i]); if (s.length() == 1) { s = "0" + s; } hexString.append(s); } String md5str = hexString.toString(); // Log.d("GODOT","**PACK** - My MD5: "+hexString+" - APK md5: "+main_pack_md5); if (!md5str.equals(main_pack_md5)) { Log.d( "GODOT", "**PACK MD5 MISMATCH???** - MD5 Found: " + md5str + " " + Integer.toString(md5str.length()) + " - MD5 Expected: " + main_pack_md5 + " " + Integer.toString(main_pack_md5.length())); return true; } return false; } catch (Exception e) { e.printStackTrace(); Log.d("GODOT", "**PACK FAIL**"); return true; } }
public String getData(String url) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); String response = ""; try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(get, responseHandler); } catch (Exception e) { debug(e.toString()); } return response; }
private void sendExceptionMsg(int what, Exception e) { e.printStackTrace(); Message msg = Message.obtain(); msg.obj = e; msg.what = what; queryHandler.sendMessage(msg); }
private String[] getCommandLine() { InputStream is; try { is = getAssets().open("_cl_"); byte[] len = new byte[4]; int r = is.read(len); if (r < 4) { Log.d("XXX", "**ERROR** Wrong cmdline length.\n"); Log.d("GODOT", "**ERROR** Wrong cmdline length.\n"); return new String[0]; } int argc = ((int) (len[3] & 0xFF) << 24) | ((int) (len[2] & 0xFF) << 16) | ((int) (len[1] & 0xFF) << 8) | ((int) (len[0] & 0xFF)); String[] cmdline = new String[argc]; for (int i = 0; i < argc; i++) { r = is.read(len); if (r < 4) { Log.d("GODOT", "**ERROR** Wrong cmdline param lenght.\n"); return new String[0]; } int strlen = ((int) (len[3] & 0xFF) << 24) | ((int) (len[2] & 0xFF) << 16) | ((int) (len[1] & 0xFF) << 8) | ((int) (len[0] & 0xFF)); if (strlen > 65535) { Log.d("GODOT", "**ERROR** Wrong command len\n"); return new String[0]; } byte[] arg = new byte[strlen]; r = is.read(arg); if (r == strlen) { cmdline[i] = new String(arg, "UTF-8"); } } return cmdline; } catch (Exception e) { e.printStackTrace(); Log.d("GODOT", "**ERROR** Exception " + e.getClass().getName() + ":" + e.getMessage()); return new String[0]; } }
private static void saveLangue(String filepath, String data) { BufferedWriter writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(filepath)))); writer.write(data); } catch (Exception e) { Log.d("savelangue1", e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (Exception e) { Log.d("savelangue", e.getMessage()); } } } }
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.receiver); final Button cancelbtn = (Button) findViewById(R.id.ButtonCancel); // cancelbtn.setEnabled(false); cancelbtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // streamtask.cancel(true); finish(); } }); try { Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); if ((!(Intent.ACTION_SEND.equals(action))) || (type == null)) { throw new RuntimeException("Unknown intent action or type"); } if (!("text/plain".equals(type))) { throw new RuntimeException("Type is not text/plain"); } String extra = intent.getStringExtra(Intent.EXTRA_TEXT); if (extra == null) { throw new RuntimeException("Cannot get shared text"); } final DownloadStreamTask streamtask = new DownloadStreamTask(this); // Once created, a task is executed very simply: streamtask.execute(extra); } catch (Exception e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); } }
// EGL buffer flip public static void flipEGL() { try { EGL10 egl = (EGL10) EGLContext.getEGL(); egl.eglWaitNative(EGL10.EGL_CORE_NATIVE_ENGINE, null); // drawing here egl.eglWaitGL(); egl.eglSwapBuffers(SDLActivity.mEGLDisplay, SDLActivity.mEGLSurface); } catch (Exception e) { Log.v("SDL", "flipEGL(): " + e); for (StackTraceElement s : e.getStackTrace()) { Log.v("SDL", s.toString()); } } }
public void mOnClick(View v) { switch (v.getId()) { case R.id.test: String rootdir = Environment.getRootDirectory().getAbsolutePath(); String datadir = Environment.getDataDirectory().getAbsolutePath(); String cachedir = Environment.getDownloadCacheDirectory().getAbsolutePath(); mEdit.setText( String.format( "ext = %s\nroot=%s\ndata=%s\ncache=%s", mSdPath, rootdir, datadir, cachedir)); break; case R.id.save: File dir = new File(mSdPath + "/dir"); dir.mkdir(); File file = new File(mSdPath + "/dir/file.txt"); try { FileOutputStream fos = new FileOutputStream(file); String str = "This file exists in SDcard"; fos.write(str.getBytes()); fos.close(); mEdit.setText("write success"); } catch (FileNotFoundException e) { mEdit.setText("File Not Found." + e.getMessage()); } catch (SecurityException e) { mEdit.setText("Security Exception"); } catch (Exception e) { mEdit.setText(e.getMessage()); } break; case R.id.load: try { FileInputStream fis = new FileInputStream(mSdPath + "/dir/file.txt"); byte[] data = new byte[fis.available()]; while (fis.read(data) != -1) {; } fis.close(); mEdit.setText(new String(data)); } catch (FileNotFoundException e) { mEdit.setText("File Not Found"); } catch (Exception e) {; } break; } }
private static boolean checkLanguageChanged() { boolean langueChanged = false; // Log.d("langue", // _activ.getResources().getConfiguration().locale.getDisplayLanguage()); if (!new File(PathData.APP_DIRECTORY + "/langue.txt").exists()) { // pas de fichier // Log.d("langue0", "langue.txt does not exists"); boolean b = false; try { b = new File(PathData.APP_DIRECTORY + "/langue.txt").createNewFile(); } catch (Exception e) { e.printStackTrace(); } if (!b) { // Log.d("langue1", "fail create langue.txt"); } else { saveLangue( PathData.APP_DIRECTORY + "/langue.txt", AppData.currentContext.getResources().getConfiguration().locale.getDisplayLanguage()); } } else { // fichiers deja la, on va voir comment ca se passe // Log.d("langue2", "langue.txt exist"); String lg = getLangueSave(PathData.APP_DIRECTORY + "/langue.txt"); // Log.d("langue2.5", "lg = "+lg); if (!lg.equals( AppData.currentContext.getResources().getConfiguration().locale.getDisplayLanguage())) { // Log.d("langue3", "langue changed"); saveLangue( PathData.APP_DIRECTORY + "/langue.txt", AppData.currentContext.getResources().getConfiguration().locale.getDisplayLanguage()); langueChanged = true; } else { // Log.d("langue4", "langue doesn't changed"); langueChanged = false; } } return langueChanged; }
public void downloadFile(String url, String savePath, String fileName) { try { URL theURL = new URL(url); InputStream input = theURL.openStream(); OutputStream output = new FileOutputStream(new File(savePath, fileName)); try { byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { output.write(buffer, 0, bytesRead); } } catch (Exception e) { debug(e.toString()); } finally { output.close(); } } catch (Exception e) { debug(e.toString()); } }
/** This method is called by SDL using JNI. */ public InputStream openAPKExtensionInputStream(String fileName) throws IOException { // Get a ZipResourceFile representing a merger of both the main and patch files if (expansionFile == null) { Integer mainVersion = Integer.valueOf(nativeGetHint("SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION")); Integer patchVersion = Integer.valueOf(nativeGetHint("SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION")); try { // To avoid direct dependency on Google APK extension library that is // not a part of Android SDK we access it using reflection expansionFile = Class.forName("com.android.vending.expansion.zipfile.APKExpansionSupport") .getMethod("getAPKExpansionZipFile", Context.class, int.class, int.class) .invoke(null, this, mainVersion, patchVersion); expansionFileMethod = expansionFile.getClass().getMethod("getInputStream", String.class); } catch (Exception ex) { ex.printStackTrace(); expansionFile = null; expansionFileMethod = null; } } // Get an input stream for a known file inside the expansion file ZIPs InputStream fileStream; try { fileStream = (InputStream) expansionFileMethod.invoke(expansionFile, fileName); } catch (Exception ex) { ex.printStackTrace(); fileStream = null; } if (fileStream == null) { throw new IOException(); } return fileStream; }
public String getFolderName(String pageCode) { String usefulSection = pageCode.substring( pageCode.indexOf("<h3 id=\"breadcrumb\">"), pageCode.indexOf("<div id=\"list-view\" class=\"view\"")); String folderName; try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(usefulSection)); Document doc = db.parse(is); NodeList divs = doc.getElementsByTagName("h3"); for (int i = 0; i < divs.getLength(); i++) { Element div = (Element) divs.item(i); String a = div.getTextContent(); folderName = a.substring(a.indexOf("/>") + 2).trim(); return folderName; } } catch (Exception e) { debug(e.toString()); } return "Error!"; }
@Override public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) { Log.d(TAG, "onEditorAction: actionId: " + actionId + ", keyEvent: " + keyEvent); if ((actionId == EditorInfo.IME_ACTION_DONE) || ((keyEvent != null) && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER))) { Log.d(TAG, "onEditorAction: IME_ACTION_DONE || KEYCODE_ENTER"); String input = textView.getText().toString().trim(); if (input.length() > 0) { String result = ""; try { result += calculator.calculate(input); } catch (Exception e) { result = "no result (" + e.getMessage() + ")"; } if (listAdapter.getCount() > 0) { listAdapter.add(""); } listAdapter.add(input + " ="); if (input.indexOf("@") > -1) { listAdapter.add(calculator.getEquation() + " ="); } listAdapter.add(result); listAdapter.notifyDataSetChanged(); inputView.endBatchEdit(); inputView.setText(""); hideKeyboard(); } } return false; }
@Override public void surfaceCreated(SurfaceHolder holder) { if (mediaRecorder == null) { try { Log.d(TAG, "Opening camera"); camera = Camera.open(); Log.d(TAG, "Camera opened"); Camera.Parameters parameters = camera.getParameters(); setRequestedOrientation(90); camera.setDisplayOrientation(90); camera.setParameters(parameters); Log.d(TAG, "Set parameters"); camera.setPreviewDisplay(holder); // set SurfaceHolder as destination for frames Log.d(TAG, "Set preview display"); camera.startPreview(); Button takePhotoButton = (Button) findViewById(R.id.takePhotoButton); takePhotoButton.setVisibility(View.VISIBLE); Log.d(TAG, "Button visible"); Log.d(TAG, "Preview started"); } catch (Exception e) { Log.d(TAG, e.getMessage()); } } }
private static String getLangueSave(String path) { String monText = ""; BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)))); String line; StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line); } monText = buffer.toString(); } catch (Exception e) { Log.d("getlangue1", e.getMessage()); } finally { if (input != null) { try { input.close(); } catch (Exception e2) { Log.d("getlangue2", e2.getMessage()); } } } return monText; }
private static void copierFichiers2(final boolean copyFiles, final boolean langueChanged) { if (copyFiles || langueChanged) { afficherProgress(); // attendreAffichageProgress(); } try { if (copyFiles) CopyFiles(); if (copyFiles || langueChanged) { CollectionManager.ImportArchive(AppData.current_activity, mProgressDialog); } AppData.current_activity.runOnUiThread( new Runnable() { public void run() { fermerProgress(); delegate.onBootstrapInitialised(); } }); } catch (Exception e) { e.printStackTrace(); } }
private void doRetryableAlert(Exception e, String msg) { AlertDialog.Builder dialog = new AlertDialog.Builder(SelectAccount.this); dialog.setTitle(msg); String dispMsg = msg + "\n\n" + e.getMessage(); dialog.setMessage(dispMsg); dialog.setPositiveButton( "Retry", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { requestAccountList(); } }); dialog.setNegativeButton("Cancel", emptyClickListener); AlertDialog dlg = dialog.create(); dlg.show(); }
// EGL functions public static boolean initEGL(int majorVersion, int minorVersion, int[] attribs) { try { EGL10 egl = (EGL10) EGLContext.getEGL(); if (SDLActivity.mEGLDisplay == null) { SDLActivity.mEGLDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(SDLActivity.mEGLDisplay, version); } if (SDLActivity.mEGLDisplay != null && SDLActivity.mEGLContext == EGL10.EGL_NO_CONTEXT) { // No current GL context exists, we will create a new one. Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion); EGLConfig[] configs = new EGLConfig[128]; int[] num_config = new int[1]; if (!egl.eglChooseConfig(SDLActivity.mEGLDisplay, attribs, configs, 1, num_config) || num_config[0] == 0) { Log.e("SDL", "No EGL config available"); return false; } EGLConfig config = null; int bestdiff = -1, bitdiff; int[] value = new int[1]; // eglChooseConfig returns a number of configurations that match or exceed the requested // attribs. // From those, we select the one that matches our requirements more closely Log.v("SDL", "Got " + num_config[0] + " valid modes from egl"); for (int i = 0; i < num_config[0]; i++) { bitdiff = 0; // Go through some of the attributes and compute the bit difference between what we want // and what we get. for (int j = 0; ; j += 2) { if (attribs[j] == EGL10.EGL_NONE) break; if (attribs[j + 1] != EGL10.EGL_DONT_CARE && (attribs[j] == EGL10.EGL_RED_SIZE || attribs[j] == EGL10.EGL_GREEN_SIZE || attribs[j] == EGL10.EGL_BLUE_SIZE || attribs[j] == EGL10.EGL_ALPHA_SIZE || attribs[j] == EGL10.EGL_DEPTH_SIZE || attribs[j] == EGL10.EGL_STENCIL_SIZE)) { egl.eglGetConfigAttrib(SDLActivity.mEGLDisplay, configs[i], attribs[j], value); bitdiff += value[0] - attribs[j + 1]; // value is always >= attrib } } if (bitdiff < bestdiff || bestdiff == -1) { config = configs[i]; bestdiff = bitdiff; } if (bitdiff == 0) break; // we found an exact match! } Log.d("SDL", "Selected mode with a total bit difference of " + bestdiff); SDLActivity.mEGLConfig = config; SDLActivity.mGLMajor = majorVersion; SDLActivity.mGLMinor = minorVersion; } return SDLActivity.createEGLSurface(); } catch (Exception e) { Log.v("SDL", e + ""); for (StackTraceElement s : e.getStackTrace()) { Log.v("SDL", s.toString()); } return false; } }
/* Called when the activity is first created */ @Override public void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.give_ride_content); /* Creating DBAdapter instance */ gr_datasource = new DBAdapter(this); /* Get email ID from previous activity to maintain session */ Bundle extras = getIntent().getExtras(); if (extras != null) { str_usrid = extras.getString("usrid"); } buttonSubmit = (Button) findViewById(R.id.btn_gr_submit); buttonCancel = (Button) findViewById(R.id.btn_gr_cancel); /* Get radius and cost */ et_radius = (EditText) this.findViewById(R.id.txt_gr_radius); et_cost = (EditText) this.findViewById(R.id.txt_gr_cost); /* Adding PlacesAutoComplete adapter to the FROM autocomplete field */ gr_frm_acView = (AutoCompleteTextView) findViewById(R.id.txt_gr_from); gr_frm_adapter = new PlacesAutoCompleteAdapter(this, R.layout.frm_item_list); gr_frm_acView.setAdapter(gr_frm_adapter); gr_frm_acView.setOnItemClickListener(this); /* Adding PlacesAutoComplete adapter to the TO autocomplete field */ gr_to_acView = (AutoCompleteTextView) findViewById(R.id.txt_gr_to); gr_to_adapter = new PlacesAutoCompleteAdapter(this, R.layout.to_item_list); gr_to_acView.setAdapter(gr_to_adapter); gr_to_acView.setOnItemClickListener(this); /* Adding array adapter to spinner control for seats */ sp_seats = (Spinner) findViewById(R.id.spn_gr_seats); ArrayAdapter<String> seats_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, str_seats); sp_seats.setAdapter(seats_adapter); /* Prompt a dialog box upon Date button click */ datePicker = (Button) findViewById(R.id.btn_gr_datepicker); datePicker.setText(dateFormatter.format(dateTime.getTime())); datePicker.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { showDialog(DIALOG_DATE); } }); /* Prompt a dialog box upon Time button click */ timePicker = (Button) findViewById(R.id.btn_gr_timepicker); timePicker.setText(timeFormatter.format(dateTime.getTime())); timePicker.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { showDialog(DIALOG_TIME); } }); buttonSubmit.setOnClickListener(buttonSubmitOnClickListener); buttonCancel.setOnClickListener(buttonCancelOnClickListener); sp_seats.setOnItemSelectedListener(spinnerseatsOnItemSelectedListener); } catch (Exception e) { Log.e("Places AutoComplete Activity OnCreate:", e.toString()); } }
@Override public void onClick(View arg0) { try { /* Open Database */ gr_datasource.open(); /* Get from and to address from autocomplete fields */ gr_frm_addr = gr_frm_acView.getText().toString(); gr_to_addr = gr_to_acView.getText().toString(); flag = 0; /* Checking if FROM and TO address is empty */ if (gr_frm_addr.length() == 0) { gr_frm_acView.setError("Enter from address"); flag = 1; } else if (gr_to_addr.length() == 0) { gr_to_acView.setError("Enter to address"); flag = 1; } /* Radius validation */ String str_radius = et_radius.getText().toString(); if (str_radius.length() == 0) { et_radius.setError("Enter valid radius"); flag = 1; } else { rad_value = Integer.valueOf(et_radius.getText().toString()); if (rad_value < 0 || rad_value > 20) { et_radius.setError("Limit 20 miles"); flag = 1; } } /* Cost Validation */ String str_cost = et_cost.getText().toString(); if (str_cost.length() == 0) { et_cost.setError("Enter valid cost"); flag = 1; } else { cost_value = Float.valueOf(et_cost.getText().toString()); if (cost_value < 0 || cost_value > 1000) { et_cost.setError("Limit 1000 dollars"); flag = 1; } } if (flag == 0) { /* Function call to calculate lattitudes and longitudes for FROM address */ jsonObject_main_frm = getLocationInfo(gr_frm_addr); frm_lattitude = getLattitude(jsonObject_main_frm); frm_longitude = getLongitude(jsonObject_main_frm); /* Function call to calculate lattitudes and longitudes for TO address */ jsonObject_main_to = getLocationInfo(gr_to_addr); to_lattitude = getLattitude(jsonObject_main_to); to_longitude = getLongitude(jsonObject_main_to); str_date = datePicker.getText().toString(); /* Convert time to milliseconds */ time = dateTime.getTimeInMillis(); /* Insert into RIDEDETAILS table */ long id; id = gr_datasource.insertridedetails( str_usrid, gr_frm_addr, gr_to_addr, rad_value, str_date, time, selected_seat, cost_value, frm_lattitude, frm_longitude, to_lattitude, to_longitude); /* Close database object */ gr_datasource.close(); /* On inserting Ride Details redirect to choose ride screen or exit */ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(PlacesAutoCompleteActivity.this); alertDialogBuilder.setTitle("Ride 'n Divide"); alertDialogBuilder .setMessage("Thank you, for giving a ride! Do you want to check other rides?") .setCancelable(false) .setPositiveButton( "Check Rides", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent reselect = new Intent(PlacesAutoCompleteActivity.this, ChooseRideActivity.class); reselect.putExtra("usrid", str_usrid); startActivity(reselect); } }) .setNegativeButton( "Exit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); PlacesAutoCompleteActivity.this.finish(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } } catch (Exception e) { Log.e("Places AutoComplete Activity buttonsubmit:", e.toString()); } }
@Override protected void onCreate(Bundle icicle) { Log.d("GODOT", "** GODOT ACTIVITY CREATED HERE ***\n"); super.onCreate(icicle); _self = this; Window window = getWindow(); window.addFlags( WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // check for apk expansion API if (true) { boolean md5mismatch = false; command_line = getCommandLine(); boolean use_apk_expansion = false; String main_pack_md5 = null; String main_pack_key = null; List<String> new_args = new LinkedList<String>(); for (int i = 0; i < command_line.length; i++) { boolean has_extra = i < command_line.length - 1; if (command_line[i].equals("-use_apk_expansion")) { use_apk_expansion = true; } else if (has_extra && command_line[i].equals("-apk_expansion_md5")) { main_pack_md5 = command_line[i + 1]; i++; } else if (has_extra && command_line[i].equals("-apk_expansion_key")) { main_pack_key = command_line[i + 1]; SharedPreferences prefs = getSharedPreferences("app_data_keys", MODE_PRIVATE); Editor editor = prefs.edit(); editor.putString("store_public_key", main_pack_key); editor.commit(); i++; } else if (command_line[i].trim().length() != 0) { new_args.add(command_line[i]); } } if (new_args.isEmpty()) { command_line = null; } else { command_line = new_args.toArray(new String[new_args.size()]); } if (use_apk_expansion && main_pack_md5 != null && main_pack_key != null) { // check that environment is ok! if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Log.d("GODOT", "**ERROR! No media mounted!"); // show popup and die } // Build the full path to the app's expansion files try { expansion_pack_path = Environment.getExternalStorageDirectory().toString() + "/Android/obb/" + this.getPackageName(); expansion_pack_path += "/" + "main." + getPackageManager().getPackageInfo(getPackageName(), 0).versionCode + "." + this.getPackageName() + ".obb"; } catch (Exception e) { e.printStackTrace(); } File f = new File(expansion_pack_path); boolean pack_valid = true; Log.d("GODOT", "**PACK** - Path " + expansion_pack_path); if (!f.exists()) { pack_valid = false; Log.d("GODOT", "**PACK** - File does not exist"); } else if (obbIsCorrupted(expansion_pack_path, main_pack_md5)) { Log.d("GODOT", "**PACK** - Expansion pack (obb) is corrupted"); pack_valid = false; try { f.delete(); } catch (Exception e) { Log.d("GODOT", "**PACK** - Error deleting corrupted expansion pack (obb)"); } } if (!pack_valid) { Log.d("GODOT", "Pack Invalid, try re-downloading."); Intent notifierIntent = new Intent(this, this.getClass()); notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT); int startResult; try { Log.d("GODOT", "INITIALIZING DOWNLOAD"); startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired( getApplicationContext(), pendingIntent, GodotDownloaderService.class); Log.d("GODOT", "DOWNLOAD SERVICE FINISHED:" + startResult); if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) { Log.d("GODOT", "DOWNLOAD REQUIRED"); // This is where you do set up to display the download // progress (next step) mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, GodotDownloaderService.class); setContentView(com.godot.game.R.layout.downloading_expansion); mPB = (ProgressBar) findViewById(com.godot.game.R.id.progressBar); mStatusText = (TextView) findViewById(com.godot.game.R.id.statusText); mProgressFraction = (TextView) findViewById(com.godot.game.R.id.progressAsFraction); mProgressPercent = (TextView) findViewById(com.godot.game.R.id.progressAsPercentage); mAverageSpeed = (TextView) findViewById(com.godot.game.R.id.progressAverageSpeed); mTimeRemaining = (TextView) findViewById(com.godot.game.R.id.progressTimeRemaining); mDashboard = findViewById(com.godot.game.R.id.downloaderDashboard); mCellMessage = findViewById(com.godot.game.R.id.approveCellular); mPauseButton = (Button) findViewById(com.godot.game.R.id.pauseButton); mWiFiSettingsButton = (Button) findViewById(com.godot.game.R.id.wifiSettingsButton); return; } else { Log.d("GODOT", "NO DOWNLOAD REQUIRED"); } } catch (NameNotFoundException e) { // TODO Auto-generated catch block Log.d("GODOT", "Error downloading expansion package:" + e.getMessage()); } } } } initializeGodot(); // instanceSingleton( new GodotFacebook(this) ); }
// Setup @Override protected void onCreate(Bundle savedInstanceState) { Log.v("SDL", "Device: " + android.os.Build.DEVICE); Log.v("SDL", "Model: " + android.os.Build.MODEL); Log.v("SDL", "onCreate():" + mSingleton); super.onCreate(savedInstanceState); SDLActivity.initialize(); // So we can call stuff from static callbacks mSingleton = this; // Load shared libraries String errorMsgBrokenLib = ""; try { loadLibraries(); } catch (UnsatisfiedLinkError e) { System.err.println(e.getMessage()); mBrokenLibraries = true; errorMsgBrokenLib = e.getMessage(); } catch (Exception e) { System.err.println(e.getMessage()); mBrokenLibraries = true; errorMsgBrokenLib = e.getMessage(); } if (mBrokenLibraries) { AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this); dlgAlert.setMessage( "An error occurred while trying to start the application. Please try again and/or reinstall." + System.getProperty("line.separator") + System.getProperty("line.separator") + "Error: " + errorMsgBrokenLib); dlgAlert.setTitle("SDL Error"); dlgAlert.setPositiveButton( "Exit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // if this button is clicked, close current activity SDLActivity.mSingleton.finish(); } }); dlgAlert.setCancelable(false); dlgAlert.create().show(); return; } // Set up the surface mSurface = new SDLSurface(getApplication()); if (Build.VERSION.SDK_INT >= 12) { mJoystickHandler = new SDLJoystickHandler_API12(); } else { mJoystickHandler = new SDLJoystickHandler(); } mLayout = new AbsoluteLayout(this); mLayout.addView(mSurface); setContentView(mLayout); }
// EGL functions public boolean initEGL(int majorVersion, int minorVersion) { Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion); try { EGL10 egl = (EGL10) EGLContext.getEGL(); EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(dpy, version); int EGL_OPENGL_ES_BIT = 1; int EGL_OPENGL_ES2_BIT = 4; int renderableType = 0; if (majorVersion == 2) { renderableType = EGL_OPENGL_ES2_BIT; } else if (majorVersion == 1) { renderableType = EGL_OPENGL_ES_BIT; } int[] configSpec = { // EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; if (!egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config) || num_config[0] == 0) { Log.e("SDL", "No EGL config available"); return false; } EGLConfig config = configs[0]; EGLContext ctx = egl.eglCreateContext(dpy, config, EGL10.EGL_NO_CONTEXT, null); if (ctx == EGL10.EGL_NO_CONTEXT) { Log.e("SDL", "Couldn't create context"); return false; } EGLSurface surface = egl.eglCreateWindowSurface(dpy, config, this, null); if (surface == EGL10.EGL_NO_SURFACE) { Log.e("SDL", "Couldn't create surface"); return false; } if (!egl.eglMakeCurrent(dpy, surface, surface, ctx)) { Log.e("SDL", "Couldn't make context current"); return false; } mEGLContext = ctx; mEGLDisplay = dpy; mEGLSurface = surface; } catch (Exception e) { Log.v("SDL", e + ""); for (StackTraceElement s : e.getStackTrace()) { Log.v("SDL", s.toString()); } } return true; }
@Override public void onClick(View v) { if (v.getId() == R.id.takePhotoButton) { camera.takePicture(shutterCallback, rawCallback, jpegCallback); Button takePhotoButton = (Button) findViewById(R.id.takePhotoButton); takePhotoButton.setVisibility(View.INVISIBLE); } if (v.getId() == R.id.cameraTryAgainButton) { Button saveButton = (Button) findViewById(R.id.savePhotoButton); saveButton.setVisibility(View.INVISIBLE); Button cameraTryAgainButton = (Button) findViewById(R.id.cameraTryAgainButton); cameraTryAgainButton.setVisibility(View.INVISIBLE); Button takePhotoButton = (Button) findViewById(R.id.takePhotoButton); takePhotoButton.setVisibility(View.VISIBLE); camera.startPreview(); /*canvas = holder.lockCanvas(); Picture picture = new Picture(); picture.draw(canvas); canvas.drawPicture(picture); holder.unlockCanvasAndPost(canvas);*/ } if (v.getId() == R.id.savePhotoButton) { filename = "picture" + ic.numberOfPictures + ".jpg"; // STEP ONE : Set filename ic.numberOfPictures++; file = path + filename; Calendar calendar = new GregorianCalendar(); // STEP TWO : Get Calendar object int month = calendar.get(calendar.MONTH); // and time/date int day = calendar.get(calendar.DAY_OF_MONTH); String time = calendar.getTime().toString().substring(11, 19); int hour = Integer.valueOf(time.substring(0, 2)); if (hour > 12) { int oldHour = hour; // STEP THREE: Format time hour = hour - 12; String oldS = Integer.toString(oldHour); String hourS = Integer.toString(hour); if (hourS.length() == 1) hourS = "0" + hourS; time = time.substring(2); time = hourS + time; time.replaceFirst(oldS, hourS); isAM = false; } if (isAM) time = time + " AM " + " --- Picture"; else time = time + " PM " + " --- Picture"; String year = new Integer(calendar.get(calendar.YEAR)).toString(); database .get(year) .get(months[month]) .get(days[day - 1]) .put(time, file); // STEP FOUR: Pull day out of Toast.makeText(this, "Picture saved to: " + file, Toast.LENGTH_LONG) .show(); // the database Button saveButton = (Button) findViewById(R.id.savePhotoButton); saveButton.setVisibility(View.INVISIBLE); Button takePhotoButton = (Button) findViewById(R.id.takePhotoButton); takePhotoButton.setVisibility(View.INVISIBLE); try { FileOutputStream camFOS = new FileOutputStream(file); // STEP FIVE: Save picture to MindBook directory camFOS.write(picture); camFOS.close(); } catch (FileNotFoundException fnfe) { Log.d("CAMERA", fnfe.getMessage()); } catch (IOException ioe) { Log.d("CAMERA", ioe.getMessage()); } try { ObjectOutputStream dataOOS = new ObjectOutputStream(new FileOutputStream(path + "database.ser")); dataOOS.writeObject(database); dataOOS.close(); ObjectOutputStream counterOOS = new ObjectOutputStream(new FileOutputStream(path + "counter.ser")); counterOOS.writeObject(ic); counterOOS.close(); } catch (Exception e) { Log.d("CAMERA", e.getMessage()); } } }
protected Boolean doInBackground(ArrayList... params) { download_photos.this.runOnUiThread( new Runnable() { public void run() { mtext.setText( getText(R.string.download_textview_message_1) + " " + path.toString() + ". "); } }); if (resume_file.exists()) { initial_value = readProgress()[0]; } else { initial_value = 1; } for (int i = initial_value - 1; i < links.size(); i++) { // asynctask expects more than one ArrayList<String> item, but we are sending only one, // which is params[0] Uri imageuri = Uri.parse(params[0].get(i).toString()); URL imageurl = null; HttpURLConnection connection = null; total_files_to_download = links.size(); completed_downloads = i + 1; try { imageurl = new URL(params[0].get(i).toString()); connection = (HttpURLConnection) imageurl.openConnection(); connection.connect(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // extracts the real file name of the photo from url path_segments = imageuri.getPathSegments(); int total_segments = path_segments.size(); file_name = path_segments.get(total_segments - 1); path.mkdirs(); // if(i==0) // first_image = path.toString() + "/" + file_name; InputStream input; OutputStream output; try { input = new BufferedInputStream(imageurl.openStream()); fully_qualified_file_name = new File(path, file_name); output = new BufferedOutputStream(new FileOutputStream(fully_qualified_file_name)); byte data[] = new byte[1024]; int count; while ((count = input.read(data)) != -1) { output.write(data, 0, count); } output.flush(); output.close(); input.close(); connection.disconnect(); new folder_scanner(getApplicationContext(), fully_qualified_file_name); publishProgress(completed_downloads, total_files_to_download); if (this.isCancelled()) { writeProgress(completed_downloads, total_files_to_download); break; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // creates required folders and subfolders if they do not exist already // boolean success = path.mkdirs(); // makes request to download photos // DownloadManager.Request request = new DownloadManager.Request(imageuri); // set path for downloads // request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,sub_path); // request.setDescription("Downloaded using Facebook Album Downloader"); // DownloadManager dm = (DownloadManager)getSystemService(DOWNLOAD_SERVICE); // download is enqueue in download list. it returns unique id for each download // download_id = dm.enqueue(request); } // returns the unique id. we are not using this id return true; }
@Override protected String[] doInBackground(String... parms) { String[] resultarr = new String[1]; String intentstr = parms[0]; // int count = urls.length; // long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += // Downloader.downloadFile(urls[i]); // publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called // if (isCancelled()) // break; try { // Connect to API and authenticate publishProgress("Connecting and authenticating API session..."); ApiWrapper wrapper; // wrapper = Api.wrapper; wrapper = new ApiWrapper(Api.mClientID, Api.mClientSecret, null, null); wrapper.login("un1tz3r0", "Farscap3"); publishProgress("Resolving url..."); String resolvedurl = resolveURL(wrapper, intentstr); publishProgress("Getting metadata..."); HttpResponse resp = wrapper.get(Request.to(resolvedurl)); JSONObject jso = Http.getJSON(resp); // resultstr = jso.toString(); if (jso.getString("kind").equals("track")) { if (jso.getBoolean("downloadable")) { publishProgress("Getting download redirect URL..."); String dlrurl = wrapper .getURI( Request.to(jso.getString("download_url")).add("allow_redirect", false), false, false) .toString(); HttpResponse dlrresp = wrapper.get(Request.to(dlrurl)); String dlstr = dlrurl; if (dlrresp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { Header dlloch = dlrresp.getFirstHeader("location"); if ((dlloch == null) || (dlloch.getValue() == null)) throw new RuntimeException("Download url HEAD response has no location header"); dlstr = wrapper.getURI(Request.to(dlloch.getValue()), false, false).toString(); } else if (dlrresp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { dlstr = dlrurl; } else { throw new RuntimeException( "Download url HEAD response has wrong status (" + String.valueOf(dlrresp.getStatusLine().getStatusCode()) + " " + dlrresp.getStatusLine().getReasonPhrase() + ")"); } // String dlstr = Request.to( dlloch.getValue() ).add("CLIENT_ID", // Api.mClientID).toString(); // if(dlresp2.getStatusLine().getStatusCode() != // HttpStatus.SC_MOVED_TEMPORARILY) // throw new RuntimeException("Download redirect url HEAD response has // wrong status: " + dlresp2.getStatusLine().toString()); // Header dlloc2 = dlresp2.getFirstHeader("location"); // if((dlloc2 == null) || (dlloc2.getValue() == null)) // throw new RuntimeException("Download redirect url HEAD response has no // location header"); // resultarr = new String[2]; resultarr[1] = jso.getString("title").replaceAll("[^A-Za-z0-9 -]*", "") + "." + jso.getString("original_format"); resultarr[0] = dlstr; } else { Stream st = wrapper.resolveStreamUrl(jso.getString("stream_url"), true); resultarr = new String[2]; resultarr[1] = jso.getString("title").replaceAll("[^A-Za-z0-9 -]*", "").concat(".mp3"); resultarr[0] = st.streamUrl; } } } catch (JSONException e) { resultarr = new String[1]; resultarr[0] = e.toString(); } catch (IOException e) { resultarr = new String[1]; resultarr[0] = e.toString(); } catch (Exception e) { resultarr = new String[1]; resultarr[0] = e.toString(); } return resultarr; }