Skip to main content

Home/ Android Dev/ Group items tagged code

Rss Feed Group items tagged

Vincent Tsao

The CommonsBlog - Activity or Notification via Ordered Broadcast - 0 views

  • I’ve run into the following generalized question a lot recently: I have an event that occurs in the background. I want to update my activity, if the activity is on the screen. Otherwise, I want to raise a Notification.
  • Hence, the recipe for the activity-or-Notification pattern is: Define an action string you will use when the event occurs that you want to go to the activity or notification (e.g., com.commonsware.java.packages.are.fun.EVENT). Dynamically register a BroadcastReceiever in your activity, with an IntentFilter set up for the aforementioned action string and with a positive priority (the default priority for a filter is 0). This receiver should then have the activity do whatever it needs to do to update the UI based on this event. The receiver should also call abortBroadcast() to prevent others from getting it. Be sure to register the receiver in onStart() or onResume() and unregister the receiver in the corresponding onStop or onPause() method. Register in your manifest a BroadcastReceiver, with an <intent-filter> set up for the aforementioned action string. This receiver should raise the Notification. In your service (e.g., an IntentService), when the event occurs, call sendOrderedBroadcast(). And that’s it. If the activity is on-screen, its receiver will be registered, so it will get the event, process it, and cancel the broadcast. If the activity is not on-screen, its receiver will not be registered, so the event will go to the default handler, in the form of your manifest-registered BroadcastReceiver, which will raise the Notification.
Vincent Tsao

[Android] Defining custom attrs - Stack Overflow - 0 views

  • You can define attributes in the top <resources> element or inside of a <declare-styleable> element. If I'm going to use an attr in more than one place I put it in the root element. Note, all attributes share the same global namespace. That means that even if you create a new attribute inside of a <declare-styleable> element it can be used outside of it and you cannot create another attribute with the same name of a different type.
  • An <attr> element has two xml attributes name and format. name lets you call it something and this is how you end up referring to it in code, e.g., R.attr.my_attribute. The format attribute can have different values depending on the 'type' of attribute you want. reference - if it references another resource id (e.g, "@color/my_color", "@layout/my_layout") color boolean dimension float integer string fraction enum - normally implicitly defined flag - normally implicitly defined You can set the format to multiple types by using |, e.g., format="reference|color".
    • Vincent Tsao
       
      了然~
Vincent Tsao

Notepad Exercise 3 | Android Developers - 0 views

  • onSaveInstanceState() is called by Android if the Activity is being stopped and may be killed before it is resumed! This means it should store any state necessary to re-initialize to the same condition when the Activity is restarted. It is the counterpart to the onCreate() method, and in fact the savedInstanceState Bundle passed in to onCreate() is the same Bundle that you construct as outState in the onSaveInstanceState() method.
  • Note that saveState() must be called in both onSaveInstanceState() and onPause() to ensure that the data is saved. This is because there is no guarantee that onSaveInstanceState() will be called and because when it is called, it is called before onPause().
Vincent Tsao

Onscreen Input Methods | Android Developers - 0 views

  • The android:inputType attribute has three pieces: The class is the overall interpretation of characters. The currently supported classes are text (plain text), number (decimal number), phone (phone number), and datetime (a date or time). The variation is a further refinement on the class. In the attribute you will normally specify the class and variant together, with the class as a prefix. For example, textEmailAddress is a text field where the user will enter something that is an e-mail address (foo@bar.com) so the key layout will have an '@' character in easy access, and numberSigned is a numeric field with a sign. If only the class is specified, then you get the default/generic variant. Additional flags can be specified that supply further refinement. These flags are specific to a class. For example, some flags for the text class are textCapSentences, textAutoCorrect, and textMultiline.
  •     <EditText android:id="@+id/edtInput"        android:layout_width="0dip"        android:layout_height="wrap_content"        android:layout_weight="1"        android:inputType="textShortMessage|textAutoCorrect|textCapSentences|textMultiLine"        android:imeOptions="actionSend|flagNoEnterAction"        android:maxLines="4"        android:maxLength="2000"        android:hint="@string/compose_hint"/>
Simon Pan

In-app Billing Overview | Android Developers - 1 views

  • nonce
    • Simon Pan
  • launches the pending intent
  • checkout flow finishes
  • ...22 more annotations...
  • sends your application a notification message
  • you must send a confirmation
  • will continue sending IN_APP_NOTIFY messages
  • should not
  • until you have delivered the item to the user.
  • will still receive an IN_APP_NOTIFY broadcast intent
  • must be able to handle IN_APP_NOTIFY messages
  • references a specific request ID
  • is installed
  • reinstalled.
  • even though you never initiated the purchase.
  • must handle
  • it usually stops sending IN_APP_NOTIFY intents
  • even though your application has sent a CONFIRM_NOTIFICATIONS message. This can occur if a device loses network connectivity while you are sending the CONFIRM_NOTIFICATIONS message.
  • You can do this by checking the orderID
  • even though your application has not sent a REQUEST_PURCHASE message.
  • may receive
  • informing the application that there is a purchase state change.
  • This applies only to items that have their purchase type set to "managed per user account."
  • signs the JSON string that is contained in the PURCHASE_STATE_CHANGED
  • it includes the signed JSON string (unencrypted) and the signature.
  • you can use the public key portion of your RSA key pair to verify the signature.
Vincent Tsao

How QR Codes Can Grow Your Business | Social Media Examiner - 1 views

  • Consumers want immediate access to what’s relevant and QR codes are being used to make that possible.
  • Bar codes are linear one-dimensional codes and can only hold up to 20 numerical digits, whereas QR codes are two-dimensional (2D) matrix barcodes that can hold thousands of alphanumeric characters of information. Their ability to hold more information and their ease of use makes them practical for small businesses.
  • When you scan or read a QR code with your iPhone, Android or other camera-enabled Smartphone, you can link to digital content on the web; activate a number of phone functions including email, IM and SMS; and connect the mobile device to a web browser.
  • ...4 more annotations...
  • There are other software companies that have created 2D codes that work much like QR codes, with Microsoft being the most notable.  Microsoft developed their own proprietary software to create codes known as MS tags.  Unlike QR codes, which can be read by a number of different readers, MS tags can only be read by the Microsoft Tag Reader.
  • Calls to Action – After building a community, the next logical step is to mobilize them to take action.   What are you trying to accomplish?  You can alternate special offers by simply linking your QR codes to new landing pages, and you can combine then with email opt-ins to build your list.
  • SEO and SMO – Earlier this month I wrote an article on social graphs where I discuss how web objects such as images, music clips, and videos add valuable content to your social graph.  QR codes enhance both your search engine and social media optimization.  Now you can increase traffic to those searchable objects to further optimize them by encouraging more sharing.
  • Social Proof – To help build a community offline, it can be helpful to use your vibrant online communities as social proof of your influence and expertise.  As one example, you can use QR codes to link to specific blog posts that have earned an abundance of activity.
Vincent Tsao

[筆記]讓Android emulator連intranet « 更夜 - 0 views

  • [通用部分] 如果開了一個以上的模擬器的話請自行加adb參數 0a. 先adb pull /system/etc/hosts hosts抓回local來修改。 0b. 在原本的 127.0.0.1 localhost 加上新的行,寫入你需要的對應如 192.168.1.15 mytestsite,存檔。 1. adb remount (才不會發生Read-only file system錯誤) 2. adb push hosts /system/etc/hosts
  • [2.0.1, 2.1 only] 這兩個版本會在這邊丟出錯誤訊息,分別為 failed to copy 'hosts' to '/system/etc/hosts': No space left on device failed to copy 'hosts' to '/system/etc/hosts': Out of memory 解決方法是,開啟模擬器時不要直接從 AVD Manager介面開,請下指令: $ emulator -avd youravdname -partition-size 128 接著再對這個模擬器使用上面的 hosts修改大法就不會出現錯誤了。 partition size的單位是MB,預設似乎是64。從adb shell 用 df 指令觀察的結果,/system 和 /data 都會被這個設定成這邊指定的值。而1.5, 1.6 的 image 因為剛好沒超過 64MB,還剩下一點空間,所以 hosts 還寫得進去,而 2.x 的 image 有 七萬多K,mount之後 /system 這個 partition 看起來就是全滿,剩下空間 0K。因此 hosts變肥後無法寫入,真的是因為partition爆了。事實上正常的手機確實也不需要留空間給user hack…模擬器還讓我們調參數已經很偷笑了,可惜AVD Manager 的 Start 沒地方可以設定 partition size。若有此需求的話只好麻煩一點手動下指定開emulator囉。
Vincent Tsao

Android Dev Phone, Ubuntu and VMWare Server : Johan de Koning - 0 views

  • Create a new file (as root) sudo gedit /etc/udev/rules.d/50-android.rules with the following content SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666" Make sure that the text after {idVendor} is the same as the device id found when using the lsusb command. Save and exit the editor To make execution of the rule possible, perform a chmod sudo chmod a+rx /etc/udev/rules.d/50-android.rules To make the rule active, restart udev sudo /etc/init.d/udev restart
  • You can perform a check, to see that the Android Dev Phone is shared with Ubuntu, by opening a Terminal (inside Ubuntu. Open a VMWare Remote Console to make use of the Ubuntu) and type the following command lsusb A list of USB devices will be shown. For example: Bus 002 Device 001: ID ld6b:0001 Linux Foundation 1.1 root hub Bus 001 Device 004: ID 0bb4:0c02 High Tech Computer Corp. Bus 001 Device 001: ID ld6b:0002 Linux Foundation 2.0 root hub
Vincent Tsao

Window Backgrounds & UI Speed | Android Developers - 0 views

  • Removing the window's background can be achieved very easily by using a custom theme. To do so, first create a file called res/values/theme.xml containing the following:
  • <resources>    <style name="Theme.NoBackground" parent="android:Theme">        <item name="android:windowBackground">@null</item>    </style></resources>
  • You then need to apply the theme to your activity by adding the attribute android:theme="@style/Theme.NoBackground" to your <activity /> or <application /> tag. This trick comes in very handy for any app that uses a MapView, a WebView or any other full screen opaque view.
Vincent Tsao

Avoiding Memory Leaks | Android Developers - 0 views

  • As part of my job, I ran into memory leaks issues in Android applications and they are most of the time due to the same mistake: keeping a long-lived reference to a Context.
  • There are two easy ways to avoid context-related memory leaks. The most obvious one is to avoid escaping the context outside of its own scope. The example above showed the case of a static reference but inner classes and their implicit reference to the outer class can be equally dangerous. The second solution is to use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle. If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().
  • In summary, to avoid context-related memory leaks, remember the following: Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself) Try using the context-application instead of a context-activity Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance A garbage collector is not an insurance against memory leaks
Vincent Tsao

Fragments | Android Developers - 1 views

  • If you add multiple changes to the transaction (such as another add() or remove()) and call addToBackStack(), then all changes applied before you call commit() are added to the back stack as a single transaction and the BACK key will reverse them all together.
    • Vincent Tsao
       
      what's the point to provide such  mechanism?
  • The most significant difference in lifecycle between an activity and a fragment is how one is stored in its respective back stack. An activity is placed into a back stack of activities that's managed by the system when it's stopped, by default (so that the user can navigate back to it with the BACK key, as discussed in Tasks and Back Stack). However, a fragment is placed into a back stack managed by the host activity only when you explicitly request that the instance be saved by calling addToBackStack() during a transaction that removes the fragment.
  • In some cases, you might need a fragment to share events with the activity. A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.
  •  
    好特別、好酷的一個類
Vincent Tsao

commonsguy/cwac-merge - GitHub - 2 views

  • MergeAdapter accepts a mix of Adapters and Views and presents them as one contiguous whole to whatever ListView it is poured into. This is good for cases where you have multiple data sources, or if you have a handful of ordinary Views to mix in with lists of data, or the like.
Vincent Tsao

java - remove notification bar shadow in android app - Stack Overflow - 0 views

  • <!-- Variation on the Light theme that turns off the title --><style name="Theme.IOSched" parent="android:style/Theme.Light">    <item name="android:windowNoTitle">true</item>    <item name="android:windowContentOverlay">@null</item></style>
  • The android:windowContentOverlay is your shadow, and setting it to @null in your theme will eliminate it. You can see this in action in the Google I|O 2010 conference app, which uses many of the same UI conventions as does the new Twitter app. However, right now, the Twitter app has not yet been open-sourced, which is why I point you to the I|O app. The code fragment above is from that app's styles.xml resource.
Simon Pan

App Widgets | Android Developers - 1 views

  • To find your minimum width and height in density-independent pixels (dp), use this formula: (number of cells * 74) - 2
    • Simon Pan
       
      why i can't highlight?
    • Vincent Tsao
       
      FYI: You may need a toolbar to highlight, http://www.diigo.com/tools/toolbar
  • how often the App Widget framework should request an update from the AppWidgetProvider by calling the onUpdate() method
  • exactly on time
  • ...6 more annotations...
  • programmatically interface with the App Widget, based on broadcast events.
  • programmatically interface with the App Widget, based on broadcast events.
  • programmatically interface with the App Widget, based on broadcast events.
  • only the event broadcasts
  • when each App Widget is added to a host
  • it includes a loop that iterates through each entry in appWidgetIds,
Vincent Tsao

Android Endless List - Stack Overflow - 0 views

  • 5 down vote accepted One solution is to implement an OnScrollListener and make changes (like adding items, etc.) to the ListAdapter at a convenient state in its onScrollStateChanged method. The following ListActivity shows a list of integers, starting with 40, adding 10 per scroll-stop.
  • public class Test extends ListActivity implements OnScrollListener {    Aleph0 adapter = new Aleph0();    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setListAdapter(adapter);         getListView().setOnScrollListener(this);    }    public void onScroll(AbsListView v, int i, int j, int k) { }    public void onScrollStateChanged(AbsListView v, int state) {        if(state == OnScrollListener.SCROLL_STATE_IDLE) {                adapter.count += 10;                adapter.notifyDataSetChanged();        }    }    class Aleph0 extends BaseAdapter {        int count = 40;        public int getCount() { return count; }        public Object getItem(int pos) { return pos; }        public long getItemId(int pos) { return pos; }        public View getView(int pos, View v, ViewGroup p) {                TextView view = new TextView(Test.this);                view.setText("entry " + pos);                return view;        }    }}
  • You should obviously use separate threads for long running actions (like loading web-data) and might want to indicate progress in the last list item (like the market or gmail apps do).
Vincent Tsao

Implementing "Pull To Refresh" in your Android App | Blog // Recursive Awesome // Table... - 1 views

  • For completeness we really should handle the possibility of the task getting cancelled. This can happen when the user navigates away from the app and the task is killed before its completed. This will cause the onPostExecute() method to not be called and so the onRefreshComplete() method won’t be called. Depending on how the user navigates through the app, they could return to this activity without going through the complete onCreate() lifecycle, and you’ll end up with the screen still showing the “loading” progress message in the header. This is common when using tabs between multiple ListViews. Also, the documented best practices for implementing an AsyncTask says that in long running background work you should periodically check if the task has been cancelled and try to gracefully quit your work and exit. So let’s get all of that in there.
Vincent Tsao

AndroidDevBlog » Clean and user-friendly UIs with ActionBar - 0 views

  • The concept of ActionBar has been introduced with the Twitter application for Android. More recently, we have seen this widget in the Google I/O 2010 schedule application. To sum up, an ActionBar can be considered as an advanced title bar that is capable of: containing several ActionBaritems (similar to buttons) being styled so that the general look’n'feel of the application is in accordance with the underlying brand/visual identity containing a title to show the user a summary of the screen content featuring several user interaction pattern.
Vincent Tsao

Application does not show up in Android Market for Motorola XOOM tablet - Stack Overflow - 0 views

  • I had the same issue. Along with including android:xlargeScreens="true" I found this to be the fix.
  • The Android Market treats as though requesting a permission like CALL_PHONE also requests: <uses-feature android:name="android.hardware.telephony" /> The XOOM does not have telephony — the first Android Market-compliant device with that limitation. While it can have a data plan, it has no voice or SMS capability, and so it is treated as not having android.hardware.telephony. But, if you request permissions like CALL_PHONE, the Android Market by default will assume you need android.hardware.telephony. As a result, you will be filtered out of the Market for the XOOM. The solution is simple: for any hardware features that might be implied by permissions but that you do not absolutely need, manually add the appropriate element to your manifest with android:required="false": <uses-feature android:name="android.hardware.telephony" android:required="false" />
Simon Pan

Custom Drawing | Android Developers - 1 views

  • Creating objects ahead of time is an important optimization. Views are redrawn very frequently, and many drawing objects require expensive initialization. Creating drawing objects within your onDraw() method significantly reduces performance and can make your UI appear sluggish.
    • Simon Pan
       
      將物件在初始化時就實例化是很重要的概念,onDraw()的運作速度很快,如困每一個Paint畫圖物件都臨時才在onDraw()產生,將會大幅下降整体程式的流暢效能。
  • If your view doesn't need special control over its size, you only need to override one method: onSizeChanged().
  • is mandatory.
Simon Pan

Service | Android Developers - 0 views

  • avoid
    • Simon Pan
       
      如果在Service裡做了要做的事,它們還是在UI thread裡做事情,而不是在什麼別的thread做事情。但是Service很特別,它又不是一個執行緒,因為通常Service要做的事情都蠻耗時的,萬一Service算是執行緒,那麼就會強碰到系統的ANR機制。
  • A facility for the application to tell the system about something it wants to be doing in the background
  • A facility for an application to expose some of its functionality to other applications.
  • ...3 more annotations...
  • two reasons
  • depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed,
  • then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent).
1 - 20 of 103 Next › Last »
Showing 20 items per page