Android: Difference between revisions

From 太極
Jump to navigation Jump to search
Line 134: Line 134:
* Head First Object-Oriented Analysis and Design
* Head First Object-Oriented Analysis and Design
* Head First Design Patterns
* Head First Design Patterns
== Material Design ==
* [http://www.google.com/design/spec/style/typography.html# Style -> Typography]


= Useful Apps =
= Useful Apps =

Revision as of 13:43, 7 June 2015

SDK

http://developer.android.com/sdk/index.html#ExistingIDE

Redhat

At the step of Running your app I cannot run app from Eclipse. The command line way does not work.After several tries, it seems the RHEL does not have an updated Ant package (currently it is 1.7 but I need 1.8). Give up.

Ubuntu

Download the bundle version. The file name I got is <adt-bundle-linux-x86_64-20140321.zip>.

On 64-bit Ubuntu, we need to run

sudo apt-get install libstdc++6:i386 lib32z1 lib32ncurses5 lib32bz2-1.0

For both 32-bit and 64-bit, we need to get openjdk

sudo apt-get install openjdk-6-jre openjdk-6-jdk icedtea6-plugin

Then uncompress <adt-bundle-linux-xxx.zip> and run the file <eclipse> from either file manager or command line. It just works!

We can furthermore set up the PATH variable by editing ~/.bashrc file.

export PATH=$PATH:~/binary/adt-bundle-linux-x86_64-20140321/sdk/platform-tools/
export PATH=$PATH:~/binary/adt-bundle-linux-x86_64-20140321/sdk/tools/
export PATH=$PATH:~/binary/android-ndk-r9d/

Then source the file by

source ~/.bashrc

A good reference is https://help.ubuntu.com/community/AndroidSDK.

To quickly test NDK, go to the samples/hello-jni directory in NDK. Type the command ndk-build. If the build is successful, it proves that the NDK environment is set up correctly.

Windows

Genymotion

Genymotion is a complete set of tools that provides a virtual environment for Android. Genymotion is much better than the ADV included in Android SDK. Before we use download/use it, we need to register.

For some reason, on my Ubuntu 12.04, I need to run the following.

sudo apt-get install ia32-libs

The genymotion can be integrated into Eclipse. The document about genymotion can be found on https://cloud.genymotion.com/page/doc/

Qt + Android

Installation

We can install requirements of Qt 5 by

  • SDK -> No need to download a special copy. Just use adt-bundle-linux-x86-2013xxxx one.
  • Apache Ant -> sudo apt-get install ant
  • NDK -> android-ndk-r9c-linux-x86.tar.bz2. Use tar -xjvf android-ndk-r9c-linux-x86.tar.bz2 to extract.
  • Download qt-linux-opensource-5.2.0-android-x86-offline.run and install it into a new location, eg ~/Qt5.2.0Android (Cannot be the same as Desktop version).
  • On a new machine, we need to install opengl library as instructed here and here.
sudo apt-get install mesa-common-dev
sudo apt-get install libglu1-mesa-dev -y

The Qt needs to change the setting from Tools > Options > Android where we can specify the locations of Android SDK, Android NDK, Ant and JDK. On Tools > Options > Devices, we can change the Device from default (Local PC) to Run on Android. See the instruction on qt.project.org. Basically we go to project's setting to do changes. It does take a little longer to get the app on device.

Test Installation

We use qt-opensource-linux-x64-android-5.2.1.run to install Qt to ~/qt-5.2.1-Android directory. Note that this installer includes Qt Creator which has preset options. So this is preferred than our other separated installed Qt Creator.

We shall also need to follow episode 3 to set up SDK, NDK, JDK and Ant directories in Qt Creator.

After that, we can create a default Qt Quick application. Before we Run Debugging, we shall also

  • Change project's setting to make sure Android for armeabi-v7a Kit is added to the project.
  • Connect a physical Android device to our computer.

If everything goes well, the Qt app will be deployed to the connected Android device.

If we want to specify the API level, we can select Project > Run > Details > Deploy configurations. See http://qt-project.org/doc/qtcreator-3.0/creator-deploying-android.html

More QML examples can be found in http://qt-project.org/doc/qt-4.7/qdeclarativeexamples.html

Two official Android examples (Quick Forecast & Flyingbus)can be found at https://blog.qt.digia.com/blog/2013/12/10/cross-platform-applications-in-ios-and-android-stores-with-qt/

Help, Applications

NDK

Following are steps to create Android App with NDK.

  1. Create a new folder: jni
  2. Create a new file under jni: <hello.c>
  3. Create a new file under jni: <Android.mk>
  4. Open a shell & go to jni folder. Type ndk-build to generate .so files
  5. Edit <MainActivity.java>
  6. Run as Android Application.

The "hello-jni" is the hello world example. Chapter 1 in Android NDK Cookbook is the same example with simpler code.

Books/Tutorials

Android Programming: The Big Nerd Ranch Guide

It seems the solution files still have bugs. For example in Chapter 1 "01_FirstApp", the <layout/activity_quiz.xml> file should have

android:text="@string/question_text_view"

instead of

android:id="@+id/question_text_view"

within <TextView> tag.

<AndroidProgramming.zip>

Beginning Android 4 Application Development

<Source_code_download_for_Beginning_Android_4_AD.zip>

Android Tutorials

Java Books

  • Head First Object-Oriented Analysis and Design
  • Head First Design Patterns

Material Design

Useful Apps

Backup/restore

Helium and play store. However, Helium's wiki says it does not back up photos or videos.

Another way is to use Ubuntu's Nautilus. On my Ubuntu 12.04, I need to install gvfs. See http://robert.penz.name/658/howto-access-mtp-devices-via-usb-on-ubuntu-12-04/. We need to reboot Ubuntu 12.04 for this to take effect.

sudo apt-get install gvfs

Offline maps

MAPS.ME

  • openstreetmap.org maps
  • routing
  • bookmark
  • offline search
  • auto-follow mode. When enabled, the map automatically orients itself to the direction you are moving.
  • One of the fastest offline maps ever.
  • Maps are updated regularly
  • no voice
  • no 3D

Remember to go to settings and turn off sharing data statistic with the author.

GPS Navigation & Maps Sygic

  • TomTom Maps
  • voice navigation
  • 3D mode
  • Free map updates & Free POI database updates
  • Spoken Street Names to focus on the road
  • With options for routing (avoid toll road, highways, ...)
  • The interface and feeling is the same as a standalone GPS
  • show house number
  • Road direction (one way or two ways)
  • 10 million downloads
  • 7 days of premium. See the different price at sygic.com.
  • Road name font is too small, no setting to change
  • Not that intuitive in terms of the interface

MapFactor/Navigator

  • OpenStreetMap data, maps are updated every month.
  • Voice guidance (a little bit inaccurate)
  • Routing
  • Can do search offline (by address or POI or browsing POI), or through google (online connection)
  • Night mode color is too brownish (change the setting is possible but too tedious)
  • even higher review than GPS Navigation & Maps Sygic?

The app is called 'Navigator' on Android's screen. When we launch it, it gives two options: Navigator Free (green color font) & Navigator (blue color). The app sometimes pops a message to ask for purchasing the TomTom map. There is no way to access this option from the free version's UI. The USA map costs 15 EUR on the paid version.

The date of each US states OSM can be found on the MapFactor website.

A Windows or Windows mobile version of the app can be found on its download page.

Navigator also works with Linux by using WINE program. See the Navigator Requirements page.

HERE

  • Voice-guided turn-by-turn navigation
  • offline use
  • route planner
  • save places
  • not sure about the source of maps
  • Nokia Apps LLC

VPN

openvpn

Download a configuration file from vpngate.net. With this, we can act as if we are located in a different country.

vpn defender

tunnelBear VPN

mms streaming

Useful like studioclassroom.com where mx player cannot. vplayer ($5) moboplayer (need sd card?), WonderShare (works, similar to ms player interface) Rock Player 2, BSPlayer (supports mms, but not work), VLC player, RealPlayer.

Network Signal Info

Play store

CPU-Z

Remote desktop/VNC

VNC

  • bBNC: feel slow
  • VNC view (from tightvnc): Port should be part of the IP (eg 192.168.1.xxx:5901). The mouse pt is different from the touch pt. Screen is kind of zoom-in. The desktop won't be moved.
  • Remote Ripple: good response like VNC view. It has a mouse control image on the desktop. If you don't click the visual mouse, you are moving the desktop.

Remote desktop

  • 2X RDP
  • Windows RDP

Github

The source code is hosted on https://github.com/github/android

Bitbucket

Adobe flash player

Booking.com

Hotel reservations

Bluetooth Auto Connect

Android System

File System Hierarchical

Basic(s)

A Word

Sometimes I'll get strange error messages when I do 'Run As Android Application'. The solution is to create a new Android app project and copy the code as I need.

A weird thing is Android SDK will automatically create project 'appcompat_v7', 'appcompat_v7_2', .... If we delete any one of them, it will screw up things.

See also https://developer.android.com/tools/support-library/setup.html, http://developer.android.com/tools/support-library/features.html

See message 1

Check connected devices

10 shell commands

Enable USB debugging on your device first.

$ sdk/platform-tools/adb devices
List of devices attached 
2011060116402004	device

Note: on new Android SDK downloaded from http://developer.android.com/sdk/index.html, the adb command is under

Android/Sdk/platform-tools/

directory.

Before this command can be used, we shall enable 'USB debugging' from the 'Developer option' page. The 'Developer option' page is under Setting but is hidden. To make this screen visible, follow the instruction on http://developer.android.com/tools/device.html. That is, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options at the bottom (tested on my Nexus 9).

Where to find the apk files on devices

See here. It is located under /data/app/.

The Android device needs

  • If connecting for the first time, User is prompted to install the drivers in which case, point to $ANDROID_SDK_PATH/usb_driver, the drivers will get installed.
  • Change your settings to permit apps that don’t come from the Google Market by going to the home screen and choosing MENU > Settings > Applications > Unknown Sources.
  • Turn USB debugging ON on your phone, On your device go to the home screen, press MENU > Settings > Applications > Development, then enable USB debugging.

How to copy an apk file out to PC

Use adb pull. For example,

adb pull data/app/com.dotgears.flappybird-1.apk .

How to put an apk file on device

Use adb install. For example,

adb install com.dotgears.flappybird-1.apk 

How to uninstall/delete apk files on devices

http://www.botskool.com/geeks/how-uninstall-apk-files-android-windows-sdk-emulator

cd SDK/tools
adb shell ls data/app
adb shell rm data/app/com.androidcan.asudoku.apk

How to copy a apk out from devices

http://stackoverflow.com/questions/4032960/how-do-i-get-an-apk-file-from-an-android-device. For example, the adobe reader

adb shell pm list packages
adb shell pm path com.adobe.reader
adb pull /data/app/com.adobe.reader-1.apk

Failed to install HelloWorld.apk on device (null) Error

http://stackoverflow.com/questions/5229906/android-failed-to-install-helloworld-apk-on-device-null-error

Solution: Try changing the ADB connection timeout. I think it defaults that to 5000ms and I changed mine to 10000ms to get rid of that problem. If you are in Eclipse, you can do this by going through Window -> Preferences and then it is in DDMS under Android.

Build without running an application

Building vs running: Building will just generate apk file but running will install the app to the device.

See here. In Eclipse menu, Windows -> Preferences. From this Preferences window: Android -> Build. Now uncheck "Skip packaging and dexing until export or launch. (Speeds up automatic builds on file save.)". From now on, as long as we save any changes in source files, the apk file will be recreated.

Modified the 'name' shown on Eclipse Package Explorer

Modify the name tag in <.project> file (hidden file).

Structure of an App project

Before we create a new project in Eclipse, we have to enter some information.

  • Application Name: the name that appears to users
  • Project Name: the name of project directory and the name visible in Eclipse
  • Package name: com.example.GUIDemo
  • Minimum Required SDK: API 8
  • Target SDK: API 18
  • Compile With: API 19 (By default, this is set to the latest version of Android available in your SDK)
  • Activity Name: MainActivity (will create <MainActivity.java> and MainActivity class)
  • Layout Name: activity_main (will create <activity_main.xml>)
  • Navigation type: None
src +-- com.example.guidemo
           +-- MainActivity.java

res +-- layout +-- activity_main.xml
       +-- values +-- strings.xml
AndroidManitest.xml
proguard-project.txt
project.properties
.project

Command Line

$ android update project -p .
$ ant debug            // create an .apk file
$ adb install bin/your-project-name-debug.apk // only install, will not run

Debug with Eclipse line by line

The Context Object

  • See stackoverflow.
  • Beginning android application book Chapter 2: Activities, fragments and intents -> Understanding Activities -> Displaying a Dialog Window.

Rotate AVD screen

  1. Enable NUMLOCK;
  2. Open your emulator and press the 7 followed by 9 on the NUMPAD on the right side of your keyboard;

Dialog

Intent

Linking activities using Intents.

  • See Chapter 2 of Beginning Android 4 App Development -> Linking Activities using Intents
  • http://www.vogella.com/tutorials/AndroidIntent/article.html
  • startActivity(). To pass data back from an activity, use startActivityForResult() and onActivityResult().
  • Intent-filter is defined in AndroidManifest.xml file. Other activities that wish to call this activity will invoke it via the activity's name in intent-filter.
  • The category for the intent filter is android.intent.category.DEFAULT. You need to add this to the intent filter so that this activity can be started by another activity using the startActivity() method.
  • Activities in Android can be invoked by any applications running on the device through intent-filter.
  • The <intent-filter> element defines how your activity can be invoked by another activity. If another activity has the same filter name, then when you call the startActivity() method with the same android name in intent-filter, the Android OS will display a selection of activities. See Figure 2-12 in 'Beginning Android 4 App Development'.
  • (Continue above) If you check the 'Use by default for this action" item, then to clear the default, we need to go to the Settings application in Android and select Apps > Manage applications, and then selection the app name. Scoll down to the bottom and click the 'Clear defaults' button.

AndroidManifest.xml

  • It names the Java package for the application.
  • It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of.
  • Android components register intent filters staticially in the AndroidManifest.xml.
  • It determines which processes will host application components.
  • It declares the minimum level of the Android API that the application requires.

Android nerd ranch book

01_FirstApp_GeoQuiz Project

activity_quiz.xml

Note that

  • A layout is a resource, a piece of your application that is not code.
  • To generate a resource ID for a widget, you include android:id attribute in the widget's definition.
  • There is a + sign in the values for android:id but not n the values for android:text. This is because you are creating the IDs and only referencing the strings.
  • Since we want to interact with 2 buttons in code, so only they need resource IDs.
  • All resource IDs can be found in <gen/com.example.geoquiz/R.java>.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:gravity="center"
  android:orientation="vertical" >

  <TextView    
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/question_text_view"
    android:padding="24dp" />
  
  <LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
      android:id="@+id/true_button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/true_button" />

    <Button
      android:id="@+id/false_button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/false_button" />

  </LinearLayout>

</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <string name="app_name">GeoQuiz</string>
  <string name="question_text_view">The Pacific Ocean is larger than the Atlantic Ocean.</string> 
  <string name="true_button">True</string>
  <string name="false_button">False</string>  
  <string name="correct_toast">Correct!</string>
  <string name="incorrect_toast">Incorrect!</string>
  <string name="menu_settings">Settings</string>

</resources>

QuizActivity.java

  • Add two member variables to access the buttons (through resource IDs)
  • Notice the prefix m on the member variable names.
  • Import the class android.widget.Button for the buttons. It can be added by organizing imports. This can be done by keyboard shortcut Ctrl + Shift + O.
  • To get references to widgets, we use the Activity method: findViewById(int id).
  • To set listeners (review Java!), use setOnClickListener(OnClickListener) method; something like
        mTrueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 // Does nothing yet.
            }
        });
  • Making toasts - a pop-up message. To create a toast, you call the method: makeText(Context context, int resId, int duration). The 2nd parameter is the resource ID of the string that the toast should display. After created a toast, you call Toast.show() on it to get it on screen.

So the complete java code looks like

package com.bignerdranch.android.geoquiz;

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

public class QuizActivity extends Activity {

    Button mTrueButton;
    Button mFalseButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);

        mTrueButton = (Button)findViewById(R.id.true_button);
        mTrueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(QuizActivity.this, 
                        R.string.incorrect_toast, Toast.LENGTH_SHORT)
                        .show();
            }
        });

        mFalseButton = (Button)findViewById(R.id.false_button);		
        mFalseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(QuizActivity.this, 
                        R.string.correct_toast, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_quiz, menu);
        return true;
    }

}

02_MVC_GeoQuiz

Works.

03_ActivityLifecycle_GeoQuiz

Crash AVD for some reason. The whole practice is the same as Chapter 2 in Beginning Android 4 Application Development (the code works there).

05_SecondActivity_GeoQuiz

07_UIFragments_CriminalIntent

  • One critical difference between the fragment lifecycle and the activity lifecycle is the fragment lifecycle methods are called by the hosting activity, not the OS.