private static String readFile(Context context, int tipo) throws IOException { if (tipo == R.string.classicos) { return FileUtils.readRawFileString(context, R.raw.carros_classicos, "UTF-8"); } else if (tipo == R.string.esportivos) { return FileUtils.readRawFileString(context, R.raw.carros_esportivos, "UTF-8"); } return FileUtils.readRawFileString(context, R.raw.carros_luxo, "UTF-8"); }
private static void salvaArquivoNaMemoriaExterna(Context context, String url, String json) { String fileName = url.substring(url.lastIndexOf("/") + 1); // Cria um arquivo privado File f = SDCardUtils.getPrivateFile(context, fileName, Environment.DIRECTORY_DOWNLOADS); IOUtils.writeString(f, json); Log.d(TAG, "1) Arquivo privado salvo na pasta downloads: " + f); // Cria um arquivo público f = SDCardUtils.getPublicFile(fileName, Environment.DIRECTORY_DOWNLOADS); IOUtils.writeString(f, json); Log.d(TAG, "2) Arquivo público salvo na pasta downloads: " + f); }
private static void salvaArquivoNaMemoriaInterna(Context context, String url, String json) { String fileName = url.substring(url.lastIndexOf("/") + 1); File f = FileUtils.getFile(context, fileName); IOUtils.writeString(f, json); Log.d(TAG, "Arquivo salvo: " + f); }
private static List<Carro> parserXML(Context context, String xml) { List<Carro> carros = new ArrayList<Carro>(); Element root = XMLUtils.getRoot(xml, "UTF-8"); // Le todas as tags <carro> List<Node> nodeCarros = XMLUtils.getChildren(root, "carro"); // Insere cada carro na lista for (Node node : nodeCarros) { Carro c = new Carro(); // Lê as informações de cada carro c.nome = XMLUtils.getText(node, "nome"); c.desc = XMLUtils.getText(node, "desc"); c.urlFoto = XMLUtils.getText(node, "url_foto"); c.urlInfo = XMLUtils.getText(node, "url_info"); c.urlVideo = XMLUtils.getText(node, "url_video"); c.latitude = XMLUtils.getText(node, "latitude"); c.longitude = XMLUtils.getText(node, "longitude"); if (LOG_ON) { Log.d(TAG, "Carro " + c.nome + " > " + c.urlFoto); } carros.add(c); } if (LOG_ON) { Log.d(TAG, carros.size() + " encontrados."); } return carros; } }
@Override protected void onHandleIntent(Intent intent) { running = true; // Este método executa em uma thread // Quando ele terminar, o método stopSelf() será chamado automaticamente int count = 0; while (running && count < MAX) { fazAlgumaCoisa(); Log.d(TAG, "ExemploServico executando... " + count); count++; } NotificationUtil.create(this,1,new Intent(this,MainActivity.class),R.mipmap.ic_launcher,"Fim","Olá"); Log.d(TAG, "ExemploServico fim."); } private void fazAlgumaCoisa() {
@Override public Object execute() throws Exception { if (selectedCarros != null) { for (Carro c : selectedCarros) { // Faz o download da foto do carro para arquivo String url = c.urlFoto; String fileName = url.substring(url.lastIndexOf("/")); // Cria o arquivo no SD card File file = SDCardUtils.getPrivateFile(getContext(), "carros", fileName); IOUtils.downloadToFile(c.urlFoto, file); // Salva a Uri para compartilhar a foto imageUris.add(Uri.fromFile(file)); } } return null; }
public static List<Carro> getCarrosFromWebService(Context context, int tipo) throws IOException { String tipoString = getTipo(tipo); String url = URL.replace("{tipo}", tipoString); Log.d(TAG, "URL: " + url); HttpHelper http = new HttpHelper(); String json = http.doGet(url); List<Carro> carros = parserJSON(context, json); // salvaArquivoNaMemoriaInterna(context, url, json); // Depois de buscar salva os carros salvarCarros(context, tipo, carros); return carros; }
@Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.action_video_browser) { // Abre o vídeo no browser IntentUtils.openBrowser(getContext(), url); } else if (item.getItemId() == R.id.action_video_player) { // Abre o vídeo no Player de Vídeo Nativo IntentUtils.showVideo(getContext(), url); } else if (item.getItemId() == R.id.action_video_videoview) { // Abre outra activity com VideoView Intent intent = new Intent(getContext(), VideoActivity.class); intent.putExtra("carro", carro); startActivity(intent); } return true; } });
public void onClickStop(View view) { stopService(new Intent(this, CLS)); NotificationUtil.cancell(this, 1); } }
@Override public void onRefresh() { // Valida se existe conexão ao fazer o gesto Pull to Refresh if (AndroidUtils.isNetworkAvailable(getContext())) { // Atualiza ao fazer o gesto Pull to Refresh taskCarros(true); } else { swipeLayout.setRefreshing(false); snack(recyclerView, R.string.msg_error_conexao_indisponivel); } } };
@Override public void onPageSelected(int position) { // Salva o índice da página/tab selecionada Prefs.setInteger(getContext(), "tabIdx", viewPager.getCurrentItem()); // Faz o backup backupManager.dataChanged(); }
public static List<Carro> getCarrosFromArquivo(Context context, int tipo) throws IOException { String tipoString = getTipo(tipo); String fileName = String.format("carros_%s.json", tipoString); Log.d(TAG, "Abrindo arquivo: " + fileName); // Lê o arquivo da memória interna String json = FileUtils.readFile(context, fileName, "UTF-8"); if (json == null) { Log.d(TAG, "Arquivo " + fileName + " não encontrado."); return null; } List<Carro> carros = parserJSON(context, json); Log.d(TAG, "Retornando carros do arquivo " + fileName + "."); return carros; }
@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { for (int result : grantResults) { if (result == PackageManager.PERMISSION_DENIED) { // Negou a permissão. Mostra alerta e fecha. AlertUtils.alert(getContext(), R.string.app_name, R.string.msg_alerta_permissao, R.string.ok, new Runnable() { @Override public void run() { // Negou permissão. Sai do app. finish(); } }); return; } } // Permissões concedidas, pode entrar. startActivity(new Intent(this, MainActivity.class)); finish(); } }
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Cria o HTML com o texto de about SpannableStringBuilder aboutBody = new SpannableStringBuilder(); String versionName = AndroidUtils.getVersionName(getActivity()); aboutBody.append(Html.fromHtml(getString(R.string.about_dialog_text, versionName))); // Infla o layout LayoutInflater inflater = LayoutInflater.from(getActivity()); TextView view = (TextView) inflater.inflate(R.layout.dialog_about, null); view.setText(aboutBody); view.setMovementMethod(new LinkMovementMethod()); // Cria o dialog customizado return new AlertDialog.Builder(getActivity()) .setTitle(R.string.about_dialog_title) .setView(view) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } } ) .create(); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = findViewById(R.id.text); img = findViewById(R.id.img); // Configura o listener do GestureOverlayView GestureOverlayView gestureOverlayView = findViewById(R.id.gestureView); gestureOverlayView.addOnGesturePerformedListener(this); // Solicita as permissões String[] permissoes = new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }; PermissionUtils.validate(this, 0, permissoes); // res/raw // gestureLib = GestureLibraries.fromRawResource(this, R.raw.gestures); }
int tabIdx = Prefs.getInteger(getContext(), "tabIdx"); viewPager.setCurrentItem(tabIdx); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void run() { try { while (running && count < MAX) { // Simula algum processamento Thread.sleep(1000); Log.d(TAG, "HelloService executando... " + count); count++; } Log.d(TAG, "HelloService fim."); } catch (InterruptedException e) { Log.e(TAG,e.getMessage(),e); } finally { // Auto-Encerra o serviço se o contador chegou a 10 stopSelf(); // Cria uma notificação para avisar o usuário que terminou. Context context = HelloService.this; Intent intent = new Intent(context,MainActivity.class); NotificationUtil.create(context, 1, intent, R.mipmap.ic_launcher, "HelloService", "Fim do serviço."); } } }
@Override public void onReceive(Context context, Intent intent) { Log.d(TAG, ">" + intent.getAction()); Sms sms = new Sms(); // Lê a mensagem SmsMessage msg = sms.read(intent); String celular = msg.getDisplayOriginatingAddress(); String mensagem = msg.getDisplayMessageBody(); Log.d(TAG, "SMSReceiver: sms[" + celular + "] -> " + mensagem); NotificationUtil.create(context, 1, new Intent(context, MainActivity.class), R.mipmap.ic_launcher, "Novo SMS de: " + celular, mensagem); } }