https://manuais.iessanclemente.net/index.php?title=Intents._Lanzar_unha_Activity&feed=atom&action=history
Intents. Lanzar unha Activity - Historial de revisiones
2024-03-29T09:03:45Z
Historial de revisiones de esta página en el wiki
MediaWiki 1.36.2
https://manuais.iessanclemente.net/index.php?title=Intents._Lanzar_unha_Activity&diff=50538&oldid=prev
Carrion: /* Intents explícitos */
2014-11-04T19:48:19Z
<p><span dir="auto"><span class="autocomment">Intents explícitos</span></span></p>
<p><b>Página nueva</b></p><div>==Permisos==<br />
*Cando instalamos unha aplicación nun dispositivo real (non nun AVD) se precisa acceder a características que esixen algún tipo de permiso, o proceso de instalación pregunta se estamos dispostos a dar eses permisos para que a aplicación poida funcionar con tódalas súas funcionalidades.<br />
*Por exemplo, instalando Gmail:<br />
[[Image:Gmail.png|250px]]<br />
<br />
*O proceso de instalación pregunta ao usuario se por exemplo lle deixa acceder a esta aplicación á súa lista de contactos.<br />
<br />
*No ficheiro '''AndroidManifest.xml''' é onde se declaran os permisos que precisa a aplicación para poder facer uso de funcionalidades protexidas: contactos, cámara, mermoria usb, gps, etc.<br />
<br />
*A través de unha ou varias etiquetas '''<uses-permission>''' vanse declarar os permisos que precisa a aplicación.<br />
<br />
Exemplos de permisos no ficheiro AndroidManifest.xml<br />
<syntaxhighlight lang="xml" line enclose="div" highlight="31-33" ><br />
<?xml version="1.0" encoding="utf-8"?><br />
<manifest xmlns:android="http://schemas.android.com/apk/res/android"<br />
package="com.example.u3_20_intents"<br />
android:versionCode="1"<br />
android:versionName="1.0" ><br />
<br />
<uses-sdk<br />
android:minSdkVersion="16"<br />
android:targetSdkVersion="21" /><br />
<br />
<application<br />
android:allowBackup="true"<br />
android:icon="@drawable/ic_launcher"<br />
android:label="@string/app_name"<br />
android:theme="@style/AppTheme" ><br />
<activity<br />
android:name=".U3_20_Intents"<br />
android:label="@string/app_name" ><br />
<intent-filter><br />
<action android:name="android.intent.action.MAIN" /><br />
<br />
<category android:name="android.intent.category.LAUNCHER" /><br />
</intent-filter><br />
</activity><br />
<activity<br />
android:name=".RecibirDatos"<br />
android:label="@string/title_activity_recibir_datos" ><br />
</activity><br />
</application><br />
<br />
<uses-permission android:name="android.permission.CALL_PHONE" /><br />
<uses-permission android:name="android.permission.INTERNET" /><br />
<uses-permission android:name="android.permission.READ_CONTACTS" /><br />
<br />
<br />
</manifest><br />
</syntaxhighlight ><br />
*'''Liña 31''': Permiso que "permite" realizar unha chamada de telefono sen pasar a través do interface do teléfono para que o usuario marque.<br />
*'''Liña 32''': Permítelle á aplicación abrir conexións de rede.<br />
*'''Liña 33''': Da súa lectura pódese concluír o que permite. <br />
<br />
*Para coñecer os permisos dispoñibles podemos consultar o seguinte enlace e incluílos directamente no xml: <br />
**http://developer.android.com/reference/android/Manifest.permission.html<br />
<br />
*Tamén se pode realizar de modo gráfico.<br />
*No ficheiro AndroidManifest.xml premer en '''Permissions'''<br />
[[Image:Android_2014_U3_20_LanzarActivity_15.jpg|600px]]<br />
<br />
*Lembrar que os permisos asígnanse no momento da instalación a aplicación. Nun dispositivo real pídeselle consentimento ao usuario, non así nun AVD.<br />
<br />
==Chamadas a intents de modo implícito==<br />
*Como xa se dixo, o que un compoñente pode ser lanzado de forma implícita cando se indica a '''acción''' que se desexa realizar e se é o caso os datos sobre os que se desexa realizar a acción.<br />
*Non se vai especificar a <br />
<br />
<syntaxhighlight lang="java" line enclose="div" highlight="17-24,33-35" ><br />
package com.example.u3_20_intents;<br />
<br />
import android.app.Activity;<br />
import android.content.Intent;<br />
import android.database.Cursor;<br />
import android.net.Uri;<br />
import android.os.Bundle;<br />
import android.provider.ContactsContract;<br />
import android.view.Menu;<br />
import android.view.MenuItem;<br />
import android.view.View;<br />
import android.widget.CheckBox;<br />
import android.widget.TextView;<br />
import android.widget.Toast;<br />
<br />
public class U3_20_Intents extends Activity {<br />
<br />
public final static String NOME = "com.example.NOME";<br />
private static final int COD_PETICION = 33;<br />
private static final int COD_CONTACTOS = 7;<br />
<br />
TextView tvNome;<br />
<br />
@Override<br />
protected void onCreate(Bundle savedInstanceState) {<br />
super.onCreate(savedInstanceState);<br />
setContentView(R.layout.activity_u3_20__intents);<br />
tvNome = (TextView) findViewById(R.id.et_nome);<br />
}<br />
<br />
@Override<br />
public boolean onCreateOptionsMenu(Menu menu) {<br />
// Inflate the menu; this adds items to the action bar if it is present.<br />
getMenuInflater().inflate(R.menu.u3_20__intents, menu);<br />
return true;<br />
}<br />
<br />
@Override<br />
public boolean onOptionsItemSelected(MenuItem item) {<br />
// Handle action bar item clicks here. The action bar will<br />
// automatically handle clicks on the Home/Up button, so long<br />
// as you specify a parent activity in AndroidManifest.xml.<br />
int id = item.getItemId();<br />
if (id == R.id.action_settings) {<br />
return true;<br />
}<br />
return super.onOptionsItemSelected(item);<br />
}<br />
<br />
public void onEnviarClick(View view) {<br />
CheckBox chkDestruir = (CheckBox) findViewById(R.id.chk_destruir);<br />
<br />
Intent intent = new Intent(this, RecibirDatos.class);<br />
intent.putExtra(NOME, tvNome.getText().toString());<br />
<br />
// startActivity(intent);<br />
startActivityForResult(intent, COD_PETICION);<br />
<br />
if (chkDestruir.isChecked())<br />
finish();<br />
}<br />
<br />
public void onCalculadoraClick(View v) {<br />
<br />
Intent intent = new Intent();<br />
intent.setClassName("com.android.calculator2", "com.android.calculator2.Calculator");<br />
<br />
// startActivity(intent);<br />
startActivityForResult(intent, 3);<br />
}<br />
<br />
@Override<br />
// Este método chámase cando se volve da actividade secundaria<br />
protected void onActivityResult(int requestCode, int resultCode, Intent data) {<br />
<br />
if (requestCode == COD_PETICION) {<br />
if (resultCode == RESULT_OK) {<br />
if (data.hasExtra("APELIDO")) {<br />
Toast.makeText(this, tvNome.getText() + " O teu apelido é " + data.getExtras().getString("APELIDO"), Toast.LENGTH_SHORT).show();<br />
}<br />
} else<br />
Toast.makeText(this, "Saíches da actividade secundaria sen premer o botón Pechar", Toast.LENGTH_SHORT).show();<br />
}<br />
<br />
else if (requestCode == COD_CONTACTOS && resultCode == RESULT_OK) {<br />
Uri contactoData = data.getData();<br />
Cursor c = managedQuery(contactoData, null, null, null, null);<br />
if (c.moveToFirst()) {<br />
String nombre = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));<br />
Toast.makeText(this, "Contacto: " + nombre, Toast.LENGTH_LONG).show();<br />
}<br />
}<br />
<br />
}<br />
<br />
public void chamarIntent(View view) {<br />
Intent intent = null;<br />
switch (view.getId()) {<br />
case R.id.btn_seleccionar_contacto:<br />
intent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts/people/"));<br />
startActivityForResult(intent, COD_CONTACTOS);<br />
break;<br />
<br />
case R.id.btn_amosar_contactos:<br />
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("content://contacts/people/"));<br />
startActivity(intent);<br />
break;<br />
<br />
case R.id.btn_chamar_tel:<br />
intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:(+34)981445566"));<br />
startActivity(intent);<br />
break;<br />
<br />
case R.id.btn_marcar_tel:<br />
intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:(+34)986112233"));<br />
startActivity(intent);<br />
break;<br />
<br />
case R.id.btn_navegador:<br />
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.es/"));<br />
startActivity(intent);<br />
break;<br />
}<br />
}<br />
<br />
public void finish() {<br />
super.finish();<br />
Toast.makeText(this, "Mataches a actividade principal", Toast.LENGTH_SHORT).show();<br />
}<br />
<br />
}<br />
<br />
</syntaxhighlight><br />
<br />
<br />
<syntaxhighlight lang="java" line enclose="div" highlight="17-24,33-35" ><br />
package com.example.u3_20_intents;<br />
<br />
import android.app.Activity;<br />
import android.content.Intent;<br />
import android.os.Bundle;<br />
import android.view.Menu;<br />
import android.view.MenuItem;<br />
import android.view.View;<br />
import android.widget.EditText;<br />
import android.widget.TextView;<br />
import android.widget.Toast;<br />
<br />
public class RecibirDatos extends Activity {<br />
// String Forma_Pechar_Activity;<br />
<br />
@Override<br />
protected void onCreate(Bundle savedInstanceState) {<br />
super.onCreate(savedInstanceState);<br />
setContentView(R.layout.activity_recibir_datos);<br />
// Forma_Pechar_Activity=" Premendo botonera Retroceso";<br />
<br />
TextView tvResultado = (TextView) findViewById(R.id.tv_resultado);<br />
<br />
Intent intent = getIntent();<br />
<br />
if ("http".equals(intent.getScheme()))<br />
<br />
tvResultado.setText("URL: " + intent.getDataString());<br />
else<br />
tvResultado.setText("Ola " + intent.getExtras().getString(U3_20_Intents.NOME));<br />
<br />
}<br />
<br />
@Override<br />
public boolean onCreateOptionsMenu(Menu menu) {<br />
// Inflate the menu; this adds items to the action bar if it is present.<br />
getMenuInflater().inflate(R.menu.recibir_datos, menu);<br />
return true;<br />
}<br />
<br />
@Override<br />
public boolean onOptionsItemSelected(MenuItem item) {<br />
// Handle action bar item clicks here. The action bar will<br />
// automatically handle clicks on the Home/Up button, so long<br />
// as you specify a parent activity in AndroidManifest.xml.<br />
int id = item.getItemId();<br />
if (id == R.id.action_settings) {<br />
return true;<br />
}<br />
return super.onOptionsItemSelected(item);<br />
}<br />
<br />
public void onPecharClick(View view) {<br />
// Forma_Pechar_Activity=" Premendo botón Pechar";<br />
<br />
EditText et_apelido = (EditText) findViewById(R.id.et_apelido);<br />
<br />
Intent datos_volta = new Intent();<br />
datos_volta.putExtra("APELIDO", et_apelido.getText().toString());<br />
setResult(RESULT_OK, datos_volta);<br />
finish();<br />
<br />
}<br />
<br />
public void finish() {<br />
super.finish();<br />
// Toast.makeText(this,<br />
// "Saiches da actividade secundaria: "+Forma_Pechar_Activity,<br />
// Toast.LENGTH_SHORT).show();<br />
}<br />
<br />
}<br />
<br />
</syntaxhighlight><br />
<br />
<br />
<br />
<syntaxhighlight lang="xml" line enclose="div" highlight="" ><br />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br />
android:layout_width="match_parent"<br />
android:layout_height="match_parent"<br />
android:orientation="vertical"<br />
android:padding="5dp" ><br />
<br />
<LinearLayout<br />
android:layout_width="match_parent"<br />
android:layout_height="wrap_content"<br />
android:orientation="horizontal" ><br />
<br />
<TextView<br />
android:layout_width="wrap_content"<br />
android:layout_height="wrap_content"<br />
android:text="Dime o teu nome" /><br />
<br />
<EditText<br />
android:id="@+id/et_nome"<br />
android:layout_width="match_parent"<br />
android:layout_height="wrap_content" /><br />
</LinearLayout><br />
<br />
<CheckBox<br />
android:id="@+id/chk_destruir"<br />
android:layout_width="match_parent"<br />
android:layout_height="wrap_content"<br />
android:checked="false"<br />
android:text="Destruír esta activity ao chamar á 2ª" /><br />
<br />
<TextView<br />
android:layout_width="wrap_content"<br />
android:layout_height="wrap_content"<br />
android:layout_gravity="center_horizontal"<br />
android:text="Chamadas explícitas a intents"<br />
android:textColor="#00F" /><br />
<br />
<Button<br />
android:id="@+id/btn_enviar"<br />
android:layout_width="match_parent"<br />
android:layout_height="wrap_content"<br />
android:onClick="onEnviarClick"<br />
android:text="Chamar 2ª Activity: Recibir Datos" /><br />
<br />
<Button<br />
android:id="@+id/btn_calculadora"<br />
android:layout_width="match_parent"<br />
android:layout_height="wrap_content"<br />
android:onClick="onCalculadoraClick"<br />
android:text="Calculadora" /><br />
<br />
<TextView<br />
android:layout_width="wrap_content"<br />
android:layout_height="wrap_content"<br />
android:layout_gravity="center_horizontal"<br />
android:text="Chamadas implícitas a intents"<br />
android:textColor="#00F" /><br />
<br />
<Button<br />
android:id="@+id/btn_amosar_contactos"<br />
android:layout_width="match_parent"<br />
android:layout_height="wrap_content"<br />
android:onClick="chamarIntent"<br />
android:text="Amosar contactos" /><br />
<br />
<Button<br />
android:id="@+id/btn_seleccionar_contacto"<br />
android:layout_width="match_parent"<br />
android:layout_height="wrap_content"<br />
android:onClick="chamarIntent"<br />
android:text="Seleccionar contacto" /><br />
<br />
<Button<br />
android:id="@+id/btn_chamar_tel"<br />
android:layout_width="match_parent"<br />
android:layout_height="wrap_content"<br />
android:onClick="chamarIntent"<br />
android:text="Chamar por teléfono" /><br />
<br />
<Button<br />
android:id="@+id/btn_marcar_tel"<br />
android:layout_width="match_parent"<br />
android:layout_height="wrap_content"<br />
android:onClick="chamarIntent"<br />
android:text="Marcar nº de teléfono" /><br />
<br />
<Button<br />
android:id="@+id/btn_navegador"<br />
android:layout_width="match_parent"<br />
android:layout_height="wrap_content"<br />
android:onClick="chamarIntent"<br />
android:text="Abrir navegador*" /><br />
<br />
</LinearLayout><br />
</syntaxhighlight" ><br />
<br />
<br />
<syntaxhighlight lang="xml" line enclose="div" highlight="" ><br />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br />
xmlns:tools="http://schemas.android.com/tools"<br />
android:layout_width="match_parent"<br />
android:layout_height="match_parent"<br />
android:orientation="vertical" ><br />
<br />
<TextView<br />
android:id="@+id/tv_resultado"<br />
android:layout_width="wrap_content"<br />
android:layout_height="wrap_content"<br />
android:layout_gravity="center_horizontal"<br />
android:textSize="20sp"<br />
android:text="resultado" /><br />
<br />
<EditText<br />
android:id="@+id/et_apelido"<br />
android:layout_width="wrap_content"<br />
android:layout_height="wrap_content"<br />
android:layout_gravity="center_horizontal"<br />
android:hint="Introduce o teu apelido" /><br />
<br />
<Button<br />
android:id="@+id/btn_pechar"<br />
android:layout_width="wrap_content"<br />
android:layout_height="wrap_content"<br />
android:layout_gravity="center_horizontal"<br />
android:onClick="onPecharClick"<br />
android:text="Pechar" /><br />
<br />
</LinearLayout><br />
</syntaxhighlight" ><br />
<br />
<br />
<br />
<br />
<br />
<br> -- [[Usuario:angelfg|Ángel D. Fernández González]] e [[Usuario:Carrion|Carlos Carrión Álvarez]] -- (2014).</div>
Carrion