summaryrefslogtreecommitdiffstats
path: root/src/com/android/nfc/NfcDispatcher.java
blob: 8c359a74a977b6ba21a62c4b40167700abb0048f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.nfc;

import com.android.nfc.RegisteredComponentCache.ComponentInfo;

import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.RemoteException;
import android.util.Log;

import java.nio.charset.Charsets;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Dispatch of NFC events to start activities
 */
public class NfcDispatcher {
    public static final byte[] RTD_ANDROID_APP = "android.com:pkg".getBytes();
    private static final boolean DBG = NfcService.DBG;
    private static final String TAG = NfcService.TAG;

    private final Context mContext;
    private final NdefP2pManager mP2pManager;
    private final IActivityManager mIActivityManager;
    private final RegisteredComponentCache mTechListFilters;

    // Locked on this
    private PendingIntent mOverrideIntent;
    private IntentFilter[] mOverrideFilters;
    private String[][] mOverrideTechLists;

    public NfcDispatcher(Context context, NdefP2pManager p2pManager) {
        mContext = context;
        mP2pManager = p2pManager;
        mIActivityManager = ActivityManagerNative.getDefault();
        mTechListFilters = new RegisteredComponentCache(mContext,
                NfcAdapter.ACTION_TECH_DISCOVERED, NfcAdapter.ACTION_TECH_DISCOVERED);
    }

    public synchronized void disableForegroundDispatch() {
        if (DBG) Log.d(TAG, "Disable Foreground Dispatch");
        mOverrideIntent = null;
        mOverrideFilters = null;
        mOverrideTechLists = null;
    }

    public synchronized void enableForegroundDispatch(PendingIntent intent,
            IntentFilter[] filters, String[][] techLists) {
        if (DBG) Log.d(TAG, "Enable Foreground Dispatch");
        mOverrideIntent = intent;
        mOverrideFilters = filters;
        mOverrideTechLists = techLists;
    }

    /** Returns false if no activities were found to dispatch to */
    public boolean dispatchTag(Tag tag, NdefMessage[] msgs) {
        if (DBG) {
            Log.d(TAG, "Dispatching tag");
            Log.d(TAG, tag.toString());
        }

        IntentFilter[] overrideFilters;
        PendingIntent overrideIntent;
        String[][] overrideTechLists;
        boolean foregroundNdefPush = mP2pManager.getForegroundMessage() != null;
        synchronized (this) {
            overrideFilters = mOverrideFilters;
            overrideIntent = mOverrideIntent;
            overrideTechLists = mOverrideTechLists;
        }

        // First look for dispatch overrides
        if (overrideIntent != null) {
            if (DBG) Log.d(TAG, "Attempting to dispatch tag with override");
            try {
                if (dispatchTagInternal(tag, msgs, overrideIntent, overrideFilters,
                        overrideTechLists)) {
                    if (DBG) Log.d(TAG, "Dispatched to override");
                    return true;
                }
                Log.w(TAG, "Dispatch override registered, but no filters matched");
            } catch (CanceledException e) {
                Log.w(TAG, "Dispatch overrides pending intent was canceled");
                synchronized (this) {
                    mOverrideFilters = null;
                    mOverrideIntent = null;
                    mOverrideTechLists = null;
                }
            }
        }

        // If there is not foreground NDEF push setup try a normal dispatch.
        //
        // This is avoided when disabled in the NDEF push case to avoid the situation where each
        // user has a different app in the foreground, causing each to launch itself on the
        // remote device and the apps swapping which is in the foreground on each phone.
        if (!foregroundNdefPush) {
            try {
                return dispatchTagInternal(tag, msgs, null, null, null);
            } catch (CanceledException e) {
                Log.e(TAG, "CanceledException unexpected here", e);
                return false;
            }
        }

        return false;
    }

    private Intent buildTagIntent(Tag tag, NdefMessage[] msgs, String action) {
        Intent intent = new Intent(action);
        intent.putExtra(NfcAdapter.EXTRA_TAG, tag);
        intent.putExtra(NfcAdapter.EXTRA_ID, tag.getId());
        intent.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES, msgs);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    // Dispatch to either an override pending intent or a standard startActivity()
    private boolean dispatchTagInternal(Tag tag, NdefMessage[] msgs,
            PendingIntent overrideIntent, IntentFilter[] overrideFilters,
            String[][] overrideTechLists)
            throws CanceledException{
        Intent intent;

        //
        // Try the NDEF content specific dispatch
        //
        if (msgs != null && msgs.length > 0) {
            NdefMessage msg = msgs[0];
            NdefRecord[] records = msg.getRecords();
            if (records.length > 0) {
                // Found valid NDEF data, try to dispatch that first
                NdefRecord record = records[0];

                intent = buildTagIntent(tag, msgs, NfcAdapter.ACTION_NDEF_DISCOVERED);
                if (setTypeOrDataFromNdef(intent, record)) {
                    // The record contains filterable data, try to start a matching activity
                    if (startDispatchActivity(intent, overrideIntent, overrideFilters,
                            overrideTechLists, records)) {
                        // If an activity is found then skip further dispatching
                        return true;
                    } else {
                        if (DBG) Log.d(TAG, "No activities for NDEF handling of " + intent);
                    }
                }
            }
        }

        //
        // Try the technology specific dispatch
        //
        String[] tagTechs = tag.getTechList();
        Arrays.sort(tagTechs);

        if (overrideIntent != null) {
            // There are dispatch overrides in place
            if (overrideTechLists != null) {
                for (String[] filterTechs : overrideTechLists) {
                    if (filterMatch(tagTechs, filterTechs)) {
                        // An override matched, send it to the foreground activity.
                        intent = buildTagIntent(tag, msgs,
                                NfcAdapter.ACTION_TECH_DISCOVERED);
                        overrideIntent.send(mContext, Activity.RESULT_OK, intent);
                        return true;
                    }
                }
            }
        } else {
            // Standard tech dispatch path
            ArrayList<ResolveInfo> matches = new ArrayList<ResolveInfo>();
            ArrayList<ComponentInfo> registered = mTechListFilters.getComponents();
            PackageManager pm = mContext.getPackageManager();

            // Check each registered activity to see if it matches
            for (ComponentInfo info : registered) {
                // Don't allow wild card matching
                if (filterMatch(tagTechs, info.techs) &&
                        isComponentEnabled(pm, info.resolveInfo)) {
                    // Add the activity as a match if it's not already in the list
                    if (!matches.contains(info.resolveInfo)) {
                        matches.add(info.resolveInfo);
                    }
                }
            }

            if (matches.size() == 1) {
                // Single match, launch directly
                intent = buildTagIntent(tag, msgs, NfcAdapter.ACTION_TECH_DISCOVERED);
                ResolveInfo info = matches.get(0);
                intent.setClassName(info.activityInfo.packageName, info.activityInfo.name);
                try {
                    mContext.startActivity(intent);
                    return true;
                } catch (ActivityNotFoundException e) {
                    if (DBG) Log.w(TAG, "No activities for technology handling of " + intent);
                }
            } else if (matches.size() > 1) {
                // Multiple matches, show a custom activity chooser dialog
                intent = new Intent(mContext, TechListChooserActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(Intent.EXTRA_INTENT,
                        buildTagIntent(tag, msgs, NfcAdapter.ACTION_TECH_DISCOVERED));
                intent.putParcelableArrayListExtra(TechListChooserActivity.EXTRA_RESOLVE_INFOS,
                        matches);
                try {
                    mContext.startActivity(intent);
                    return true;
                } catch (ActivityNotFoundException e) {
                    if (DBG) Log.w(TAG, "No activities for technology handling of " + intent);
                }
            } else {
                // No matches, move on
                if (DBG) Log.w(TAG, "No activities for technology handling");
            }
        }

        //
        // Try the generic intent
        //
        intent = buildTagIntent(tag, msgs, NfcAdapter.ACTION_TAG_DISCOVERED);
        if (startDispatchActivity(intent, overrideIntent, overrideFilters, overrideTechLists,
                null)) {
            return true;
        } else {
            Log.e(TAG, "No tag fallback activity found for " + intent);
            return false;
        }
    }

    private boolean startDispatchActivity(Intent intent, PendingIntent overrideIntent,
            IntentFilter[] overrideFilters, String[][] overrideTechLists, NdefRecord[] records)
            throws CanceledException {
        if (overrideIntent != null) {
            boolean found = false;
            if (overrideFilters == null && overrideTechLists == null) {
                // No filters means to always dispatch regardless of match
                found = true;
            } else if (overrideFilters != null) {
                for (IntentFilter filter : overrideFilters) {
                    if (filter.match(mContext.getContentResolver(), intent, false, TAG) >= 0) {
                        found = true;
                        break;
                    }
                }
            }

            if (found) {
                Log.i(TAG, "Dispatching to override intent " + overrideIntent);
                overrideIntent.send(mContext, Activity.RESULT_OK, intent);
                return true;
            } else {
                return false;
            }
        } else {
            try {
                // If the current app called stopAppSwitches() then our startActivity()
                // can be delayed for several seconds. This happens with the default home
                // screen. As a system service we can override this behavior with
                // resumeAppSwitches()
                mIActivityManager.resumeAppSwitches();
            } catch (RemoteException e) { }
            if (records != null) {
                String firstPackage = null;
                for (NdefRecord record : records) {
                    if (record.getTnf() == NdefRecord.TNF_EXTERNAL_TYPE) {
                        if (Arrays.equals(record.getType(), RTD_ANDROID_APP)) {
                            String pkg = new String(record.getPayload(), Charsets.US_ASCII);
                            if (firstPackage == null) {
                                firstPackage = pkg;
                            }
                            intent.setPackage(pkg);
                            try {
                                mContext.startActivity(intent);
                                return true;
                            } catch (ActivityNotFoundException e) {
                                // Continue; there may be another match.
                            }
                        }
                    }
                }
                if (firstPackage != null) {
                    // Found an Android package, but could not handle ndef intent.
                    // If the application is installed, call its main activity.
                    try {
                        Intent main = new Intent(Intent.ACTION_MAIN);
                        main.addCategory(Intent.CATEGORY_LAUNCHER);
                        main.setPackage(firstPackage);
                        mContext.startActivity(main);
                        return true;
                    } catch (ActivityNotFoundException e) {
                        Intent market = getAppSearchIntent(firstPackage);
                        mContext.startActivity(market);
                        return true;
                    }
                }
            }
            try {
                mContext.startActivity(intent);
                return true;
            } catch (ActivityNotFoundException e) {
                return false;
            }
        }
    }

    /** Returns true if the tech list filter matches the techs on the tag */
    private boolean filterMatch(String[] tagTechs, String[] filterTechs) {
        if (filterTechs == null || filterTechs.length == 0) return false;

        for (String tech : filterTechs) {
            if (Arrays.binarySearch(tagTechs, tech) < 0) {
                return false;
            }
        }
        return true;
    }

    private boolean setTypeOrDataFromNdef(Intent intent, NdefRecord record) {
        short tnf = record.getTnf();
        byte[] type = record.getType();
        try {
            switch (tnf) {
                case NdefRecord.TNF_MIME_MEDIA: {
                    intent.setType(new String(type, Charsets.US_ASCII));
                    return true;
                }

                case NdefRecord.TNF_ABSOLUTE_URI: {
                    intent.setData(Uri.parse(new String(type, Charsets.UTF_8)));
                    return true;
                }

                case NdefRecord.TNF_WELL_KNOWN: {
                    byte[] payload = record.getPayload();
                    if (payload == null || payload.length == 0) return false;
                    if (Arrays.equals(type, NdefRecord.RTD_TEXT)) {
                        intent.setType("text/plain");
                        return true;
                    } else if (Arrays.equals(type, NdefRecord.RTD_SMART_POSTER)) {
                        // Parse the smart poster looking for the URI
                        try {
                            NdefMessage msg = new NdefMessage(record.getPayload());
                            for (NdefRecord subRecord : msg.getRecords()) {
                                short subTnf = subRecord.getTnf();
                                if (subTnf == NdefRecord.TNF_WELL_KNOWN
                                        && Arrays.equals(subRecord.getType(),
                                                NdefRecord.RTD_URI)) {
                                    intent.setData(NdefRecord.parseWellKnownUriRecord(subRecord));
                                    return true;
                                } else if (subTnf == NdefRecord.TNF_ABSOLUTE_URI) {
                                    intent.setData(Uri.parse(new String(subRecord.getType(),
                                            Charsets.UTF_8)));
                                    return true;
                                }
                            }
                        } catch (FormatException e) {
                            return false;
                        }
                    } else if (Arrays.equals(type, NdefRecord.RTD_URI)) {
                        intent.setData(NdefRecord.parseWellKnownUriRecord(record));
                        return true;
                    }
                    return false;
                }

                case NdefRecord.TNF_EXTERNAL_TYPE: {
                    intent.setData(Uri.parse("vnd.android.nfc://ext/" +
                            new String(record.getType(), Charsets.US_ASCII)));
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "failed to parse record", e);
            return false;
        }
    }

    /**
     * Returns an intent that can be used to find an application not currently
     * installed on the device.
     */
    private static Intent getAppSearchIntent(String pkg) {
        Intent market = new Intent(Intent.ACTION_VIEW);
        market.setData(Uri.parse("market://details?id=" + pkg));
        return market;
    }

    private static boolean isComponentEnabled(PackageManager pm, ResolveInfo info) {
        boolean enabled = false;
        ComponentName compname = new ComponentName(
                info.activityInfo.packageName, info.activityInfo.name);
        try {
            // Note that getActivityInfo() will internally call
            // isEnabledLP() to determine whether the component
            // enabled. If it's not, null is returned.
            if (pm.getActivityInfo(compname,0) != null) {
                enabled = true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            enabled = false;
        }
        if (!enabled) {
            Log.d(TAG, "Component not enabled: " + compname);
        }
        return enabled;
    }
}