Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.cubika.iPoema;
- import java.io.*;
- import java.net.MalformedURLException;
- import java.net.URI;
- import java.net.URISyntaxException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.*;
- import android.annotation.TargetApi;
- import android.app.AlertDialog;
- import android.app.ProgressDialog;
- import android.content.*;
- import android.content.pm.PackageInfo;
- import android.net.*;
- import android.content.pm.PackageManager;
- import android.os.*;
- import android.support.v7.app.*;
- import android.support.v4.view.*;
- import android.support.v4.app.*;
- import android.view.*;
- import android.widget.*;
- import org.jdom2.*;
- import org.jdom2.input.*;
- import org.apache.http.util.ByteArrayBuffer;
- @TargetApi(Build.VERSION_CODES.CUPCAKE)
- public class iPoema extends ActionBarActivity {
- /**
- * The {@link android.support.v4.view.PagerAdapter} that will provide
- * fragments for each of the sections. We use a
- * {@link FragmentPagerAdapter} derivative, which will keep every
- * loaded fragment in memory. If this becomes too memory intensive, it
- * may be best to switch to a
- * {@link android.support.v4.app.FragmentStatePagerAdapter}.
- */
- private static String PATH = Environment.getExternalStorageDirectory()+"/Download/";
- private PackageInfo Pi = null;
- int lenghtOfFile = 0;
- int progress = 0;
- String titulo[] = new String[20];
- String texto[] = new String[20];
- String autor[] = new String[20];
- SectionsPagerAdapter mSectionsPagerAdapter;
- /**
- * The {@link ViewPager} that will host the section contents.
- */
- ViewPager mViewPager;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_i_poema);
- try {
- Pi = getPackageManager().getPackageInfo(getPackageName(), 0);
- } catch (PackageManager.NameNotFoundException e) { }
- File arquivo = new File(PATH + "iPoema.xml");
- if (arquivo.exists() == true) {
- readXML();
- } else {
- refresh();
- }
- // Create the adapter that will return a fragment for each of the three
- // primary sections of the activity.
- mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
- // Set up the ViewPager with the sections adapter.
- mViewPager = (ViewPager) findViewById(R.id.pager);
- mViewPager.setAdapter(mSectionsPagerAdapter);
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.i_poema, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- if (id == R.id.action_refresh) {
- refresh();
- return true;
- } else if (id == R.id.action_settings) {
- Intent intent = new Intent(this, Settings.class);
- startActivity(intent);
- return true;
- } else if (id == R.id.action_update) {
- loadAtualizacao();
- return true;
- } else {
- return super.onOptionsItemSelected(item);
- }
- }
- public void readXML() {
- final ProgressDialog d = new ProgressDialog(this);
- d.setMessage("Recebendo os dados de XML...");
- d.setTitle("Lendo arquivo");
- d.setIndeterminate(false);
- d.setProgress(0);
- d.setMax(100);
- d.setProgressStyle(ProgressDialog.STYLE_SPINNER);
- d.setCancelable(true);
- d.show();
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- Thread.sleep(5000);
- lerXML.execute();
- } catch (Exception e) {
- showMessage(e.getClass().getName(), "Não foi possível receber os dados do XML.");
- }
- d.dismiss();
- }
- }).start();
- }
- public String getTitulo(int i) {
- return titulo[i];
- }
- public String getTexto(int i) throws UnsupportedEncodingException {
- String text = null;
- text = texto[i];
- text = text.replaceAll("</p>", "\n");
- text = text.replaceAll("<p>", "");
- text = text.replaceAll("<br/>", "\n");
- text = text.replaceAll("’", "'");
- text = text.replaceAll("“", "\"");
- text = text.replaceAll("”", "\"");
- return text;
- }
- public String getAutor(int i) {
- return autor[i];
- }
- public void showMessage(String title, String text) {
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setCancelable(false);
- builder.setTitle(title);
- builder.setMessage(text);
- builder.setIcon(R.drawable.ic_launcher);
- builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.cancel();
- }
- });
- AlertDialog alert = builder.create();
- alert.show();
- }
- public void loadAtualizacao() {
- final ProgressDialog d = new ProgressDialog(this);
- d.setMessage("Checando versão de iPoema...");
- d.setTitle("Aguarde");
- d.setIndeterminate(false);
- d.setProgress(0);
- d.setMax(100);
- d.setProgressStyle(ProgressDialog.STYLE_SPINNER);
- d.setCancelable(true);
- d.show();
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- Thread.sleep(5000);
- atualizaApp.execute();
- } catch (Exception e) {
- showMessage(e.getClass().getName(), "Não foi possível receber os dados de versão.");
- }
- d.dismiss();
- }
- }).start();
- }
- public void refresh() {
- final ProgressDialog d = new ProgressDialog(this);
- d.setMessage("Recebendo dados de Feed");
- d.setTitle("Atualizando");
- d.setIndeterminate(false);
- d.setProgress(0);
- d.setMax(100);
- d.setProgressStyle(ProgressDialog.STYLE_SPINNER);
- d.setCancelable(true);
- d.show();
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- Thread.sleep(3000);
- getFeed.execute();
- } catch (Exception e) {
- showMessage(e.getClass().getName(), "Não foi possível receber os dados de Feed.");
- }
- d.dismiss();
- }
- }).start();
- }
- AsyncTask<Void, Void, String> getFeed = new AsyncTask<Void, Void, String>(){
- @Override
- protected String doInBackground(Void... params) {
- String retorno = "não";
- try {
- // Baixar Feed
- URL url = new URL("http://www.ipoema.tumblr.com/rss");
- File file = new File(PATH + "iPoema.xml");
- file.delete();
- URLConnection ucon = url.openConnection();
- InputStream is = ucon.getInputStream();
- BufferedInputStream bis = new BufferedInputStream(is);
- ByteArrayBuffer baf = new ByteArrayBuffer(50);
- lenghtOfFile = ucon.getContentLength();
- int current = 0;
- while ((current = bis.read()) != -1) {
- baf.append((byte) current);
- progress = current;
- }
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(baf.toByteArray());
- fos.close();
- retorno = "sim";
- } catch (IOException e) {
- showMessage(e.getClass().getName(), "Erro ao tentar realizar o download do arquivo.");
- }
- return retorno;
- }
- @Override
- protected void onPostExecute(String s) {
- super.onPostExecute(s);
- if (s.equals("sim")) {
- try {
- lerXML.execute();
- } catch (Exception e) {
- showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do arquivo.");
- }
- }
- }
- };
- AsyncTask<Void, Void, String> lerXML = new AsyncTask<Void, Void, String>(){
- @Override
- protected String doInBackground(Void... params) {
- String state = "erro";
- try {
- // Ler XML
- showMessage("iPoema", "Arquivo lido com sucesso");
- File f = new File(PATH + "iPoema.xml");
- SAXBuilder sb = new SAXBuilder();
- Document d = sb.build(f);
- Element mural = d.getRootElement();
- List<Element> elements = mural.getChildren("channel");
- Iterator<Element> i = elements.iterator();
- int x = 0;
- //for (int x = 0; x <= elements.size(); x++) {
- while (i.hasNext()) {
- //Element node = (Element) elements.get(x);
- Element node = (Element) i.next();
- Element item = node.getChild("item");
- titulo[x] = item.getChildText("title");
- texto[x] = item.getChildText("description");
- autor[x] = item.getChildText("category");
- x++;
- }
- state = "ok";
- } catch (JDOMException e) {
- showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do XML.");
- } catch (IOException e) {
- showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do XML.");
- }
- return state;
- }
- @Override
- protected void onPostExecute(String s) {
- super.onPostExecute(s);
- if (s.equals("ok")) {
- try {
- // Títulos
- TextView titulo1 = (TextView) findViewById(R.id.titulo1);
- TextView titulo2 = (TextView) findViewById(R.id.titulo2);
- TextView titulo3 = (TextView) findViewById(R.id.titulo3);
- TextView titulo4 = (TextView) findViewById(R.id.titulo4);
- // Textos
- TextView texto1 = (TextView) findViewById(R.id.texto1);
- TextView texto2 = (TextView) findViewById(R.id.texto2);
- TextView texto3 = (TextView) findViewById(R.id.texto3);
- TextView texto4 = (TextView) findViewById(R.id.texto4);
- // SetText
- titulo1.setText(getTitulo(0));
- texto1.setText(getTexto(0)+"\n\n#"+getAutor(0)+"\n\n");
- titulo2.setText(getTitulo(1));
- texto2.setText(getTexto(1)+"\n\n#"+getAutor(1)+"\n\n");
- titulo3.setText(getTitulo(2));
- texto3.setText(getTexto(2)+"\n\n#"+getAutor(2)+"\n\n");
- titulo4.setText(getTitulo(3));
- texto4.setText(getTexto(3)+"\n\n#"+getAutor(3)+"\n\n");
- // Exibe
- titulo1.setVisibility(TextView.VISIBLE);
- texto1.setVisibility(TextView.VISIBLE);
- titulo2.setVisibility(TextView.VISIBLE);
- texto2.setVisibility(TextView.VISIBLE);
- titulo3.setVisibility(TextView.VISIBLE);
- texto3.setVisibility(TextView.VISIBLE);
- titulo4.setVisibility(TextView.VISIBLE);
- texto4.setVisibility(TextView.VISIBLE);
- } catch (Exception e) {
- showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do arquivo.");
- }
- }
- }
- };
- AsyncTask<Void, Void, String> atualizaApp = new AsyncTask<Void, Void, String>(){
- @Override
- protected String doInBackground(Void... params) {
- String versao = "0";
- try {
- // Baixar iPoema.txt
- URL url = new URL("http://www.xadees.xpg.com.br/iPoema.txt");
- File file = new File(PATH + "iPoema.txt");
- file.delete();
- URLConnection ucon = url.openConnection();
- InputStream is = ucon.getInputStream();
- BufferedInputStream bis = new BufferedInputStream(is);
- ByteArrayBuffer baf = new ByteArrayBuffer(50);
- lenghtOfFile = ucon.getContentLength();
- int current = 0;
- while ((current = bis.read()) != -1) {
- baf.append((byte) current);
- progress = current;
- }
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(baf.toByteArray());
- fos.close();
- // Ler iPoema.txt
- StringBuilder text = new StringBuilder();
- BufferedReader br = new BufferedReader(new FileReader(file));
- String line;
- while ((line = br.readLine()) != null) {
- text.append(line);
- }
- versao = text.toString();
- } catch (IOException e) {
- showMessage(e.getClass().getName(), "Erro ao tentar realizar o download do arquivo.");
- } catch (Exception e) {
- showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do arquivo.");
- }
- return versao;
- }
- @Override
- protected void onPostExecute(String s) {
- super.onPostExecute(s);
- int vAtual = Pi.versionCode;
- int vAPK = Integer.parseInt(s);
- if (vAtual < vAPK) {
- try {
- // Baixar
- URL url = new URL("http://www.xadees.xpg.com.br/iPoema%20for%20Android.apk");
- File file = new File(PATH + "iPoema.apk");
- file.delete();
- URLConnection ucon = url.openConnection();
- InputStream is = ucon.getInputStream();
- BufferedInputStream bis = new BufferedInputStream(is);
- ByteArrayBuffer baf = new ByteArrayBuffer(50);
- lenghtOfFile = ucon.getContentLength();
- int current = 0;
- while ((current = bis.read()) != -1) {
- baf.append((byte) current);
- progress = current;
- }
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(baf.toByteArray());
- fos.close();
- // Instalar
- Intent intent = new Intent(Intent.ACTION_VIEW);
- intent.setDataAndType(Uri.fromFile(new File(PATH + "iPoema.apk")), "application/vnd.android.package-archive");
- //java.lang.Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "adb install -r " + PATH + "iPoema.apk"});
- //proc.waitFor();
- startActivityForResult(intent,0);
- } catch (IOException e) {
- showMessage(e.getClass().getName(), "Erro ao tentar realizar o download do pacote.");
- }
- } else {
- showMessage("iPoema", "iPoema já está atualizado.");
- }
- }
- };
- /**
- * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
- * one of the sections/tabs/pages.
- */
- public class SectionsPagerAdapter extends FragmentPagerAdapter {
- public SectionsPagerAdapter(FragmentManager fm) {
- super(fm);
- }
- @Override
- public Fragment getItem(int position) {
- // getItem is called to instantiate the fragment for the given page.
- // Return a PlaceholderFragment (defined as a static inner class below).
- return PlaceholderFragment.newInstance(position + 1);
- }
- @Override
- public int getCount() {
- // Show 3 total pages.
- return 3;
- }
- @Override
- public CharSequence getPageTitle(int position) {
- Locale l = Locale.getDefault();
- switch (position) {
- case 0:
- return getString(R.string.title_section1).toUpperCase(l);
- case 1:
- return getString(R.string.title_section2).toUpperCase(l);
- case 2:
- return getString(R.string.title_section3).toUpperCase(l);
- }
- return null;
- }
- }
- /**
- * A placeholder fragment containing a simple view.
- */
- public static class PlaceholderFragment extends Fragment {
- /**
- * The fragment argument representing the section number for this
- * fragment.
- */
- private static final String ARG_SECTION_NUMBER = "section_number";
- /**
- * Returns a new instance of this fragment for the given section
- * number.
- */
- public static PlaceholderFragment newInstance(int sectionNumber) {
- PlaceholderFragment fragment = new PlaceholderFragment();
- Bundle args = new Bundle();
- args.putInt(ARG_SECTION_NUMBER, sectionNumber);
- fragment.setArguments(args);
- return fragment;
- }
- public PlaceholderFragment() {
- }
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View rootView = inflater.inflate(R.layout.fragment_i_poema, container, false);
- // Componenetes
- TextView section_label = (TextView) rootView.findViewById(R.id.section_label);
- ImageView appLogo = (ImageView) rootView.findViewById(R.id.appLogo);
- // AboutApp() {
- TextView aboutApp1 = (TextView) rootView.findViewById(R.id.aboutApp1);
- TextView aboutApp2 = (TextView) rootView.findViewById(R.id.aboutApp2);
- TextView appName = (TextView) rootView.findViewById(R.id.appName);
- TextView appVersion = (TextView) rootView.findViewById(R.id.appVersion);
- TextView appAutor = (TextView) rootView.findViewById(R.id.appAutor);
- TextView appURL = (TextView) rootView.findViewById(R.id.appURL);
- appVersion.setText("Versão 1.4.0");
- // }
- // AboutAutor() {
- ImageView autorFoto = (ImageView) rootView.findViewById(R.id.autorFoto);
- TextView aboutPotynho = (TextView) rootView.findViewById(R.id.aboutPotynho);
- // }
- switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
- case 1:
- section_label.setText(getString(R.string.title_section1));
- appLogo.setVisibility(ImageView.GONE);
- autorFoto.setVisibility(ImageView.GONE);
- aboutPotynho.setVisibility(TextView.GONE);
- aboutApp1.setVisibility(TextView.GONE);
- aboutApp2.setVisibility(TextView.GONE);
- appName.setVisibility(TextView.GONE);
- appVersion.setVisibility(TextView.GONE);
- appAutor.setVisibility(TextView.GONE);
- appURL.setVisibility(TextView.GONE);
- break;
- case 2:
- section_label.setText(getString(R.string.title_section2));
- appLogo.setVisibility(ImageView.VISIBLE);
- autorFoto.setVisibility(ImageView.GONE);
- aboutPotynho.setVisibility(TextView.GONE);
- aboutApp1.setVisibility(TextView.VISIBLE);
- aboutApp2.setVisibility(TextView.VISIBLE);
- appName.setVisibility(TextView.VISIBLE);
- appVersion.setVisibility(TextView.VISIBLE);
- appAutor.setVisibility(TextView.VISIBLE);
- appURL.setVisibility(TextView.VISIBLE);
- break;
- case 3:
- section_label.setText(getString(R.string.title_section3));
- appLogo.setVisibility(ImageView.GONE);
- autorFoto.setVisibility(ImageView.VISIBLE);
- aboutPotynho.setVisibility(TextView.VISIBLE);
- aboutApp1.setVisibility(TextView.GONE);
- aboutApp2.setVisibility(TextView.GONE);
- appName.setVisibility(TextView.GONE);
- appVersion.setVisibility(TextView.GONE);
- appAutor.setVisibility(TextView.GONE);
- appURL.setVisibility(TextView.GONE);
- break;
- default:
- section_label.setText("404: NOT FOUND!");
- break;
- }
- return rootView;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement