miércoles, 26 de septiembre de 2012

Añadir accesos directos

Dependiendo de las funcionalidades que ofrezca nuestra aplicación, nos puede interesar que el usuario pueda añadir accesos directos a ellas. Así pues para llegar a esa opción no será necesario abrir y navegar por la aplicación.
Para crear accesos directos podemos hacerlo de dos formas: Podemos permitir que el usuario tenga la opción de añadirla manualmente (por ejemplo, usando un botón en la app que cree el acceso) o bien, navegando por el sistema (dónde se encuentran el resto de accesos de las otras aplicaciones).

Así pues, en este ejemplo vamos a mostrar com permitir al usuario añadir un acceso directo a partir de la aplicación, ya que, la segunda opción es obvia.

En la aplicación veremos 2 activities, la primera que contendrá el botón que añadirá el acceso a la segunda activity. Sólo ser accesible a partir del acceso directo.

strings.xml

<resources>

    <string name="app_name">BlogShortCut</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">BlogShortCut</string>
    
    <string name="addShortcut">Add shortcut to HomeScreen</string>

    <string name="shortcut">ShortcutExample</string>
    <string name="activityShortcut">I\'m shortCut Activity!</string>

</resources>


AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.blogshortcut"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ShortCutActivity" >
            <intent-filter>
                <action android:name="android.intent.action.CREATE_SHORTCUT" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button_add_shortcut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="50dip"
        android:gravity="center"
        android:text="@string/addShortcut" >
    </Button>

</LinearLayout>

activity_shortcut.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textview_intent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:padding="@dimen/padding_medium"
        android:text="@string/activityShortcut" />

</RelativeLayout>

MainActivity.java
package com.example.blogshortcut;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// allow install shortcuts from homescreen

((Button) findViewById(R.id.button_add_shortcut))
.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// comprobamos que el dispositivo puede crear el acceso directo
if (getPackageManager()
.queryBroadcastReceivers(
new Intent(
"com.android.launcher.action.INSTALL_SHORTCUT"),
0).size() > 0) {
createShortCut();
} else {
Toast.makeText(MainActivity.this,
"cannot add shortcut", Toast.LENGTH_SHORT)
.show();
}

}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

private void createShortCut() {

Intent shortcutIntent = new Intent(this, ShortCutActivity.class);
shortcutIntent.addCategory(Intent.CATEGORY_DEFAULT);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
shortcutIntent.putExtra("myParameter", "Parameter from Intent");
shortcutIntent.putExtra("shortcut", "no");

Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra("duplicate", false); //evitamos duplicados
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getResources()
.getString(R.string.activityShortcut));
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this,
R.drawable.YOUR_ICON));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(addIntent);
}
}

ShortCutActivity.java
package com.example.blogshortcut;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class ShortCutActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shortcut);

Bundle extras = getIntent().getExtras();
if (extras != null) {
String intentText = extras.getString("myParameter");
if (!"".equals(intentText)) {
((TextView) findViewById(R.id.textview_intent))
.setText(intentText);
}
}
if (extras == null) {
createShortCut();
}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

private void createShortCut() {
Intent shortcutIntent = new Intent(this, ShortCutActivity.class);
shortcutIntent.addCategory(Intent.CATEGORY_DEFAULT);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
shortcutIntent.putExtra("myParameter", "Parameter from Intent");
shortcutIntent.putExtra("shortcut", "no");

Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra("duplicate", false);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getResources()
.getString(R.string.activityShortcut));
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this,
R.drawable.ic_shortcut));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(addIntent);
}
}


A continuación la imagen del shortcut creado:


It works!
Roger Sala,






No hay comentarios:

Publicar un comentario