AppShortcuts 이벤트 시작

16904 단어 Android
Android 2 Advent Calendar 2016 나흘째 보도다.
Android 7.1의 AppShortcuts를 소개합니다.

이른바 App Shortcuts


앱스포츠는 안드로이드 7.1에 추가된 앱 내 기능을 만들 수 있는 단축키 기능이다.
Applialcom을 길게 누르면 표시되는 단축키를 통해 프로그램의 기능에 접근할 수 있다.
단축키를 복제하여 이니시에이터에 고정할 수도 있습니다.
단축키에 사용 빈도가 높은 기능이 추가되면 바로 기능에 접근할 수 있어 편리하다.
단축키 목록
단축키의 핀


그나저나 구글 앱 외에 트위터, 탈론(Tiwtter Client) 등에 이미 대응하는 기능이 있어 구글플레이에서 떨어져볼 수 있다.

AppShortcuts의 종류


단축키는 두 종류가 있다.
Static Shortcuts
정적 단축키로 xml에서 단축키 설정을 설명하고 단축키를 표시합니다.
단축키를 동적으로 업데이트하고 삭제할 수 없습니다. 변경하려면 프로그램을 업데이트해야 합니다.
동적으로 삭제하는 경우 삭제됩니다.
Dynamic Shortcuts
동적 단축키는 StaticShortcuts와 달리 코드에 단축키를 추가, 삭제, 업데이트할 수 있습니다.
동적으로 추가할 수 있기 때문에 단축키에 사용자가 자주 방문하는 페이지를 추가할 수도 있고 단축키 등 다양한 사용 방법을 선택할 수도 있다.

Static Shortcuts 설치


단축키 구성 파일 준비
표시할 단축키 설정을 설명하는 xml 파일을 res/xml 에 설정합니다.shortcuts에 표시되는 단축키입니다.
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- ショートカットのID・アイコン・文言等を設定 -->
    <shortcut
        android:icon="@mipmap/ic_launcher"
        android:shortcutId="first_shortcut"
        android:shortcutShortLabel="@string/short_label">
        <!-- 遷移先 -->
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.kuwapp.myshortcutsample"
            android:targetClass="com.kuwapp.myshortcutsample.MainActivity" />
    </shortcut>

</shortcuts>
AndroidManifest.xml에서 단축키 설정 파일 지정하기
intent-filterandroid.intent.action.MAINandroid.intent.category.LAUNCHER의Activity의meta-data 요소에 단축키 설정 파일을 지정합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kuwapp.myshortcutsample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <!-- 設定ファイルを指定する -->
            <meta-data android:name="android.app.shortcuts"
                android:resource="@xml/shortcuts" />
        </activity>
    </application>

</manifest>
이렇게 하면 단축키를 표시할 수 있다.

shortcut 요소에 기술할 수 있는 속성


등록 정보
설명
android:shortcutId
shortcut을 인식하려면 ID가 있어야 합니다.
android:enabled
유효, 유효하지 않은 태그 초기값은 진짜입니다
android:shortcutShortLabel
시작 아이콘의 머리글 문
android:shortcutLongLabel
열 아이콘 길이에 따라 표시되는 단축키 문(정의되지 않은 경우 ShortLabel 사용)
android:shortcutDisabledMessage
잘못된 고정된 단축키가 헤더를 뽑을 때 표시되는 문장

Dynamic Shortcuts 설치


DynamicShortcuts 추가

ShortcutManager 사용류addDynamicShortcuts 또는 setDynamicShortcuts 방법.
어떤 방법이든 다이나믹 Shortcuts를 추가할 수 있다. 다른 것은addDynamicShortcuts 기존의 다이나믹 Shortcuts 목록에 새로운 다이나믹 ShortcutssetDynamicShortcuts를 추가하여 기존의 다이나믹 Shortcuts 목록을 새로운 다이나믹 Shortcuts로 바꾸는 것이다.
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
// Actionを設定しないと落ちる
intent.setAction(Intent.ACTION_DEFAULT);
ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(this, id)
        .setShortLabel(getString(R.string.short_label))
        .setIntent(intent)
        .build();
shortcutManager.addDynamicShortcuts(Collections.singletonList(shortcutInfo));

DynamicShortcuts 삭제

ShortcutManager 사용류removeAllDynamicShortcuts 또는 removeDynamicShortcuts 방법.
방법명으로 추정할 수 있듯이 removeAllDynamicShortcuts 모든 다이나믹 Shortcuts를 삭제하고 removeDynamicShortcuts 단일 다이나믹 Shortcuts를 삭제한다.removeDynamicShortcuts의 매개변수에서 삭제할 DynamicShortcuts의 ID를 지정합니다.
// 削除するDynamicShortcutのIDを指定
shortcutManager.removeDynamicShortcuts(removeShortcutIdList);

DynamicShortcuts 업데이트

ShortcutManager사용류updateShortcuts방법.
// 更新するShortcutと同一のIDを指定
ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(this, id)
        .setShortLabel(getString(R.string.short_label))
        .setIntent(intent)
        .build();
shortcutManager.updateShortcuts(Collections.singletonList(shortcutInfo));

단축키 사용 안 함


단축키가 비활성화되어 있으면 목록에서 표시할 수 없고, 박힌 아이콘도 회색으로 표시되지 않고 클릭할 수 없습니다.
클릭할 때disabledMessage 지정한 문장은 토스트로 표시한다.
고정된 단축키는 비활성화될 수 있지만 코드에서 동적으로 삭제할 수 없습니다.
Static Shortcutsandroid:enabled 속성을 가짜로 설정하면 무효입니다.
유효하지 않은 경우 표시되는 정보는 android:shortcutDisabledMessage에 지정됩니다.
Dynamic ShortcutsShortcutManager 호출 클래스disableShortcuts 방법.
매개변수 disable할 단축키 ID를 지정합니다.
shortcutManager.disableShortcuts(disableShortcutIds);
올바르지 않을 때 표시되는 정보는 ShortcutInfo 만들 때 setDisabledMessage 방법으로 지정됩니다.
ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(this, id)
                .setShortLabel(getString(R.string.short_label))
                .setIntent(intent)
                .setDisabledMessage(getString(R.string.disable_message))
                .build();

TIPS 및 네스트링 등


단축키 없음


다음과 같은 경우에는 단축키가 표시되지 않습니다.
  • android:shortcutId 다른 단축키와 중첩
  • android:shortcutId에 string 자원 지정

  • 미지정android:action
  • 후면 스택을 다른 Activity에서 쌓아서 옮기고 싶어요.


    ActivityB로 마이그레이션한 후 Enter 키를 누른 상태에서 ActivtyA를 표시하려면 여러 Intent를 지정합니다.
    (ActivityA->ActivityB처럼 쌓아두기)
    StaticShortcuts
    <shortcut
        android:icon="@mipmap/ic_launcher"
        android:shortcutId="shortcut"
        android:shortcutShortLabel="@string/short_label">
        <!-- バックスタックに積みたいActivityの数だけintentを追加する 一番下に記述したintentが一番上に積まれる -->
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.kuwapp.myshortcutsample"
            android:targetClass="com.kuwapp.myshortcutsample.MainActivity" />
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.kuwapp.myshortcutsample"
            android:targetClass="com.kuwapp.myshortcutsample.SecondActivity" />
    </shortcut>
    
    DynamicShortcuts
    인스턴스ShortcutInfo를 생성할 때setIntents 메소드 매개변수에 여러 Intent를 지정합니다.
    Intent[] intents = // 略
    ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(this, id)
            .setShortLabel(getString(R.string.short_label))
            .setIntents(intents)
            .build();
    

    StaticShortcuts를 사용하여 구축할 때 패키지 이름을 동적으로 변경할 때 대응


    여러 APK가 공존할 수 있도록 구축 시 패키지 이름을 변경한 경우(debug과release 버전 등) StaticShortcuts의 int 요소에 추가android:targetPackage도 함께 변경해야 한다.
    나는 접근 방법으로서 다음과 같은 몇 가지를 고려할 수 있다고 생각한다.
  • 패키지 이름 수에 따라 단축키 설정 파일 만들기
  • BuildType 또는 Flavor가 증가할 때마다 대체적으로 같은 내용의 설정 파일을 추가해야 합니다
  • 구축 시 설정 파일을 동적으로 다시 쓰는 Gradle 작업 등
  • 한번 하면 편하지만 시간이 좀 걸린다
  • Static Shortcuts 중지, Dynamic Shortcuts 사용
  • 단순 교체이기 때문에 쉽습니다
  • 다이나믹 Shortcuts로의 이동이 쉬워서 다이나믹 Shortcuts를 사용하기로 했습니다.

    다른 단축키에서 같은 Activity로 이동하지만, 단축키마다 행동을 바꾸기를 원합니다


    다른 단축키에서 같은 Activity로 디스플레이 내용을 변환하려면 Intent의 Action이나 Extra에 값을 입력하여 처리를 변경할 수 있습니다.
    Static Shortcuts라면 다음과 같은 android:action에 독립된 동작을 넣었는지 여부입니다. intent 요소에 extra를 기술하고 시작 측면에서 받아들이면 어느 단축키에서 왔는지 알 수 있습니다.
    <intent
        android:action="com.kuwapp.Intent.MAIN"
        android:targetClass="com.kuwapp.appshortcutssample.MainActivity"
        android:targetPackage="com.kuwapp.appshortcutssample">
        <extra android:name="Shortcut" android:value="Main" />
    </intent>    
    
    다음은 Action or extra를 꺼내서 어느 단축키에서 왔는지 판단하고 처리를 바꾸면 됩니다.
    String action = getIntent().getAction();
    String extra = getIntent().getStringExtra("Shortcut");
    

    끝말


    AppShortcuts를 설치해 보았습니다.이제 안드로이드 7.1에서만 사용할 수 있지만 설치가 쉽고 편리해 넣을 수 있다.스케줄러:언제minSdkVersion이25가 되면 좋을텐데...
    저는 개인적으로 Dynamic Shortcuts가 부드러워서 Static Shortcuts를 사용한다는 뜻이 있습니다.

    참고 자료


    App Shortcuts | Android Developers

    좋은 웹페이지 즐겨찾기