Improved tag writing support.
Jeff Hamilton [Sun, 23 Jan 2011 22:57:33 +0000 (16:57 -0600)]
Now you go to an activity that prompts
you to scan a tag to write to it and
prints out the status when a tag is
scanned.

Still hidden on user builds since the
UI is really rough and has a lot of
known issues.

Change-Id: I56edccb80b3ab599c849e23f4ec5897a0cc97090

AndroidManifest.xml
res/layout/write_tag.xml [new file with mode: 0644]
src/com/android/apps/tag/MyTagList.java
src/com/android/apps/tag/TagViewer.java
src/com/android/apps/tag/WriteTagActivity.java [new file with mode: 0644]

index 56cfd03..5ec59fe 100644 (file)
             android:screenOrientation="portrait"
         />
 
+        <activity android:name="WriteTagActivity"
+            android:launchMode="singleTop"
+            android:screenOrientation="portrait"
+        />
+
         <service android:name="TagService" />
 
         <provider android:name=".provider.TagProvider"
diff --git a/res/layout/write_tag.xml b/res/layout/write_tag.xml
new file mode 100644 (file)
index 0000000..fc4ea53
--- /dev/null
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+Copyright (C) 2010 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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:orientation="vertical"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+>
+    <TextView android:id="@+id/title"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="8dip"
+
+        android:gravity="center_horizontal"
+        android:textAppearance="?android:attr/textAppearanceLarge"
+    />
+
+    <ImageView
+        android:layout_width="match_parent"
+        android:layout_height="0dip"
+        android:layout_weight="1"
+
+        android:src="@drawable/ic_launcher_nfc"
+        android:gravity="center"
+        android:scaleType="center"
+    />
+
+    <TextView android:id="@+id/count"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+
+        android:gravity="center_horizontal"
+        android:textAppearance="?android:attr/textAppearanceMedium"
+    />
+
+    <TextView android:id="@+id/status"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginBottom="16dip"
+
+        android:gravity="center_horizontal"
+        android:textAppearance="?android:attr/textAppearanceMedium"
+    />
+</LinearLayout>
+
index 06d4db7..80e04e4 100644 (file)
@@ -394,7 +394,7 @@ public class MyTagList
         mTagIdLongPressed = id;
 
         if (mWriteSupport) {
-            menu.add(0, 1, 0, "Write to next tag scanned");
+            menu.add(0, 1, 0, "Write to tag");
         }
     }
 
@@ -433,8 +433,9 @@ public class MyTagList
                     break;
                 }
 
-                SharedPreferences prefs = getSharedPreferences("tags.pref", Context.MODE_PRIVATE);
-                prefs.edit().putLong(PREF_KEY_TAG_TO_WRITE, info.id).apply();
+                Intent intent = new Intent(this, WriteTagActivity.class);
+                intent.putExtra("id", info.id);
+                startActivity(intent);
                 return true;
         }
         return false;
index 4b22ed5..fd3fe2e 100644 (file)
@@ -183,18 +183,6 @@ public class TagViewer extends Activity implements OnClickListener {
                 }
             }
 
-            // Check to see if there's a tag queued up for writing.
-            SharedPreferences prefs = getSharedPreferences("tags.pref", Context.MODE_PRIVATE);
-            long tagToWrite = prefs.getLong(MyTagList.PREF_KEY_TAG_TO_WRITE, 0);
-            prefs.edit().putLong(MyTagList.PREF_KEY_TAG_TO_WRITE, 0).apply();
-            if (tagToWrite != 0) {
-                if (writeTag((Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG), tagToWrite)) {
-                    Toast.makeText(this, "Tag written", Toast.LENGTH_SHORT).show();
-                    finish();
-                    return;
-                }
-            }
-
             // When a tag is discovered we send it to the service to be save. We
             // include a PendingIntent for the service to call back onto. This
             // will cause this activity to be restarted with onNewIntent(). At
@@ -269,51 +257,6 @@ public class TagViewer extends Activity implements OnClickListener {
         }
     }
 
-    private boolean writeTag(Tag tag, long id) {
-        try {
-            Cursor cursor = getContentResolver().query(
-                    ContentUris.withAppendedId(NdefMessages.CONTENT_URI, id),
-                    new String[] { NdefMessages.BYTES }, null, null, null);
-            if (cursor == null || !cursor.moveToFirst()) {
-                return false;
-            }
-
-            byte[] bytes = cursor.getBlob(0);
-            cursor.close();
-            NdefMessage msg = new NdefMessage(bytes);
-
-            Ndef ndef = Ndef.get(tag);
-            if (ndef != null) {
-                ndef.connect();
-                if (!ndef.isWritable()) {
-                    Toast.makeText(this, "Tag is read-only, not writing", Toast.LENGTH_SHORT)
-                            .show();
-                    return false;
-                }
-                ndef.writeNdefMessage(msg);
-                Toast.makeText(this, "Wrote message to pre-formatted tag", Toast.LENGTH_SHORT)
-                        .show();
-                return true;
-            } else {
-                NdefFormatable format = NdefFormatable.get(tag);
-                if (format != null) {
-                    format.connect();
-                    format.format(msg);
-                    Toast.makeText(this, "Formatted tag and wrote message", Toast.LENGTH_SHORT)
-                            .show();
-                    return true;
-                }
-            }
-        } catch (Exception e) {
-            Log.e(TAG, "Failed to write tag", e);
-        }
-
-        Toast.makeText(this, "Failed to write tag", Toast.LENGTH_SHORT)
-                .show();
-
-        return false;
-    }
-
     void buildTagViews(NdefMessage[] msgs) {
         if (msgs == null || msgs.length == 0) {
             return;
diff --git a/src/com/android/apps/tag/WriteTagActivity.java b/src/com/android/apps/tag/WriteTagActivity.java
new file mode 100644 (file)
index 0000000..d82d042
--- /dev/null
@@ -0,0 +1,188 @@
+/*
+ * 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.apps.tag;
+
+import com.android.apps.tag.provider.TagContract.NdefMessages;
+
+import android.app.Activity;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.Cursor;
+import android.graphics.Color;
+import android.nfc.FormatException;
+import android.nfc.NdefMessage;
+import android.nfc.NfcAdapter;
+import android.nfc.Tag;
+import android.nfc.tech.Ndef;
+import android.nfc.tech.NdefFormatable;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.util.Log;
+import android.widget.TextView;
+
+import java.io.IOException;
+
+public class WriteTagActivity extends Activity {
+    static final String TAG = WriteTagActivity.class.getName();
+
+    NfcAdapter mAdapter;
+    PendingIntent mPendingIntent;
+    TextView mTitle;
+    TextView mStatus;
+    TextView mCountView;
+    NdefMessage mMessage;
+    int mSize;
+    int mCount = 1;
+
+    final class MessageLoaderTask extends AsyncTask<String, Void, Cursor> {
+        @Override
+        public Cursor doInBackground(String... args) {
+            Cursor cursor = getContentResolver().query(
+                    NdefMessages.CONTENT_URI,
+                    new String[] { NdefMessages.TITLE, NdefMessages.BYTES },
+                    NdefMessages._ID + "=?",
+                    new String[] { args[0] }, null);
+
+            // Ensure the cursor executes and fills its window
+            if (cursor != null) cursor.getCount();
+            return cursor;
+        }
+
+        @Override
+        protected void onPostExecute(Cursor cursor) {
+            try {
+                if (cursor == null || !cursor.moveToFirst()) {
+                    setStatus("Failed to load tag for writing.", false);
+                    return;
+                }
+                byte[] blob = cursor.getBlob(1);
+                mSize = blob.length;
+                mMessage = new NdefMessage(blob);
+                mTitle.setText("Scan a tag to write\n" + cursor.getString(0));
+            } catch (FormatException e) {
+                setStatus("Invalid tag.", false);
+            } finally {
+                if (cursor != null) cursor.close();
+            }
+        }
+    }
+
+    @Override
+    public void onCreate(Bundle savedState) {
+        super.onCreate(savedState);
+
+        setContentView(R.layout.write_tag);
+        mTitle = (TextView) findViewById(R.id.title);
+        mStatus = (TextView) findViewById(R.id.status);
+        mCountView = (TextView) findViewById(R.id.count);
+
+        Bundle extras = getIntent().getExtras();
+        if (extras == null || !extras.containsKey("id")) {
+            setStatus("Nothing to write.", true);
+            return;
+        }
+
+        mTitle.setText("Loading tag.");
+        long id = extras.getLong("id");
+        new MessageLoaderTask().execute(Long.toString(id));
+
+        mAdapter = NfcAdapter.getDefaultAdapter(this);
+
+        // Create a generic PendingIntent that will be deliver to this activity. The NFC stack
+        // will fill in the intent with the details of the discovered tag before delivering to
+        // this activity.
+        mPendingIntent = PendingIntent.getActivity(this, 0,
+                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+        mAdapter.enableForegroundDispatch(this, mPendingIntent, (IntentFilter[]) null);
+    }
+
+    @Override
+    public void onNewIntent(Intent intent) {
+        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
+        mCountView.setText("Tag " + mCount++);
+        if (mMessage != null) {
+            writeTag(tag);
+        } else {
+            setStatus("Not ready to write.", false);
+        }
+    }
+
+    @Override
+    public void onPause() {
+        super.onPause();
+        mAdapter.disableForegroundDispatch(this);
+    }
+
+    void setStatus(String message, boolean success) {
+        mStatus.setText(message);
+        if (!success) {
+            mStatus.setTextColor(Color.RED);
+        } else {
+            mStatus.setTextColor(Color.GREEN);
+        }
+    }
+
+    boolean writeTag(Tag tag) {
+        try {
+            Ndef ndef = Ndef.get(tag);
+            if (ndef != null) {
+                ndef.connect();
+
+                if (!ndef.isWritable()) {
+                    setStatus("Tag is read-only.", false);
+                    return false;
+                }
+                if (ndef.getMaxSize() < mSize) {
+                    setStatus("Tag capacity is " + ndef.getMaxSize() + " bytes, message is " +
+                            mSize + " bytes.", false);
+                    return false;
+                }
+
+                ndef.writeNdefMessage(mMessage);
+                setStatus("Wrote message to pre-formatted tag.", true);
+                return true;
+            } else {
+                NdefFormatable format = NdefFormatable.get(tag);
+                if (format != null) {
+                    try {
+                        format.connect();
+                        format.format(mMessage);
+                        setStatus("Formatted tag and wrote message.", true);
+                        return true;
+                    } catch (IOException e) {
+                        setStatus("Failed to format tag.", false);
+                        return false;
+                    }
+                } else {
+                    setStatus("Tag doesn't support NDEF.", false);
+                    return false;
+                }
+            }
+        } catch (Exception e) {
+            Log.e(TAG, "Failed to write tag", e);
+        }
+
+        setStatus("Failed to write tag", false);
+        return false;
+    }
+}