summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--api/current.txt15
-rw-r--r--cmds/am/src/com/android/commands/am/Am.java106
-rw-r--r--core/java/android/appwidget/AppWidgetManager.java10
-rw-r--r--core/java/android/appwidget/AppWidgetProviderInfo.java11
-rw-r--r--core/java/android/content/SyncManager.java7
-rw-r--r--core/java/android/net/ConnectivityManager.java13
-rw-r--r--core/java/android/net/DhcpInfoInternal.java3
-rw-r--r--core/java/android/provider/ContactsContract.java31
-rw-r--r--core/java/android/text/style/SuggestionSpan.java79
-rw-r--r--core/java/android/view/GLES20Canvas.java1
-rw-r--r--core/java/android/view/GLES20RenderLayer.java8
-rw-r--r--core/java/android/view/GLES20TextureLayer.java6
-rw-r--r--core/java/android/view/HardwareLayer.java8
-rw-r--r--core/java/android/view/HardwareRenderer.java4
-rw-r--r--core/java/android/view/TextureView.java53
-rw-r--r--core/java/android/view/Window.java8
-rw-r--r--core/java/android/webkit/HTML5Audio.java22
-rw-r--r--core/java/android/webkit/WebView.java6
-rw-r--r--core/java/android/webkit/ZoomManager.java10
-rw-r--r--core/java/android/widget/AbsListView.java16
-rw-r--r--core/java/android/widget/SearchView.java35
-rw-r--r--core/java/android/widget/TextView.java29
-rw-r--r--core/java/com/android/internal/view/menu/ActionMenuView.java10
-rw-r--r--core/jni/android/graphics/TextLayoutCache.cpp26
-rw-r--r--core/jni/android_view_GLES20Canvas.cpp7
-rw-r--r--core/res/res/drawable-hdpi/day_picker_week_view_dayline_holo.9.pngbin261 -> 142 bytes
-rw-r--r--core/res/res/drawable-hdpi/ic_commit.pngbin1438 -> 0 bytes
-rw-r--r--core/res/res/drawable-hdpi/ic_commit_search_api_holo_dark.pngbin0 -> 597 bytes
-rw-r--r--core/res/res/drawable-hdpi/ic_commit_search_api_holo_light.pngbin1307 -> 616 bytes
-rw-r--r--core/res/res/drawable-mdpi/day_picker_week_view_dayline_holo.9.pngbin226 -> 133 bytes
-rw-r--r--core/res/res/drawable-mdpi/ic_commit_search_api_holo_dark.pngbin0 -> 511 bytes
-rw-r--r--core/res/res/drawable-mdpi/ic_commit_search_api_holo_light.pngbin558 -> 532 bytes
-rw-r--r--core/res/res/drawable-xhdpi/day_picker_week_view_dayline_holo.9.pngbin272 -> 142 bytes
-rw-r--r--core/res/res/drawable-xhdpi/ic_commit_search_api_holo_dark.pngbin0 -> 703 bytes
-rw-r--r--core/res/res/drawable-xhdpi/ic_commit_search_api_holo_light.pngbin786 -> 712 bytes
-rw-r--r--core/res/res/layout/search_bar.xml7
-rw-r--r--core/res/res/layout/search_view.xml6
-rwxr-xr-xcore/res/res/values/attrs.xml16
-rwxr-xr-xcore/res/res/values/config.xml1
-rw-r--r--core/res/res/values/dimens.xml9
-rw-r--r--core/res/res/values/styles.xml12
-rw-r--r--core/res/res/values/themes.xml7
-rw-r--r--data/fonts/Lohit_Hindi.ttfbin0 -> 67960 bytes
-rw-r--r--data/fonts/fallback_fonts.xml5
-rw-r--r--data/fonts/fonts.mk1
-rw-r--r--docs/html/guide/guide_toc.cs2
-rw-r--r--docs/html/guide/topics/graphics/opengl.jd411
-rw-r--r--docs/html/images/opengl/coordinates.pngbin0 -> 14019 bytes
-rw-r--r--docs/html/images/opengl/helloopengl-es10-1.pngbin0 -> 8448 bytes
-rw-r--r--docs/html/images/opengl/helloopengl-es10-2.pngbin0 -> 7259 bytes
-rw-r--r--docs/html/images/opengl/helloopengl-es20-1.pngbin0 -> 6935 bytes
-rw-r--r--docs/html/images/opengl/helloopengl-es20-2.pngbin0 -> 6833 bytes
-rw-r--r--docs/html/resources/resources-data.js20
-rw-r--r--docs/html/resources/tutorials/opengl/opengl-es10.jd532
-rw-r--r--docs/html/resources/tutorials/opengl/opengl-es20.jd652
-rw-r--r--docs/html/sdk/ndk/overview.jd3
-rw-r--r--include/media/stagefright/ACodec.h3
-rw-r--r--libs/hwui/Layer.h9
-rw-r--r--libs/hwui/Matrix.cpp23
-rw-r--r--libs/hwui/Matrix.h2
-rw-r--r--libs/hwui/OpenGLRenderer.cpp10
-rw-r--r--media/java/android/media/AudioService.java19
-rw-r--r--media/java/android/media/videoeditor/MediaArtistNativeHelper.java93
-rwxr-xr-xmedia/java/android/media/videoeditor/MediaImageItem.java26
-rwxr-xr-xmedia/java/android/media/videoeditor/MediaItem.java38
-rwxr-xr-xmedia/java/android/media/videoeditor/MediaVideoItem.java18
-rwxr-xr-xmedia/jni/mediaeditor/VideoBrowserInternal.h3
-rwxr-xr-xmedia/jni/mediaeditor/VideoBrowserMain.c19
-rwxr-xr-xmedia/jni/mediaeditor/VideoEditorMain.cpp86
-rw-r--r--media/libmediaplayerservice/nuplayer/NuPlayer.cpp18
-rw-r--r--media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp33
-rw-r--r--media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h2
-rw-r--r--media/libstagefright/ACodec.cpp74
-rw-r--r--media/libstagefright/Android.mk6
-rw-r--r--media/libstagefright/AwesomePlayer.cpp2
-rwxr-xr-xmedia/libstagefright/OMXCodec.cpp9
-rwxr-xr-xmedia/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java28
-rw-r--r--packages/SystemUI/res/layout-sw600dp/status_bar_notification_area.xml1
-rw-r--r--packages/SystemUI/res/layout/navigation_bar.xml2
-rw-r--r--packages/SystemUI/res/values/attrs.xml4
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java29
-rw-r--r--policy/src/com/android/internal/policy/impl/PhoneWindow.java5
-rwxr-xr-xpolicy/src/com/android/internal/policy/impl/PhoneWindowManager.java2
-rw-r--r--services/input/InputDispatcher.cpp20
-rw-r--r--services/java/com/android/server/AppWidgetService.java8
-rw-r--r--services/java/com/android/server/BatteryService.java2
-rw-r--r--services/java/com/android/server/ConnectivityService.java96
-rw-r--r--services/java/com/android/server/SystemServer.java10
-rw-r--r--services/java/com/android/server/am/ActivityManagerService.java6
-rw-r--r--services/java/com/android/server/am/BatteryStatsService.java2
-rw-r--r--services/java/com/android/server/connectivity/Vpn.java4
-rw-r--r--services/java/com/android/server/usb/UsbDeviceManager.java41
-rw-r--r--services/java/com/android/server/wm/WindowManagerService.java6
-rw-r--r--services/surfaceflinger/Android.mk4
-rw-r--r--services/surfaceflinger/DdmConnection.cpp75
-rw-r--r--services/surfaceflinger/DdmConnection.h29
-rw-r--r--services/surfaceflinger/SurfaceFlinger.cpp11
-rw-r--r--services/surfaceflinger/SurfaceFlinger.h1
-rw-r--r--tests/HwAccelerationTest/src/com/android/test/hwui/TextureViewActivity.java4
-rw-r--r--wifi/java/android/net/wifi/WifiStateTracker.java24
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pManager.java155
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pService.java166
103 files changed, 2857 insertions, 581 deletions
diff --git a/api/current.txt b/api/current.txt
index f8d3e06aadce..3ea70b7d79ac 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -16037,6 +16037,12 @@ package android.provider {
field public static final java.lang.String GROUP_SOURCE_ID = "group_sourceid";
}
+ public static final class ContactsContract.CommonDataKinds.Identity implements android.provider.ContactsContract.DataColumnsWithJoins {
+ field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/identity";
+ field public static final java.lang.String IDENTITY = "data1";
+ field public static final java.lang.String NAMESPACE = "data2";
+ }
+
public static final class ContactsContract.CommonDataKinds.Im implements android.provider.ContactsContract.CommonDataKinds.CommonColumns android.provider.ContactsContract.DataColumnsWithJoins {
method public static final java.lang.CharSequence getProtocolLabel(android.content.res.Resources, int, java.lang.CharSequence);
method public static final int getProtocolLabelResource(int);
@@ -20730,7 +20736,7 @@ package android.text.style {
method public void writeToParcel(android.os.Parcel, int);
}
- public class SuggestionSpan implements android.text.ParcelableSpan {
+ public class SuggestionSpan extends android.text.style.CharacterStyle implements android.text.ParcelableSpan {
ctor public SuggestionSpan(android.content.Context, java.lang.String[], int);
ctor public SuggestionSpan(java.util.Locale, java.lang.String[], int);
ctor public SuggestionSpan(android.content.Context, java.util.Locale, java.lang.String[], int, java.lang.Class<?>);
@@ -20740,10 +20746,12 @@ package android.text.style {
method public java.lang.String getLocale();
method public int getSpanTypeId();
method public java.lang.String[] getSuggestions();
+ method public void updateDrawState(android.text.TextPaint);
method public void writeToParcel(android.os.Parcel, int);
field public static final java.lang.String ACTION_SUGGESTION_PICKED = "android.text.style.SUGGESTION_PICKED";
field public static final android.os.Parcelable.Creator CREATOR;
- field public static final int FLAG_VERBATIM = 1; // 0x1
+ field public static final int FLAG_EASY_CORRECT = 1; // 0x1
+ field public static final int FLAG_MISSPELLED = 2; // 0x2
field public static final int SUGGESTIONS_MAX_SIZE = 5; // 0x5
field public static final java.lang.String SUGGESTION_SPAN_PICKED_AFTER = "after";
field public static final java.lang.String SUGGESTION_SPAN_PICKED_BEFORE = "before";
@@ -22479,12 +22487,14 @@ package android.view {
method public android.graphics.Bitmap getBitmap(android.graphics.Bitmap);
method public android.graphics.SurfaceTexture getSurfaceTexture();
method public android.view.TextureView.SurfaceTextureListener getSurfaceTextureListener();
+ method public android.graphics.Matrix getTransform(android.graphics.Matrix);
method public boolean isAvailable();
method public android.graphics.Canvas lockCanvas();
method public android.graphics.Canvas lockCanvas(android.graphics.Rect);
method protected final void onDraw(android.graphics.Canvas);
method public void setOpaque(boolean);
method public void setSurfaceTextureListener(android.view.TextureView.SurfaceTextureListener);
+ method public void setTransform(android.graphics.Matrix);
method public void unlockCanvasAndPost(android.graphics.Canvas);
}
@@ -23471,6 +23481,7 @@ package android.view {
method public abstract void setTitleColor(int);
method public void setType(int);
method public void setUiOptions(int);
+ method public void setUiOptions(int, int);
method public abstract void setVolumeControlStream(int);
method public void setWindowAnimations(int);
method public void setWindowManager(android.view.WindowManager, android.os.IBinder, java.lang.String);
diff --git a/cmds/am/src/com/android/commands/am/Am.java b/cmds/am/src/com/android/commands/am/Am.java
index 2937d2705aea..293116cb671e 100644
--- a/cmds/am/src/com/android/commands/am/Am.java
+++ b/cmds/am/src/com/android/commands/am/Am.java
@@ -28,6 +28,8 @@ import android.content.ComponentName;
import android.content.Context;
import android.content.IIntentReceiver;
import android.content.Intent;
+import android.content.pm.IPackageManager;
+import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
@@ -44,8 +46,8 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URISyntaxException;
-import java.util.Iterator;
-import java.util.Set;
+import java.util.HashSet;
+import java.util.List;
public class Am {
@@ -56,6 +58,7 @@ public class Am {
private boolean mDebugOption = false;
private boolean mWaitOption = false;
+ private boolean mStopOption = false;
private String mProfileFile;
private boolean mProfileAutoStop;
@@ -77,7 +80,7 @@ public class Am {
showUsage();
System.err.println("Error: " + e.getMessage());
} catch (Exception e) {
- System.err.println(e.toString());
+ e.printStackTrace(System.err);
System.exit(1);
}
}
@@ -129,6 +132,8 @@ public class Am {
mDebugOption = false;
mWaitOption = false;
+ mStopOption = false;
+ mProfileFile = null;
Uri data = null;
String type = null;
@@ -258,6 +263,8 @@ public class Am {
} else if (opt.equals("--start-profiler")) {
mProfileFile = nextArgRequired();
mProfileAutoStop = false;
+ } else if (opt.equals("-S")) {
+ mStopOption = true;
} else {
System.err.println("Error: Unknown option: " + opt);
showUsage();
@@ -266,23 +273,43 @@ public class Am {
}
intent.setDataAndType(data, type);
- String uri = nextArg();
- if (uri != null) {
- Intent oldIntent = intent;
- intent = Intent.parseUri(uri, 0);
- if (oldIntent.getAction() != null) {
- intent.setAction(oldIntent.getAction());
- }
- if (oldIntent.getData() != null || oldIntent.getType() != null) {
- intent.setDataAndType(oldIntent.getData(), oldIntent.getType());
+ String arg = nextArg();
+ if (arg != null) {
+ Intent baseIntent;
+ if (arg.indexOf(':') >= 0) {
+ // The argument is a URI. Fully parse it, and use that result
+ // to fill in any data not specified so far.
+ baseIntent = Intent.parseUri(arg, Intent.URI_INTENT_SCHEME);
+ } else if (arg.indexOf('/') >= 0) {
+ // The argument is a component name. Build an Intent to launch
+ // it.
+ baseIntent = new Intent(Intent.ACTION_MAIN);
+ baseIntent.addCategory(Intent.CATEGORY_LAUNCHER);
+ baseIntent.setComponent(ComponentName.unflattenFromString(arg));
+ } else {
+ // Assume the argument is a package name.
+ baseIntent = new Intent(Intent.ACTION_MAIN);
+ baseIntent.addCategory(Intent.CATEGORY_LAUNCHER);
+ baseIntent.setPackage(arg);
}
- Set cats = oldIntent.getCategories();
- if (cats != null) {
- Iterator it = cats.iterator();
- while (it.hasNext()) {
- intent.addCategory((String)it.next());
+ Bundle extras = intent.getExtras();
+ intent.replaceExtras((Bundle)null);
+ Bundle uriExtras = baseIntent.getExtras();
+ baseIntent.replaceExtras((Bundle)null);
+ if (intent.getAction() != null && baseIntent.getCategories() != null) {
+ HashSet<String> cats = new HashSet<String>(baseIntent.getCategories());
+ for (String c : cats) {
+ baseIntent.removeCategory(c);
}
}
+ intent.fillIn(baseIntent, Intent.FILL_IN_COMPONENT);
+ if (extras == null) {
+ extras = uriExtras;
+ } else if (uriExtras != null) {
+ uriExtras.putAll(extras);
+ extras = uriExtras;
+ }
+ intent.replaceExtras(extras);
hasIntentInfo = true;
}
@@ -301,6 +328,41 @@ public class Am {
private void runStart() throws Exception {
Intent intent = makeIntent();
+
+ String mimeType = intent.getType();
+ if (mimeType == null && intent.getData() != null
+ && "content".equals(intent.getData().getScheme())) {
+ mimeType = mAm.getProviderMimeType(intent.getData());
+ }
+
+ if (mStopOption) {
+ String packageName;
+ if (intent.getComponent() != null) {
+ packageName = intent.getComponent().getPackageName();
+ } else {
+ IPackageManager pm = IPackageManager.Stub.asInterface(
+ ServiceManager.getService("package"));
+ if (pm == null) {
+ System.err.println("Error: Package manager not running; aborting");
+ return;
+ }
+ List<ResolveInfo> activities = pm.queryIntentActivities(intent, mimeType, 0);
+ if (activities == null || activities.size() <= 0) {
+ System.err.println("Error: Intent does not match any activities: "
+ + intent);
+ return;
+ } else if (activities.size() > 1) {
+ System.err.println("Error: Intent matches multiple activities; can't stop: "
+ + intent);
+ return;
+ }
+ packageName = activities.get(0).activityInfo.packageName;
+ }
+ System.out.println("Stopping: " + packageName);
+ mAm.forceStopPackage(packageName);
+ Thread.sleep(250);
+ }
+
System.out.println("Starting: " + intent);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
@@ -319,16 +381,15 @@ public class Am {
}
}
- // XXX should do something to determine the MIME type.
IActivityManager.WaitResult result = null;
int res;
if (mWaitOption) {
- result = mAm.startActivityAndWait(null, intent, intent.getType(),
+ result = mAm.startActivityAndWait(null, intent, mimeType,
null, 0, null, null, 0, false, mDebugOption,
mProfileFile, fd, mProfileAutoStop);
res = result.result;
} else {
- res = mAm.startActivity(null, intent, intent.getType(),
+ res = mAm.startActivity(null, intent, mimeType,
null, 0, null, null, 0, false, mDebugOption,
mProfileFile, fd, mProfileAutoStop);
}
@@ -1103,7 +1164,7 @@ public class Am {
private static void showUsage() {
System.err.println(
"usage: am [subcommand] [options]\n" +
- "usage: am start [-D] [-W] [-P <FILE>] [--start-profiler <FILE>] <INTENT>\n" +
+ "usage: am start [-D] [-W] [-P <FILE>] [--start-profiler <FILE>] [-S] <INTENT>\n" +
" am startservice <INTENT>\n" +
" am force-stop <PACKAGE>\n" +
" am broadcast <INTENT>\n" +
@@ -1121,6 +1182,7 @@ public class Am {
" -W: wait for launch to complete\n" +
" --start-profiler <FILE>: start profiler and send results to <FILE>\n" +
" -P <FILE>: like above, but profiling stops when app goes idle\n" +
+ " -S: force stop the target app before starting the activity\n" +
"\n" +
"am startservice: start a Service.\n" +
"\n" +
@@ -1175,7 +1237,7 @@ public class Am {
" [--activity-single-top] [--activity-clear-task]\n" +
" [--activity-task-on-home]\n" +
" [--receiver-registered-only] [--receiver-replace-pending]\n" +
- " [<URI>]\n"
+ " [<URI> | <PACKAGE> | <COMPONENT>]\n"
);
}
}
diff --git a/core/java/android/appwidget/AppWidgetManager.java b/core/java/android/appwidget/AppWidgetManager.java
index 1ef99a1e6845..09661a59334c 100644
--- a/core/java/android/appwidget/AppWidgetManager.java
+++ b/core/java/android/appwidget/AppWidgetManager.java
@@ -184,16 +184,6 @@ public class AppWidgetManager {
*/
public static final String META_DATA_APPWIDGET_PROVIDER = "android.appwidget.provider";
- /**
- * Field for the manifest meta-data tag used to indicate any previous name for the
- * app widget receiver.
- *
- * @see AppWidgetProviderInfo
- *
- * @hide Pending API approval
- */
- public static final String META_DATA_APPWIDGET_OLD_NAME = "android.appwidget.oldName";
-
static WeakHashMap<Context, WeakReference<AppWidgetManager>> sManagerCache =
new WeakHashMap<Context, WeakReference<AppWidgetManager>>();
static IAppWidgetService sService;
diff --git a/core/java/android/appwidget/AppWidgetProviderInfo.java b/core/java/android/appwidget/AppWidgetProviderInfo.java
index 9c352d58dfb2..c33681d65941 100644
--- a/core/java/android/appwidget/AppWidgetProviderInfo.java
+++ b/core/java/android/appwidget/AppWidgetProviderInfo.java
@@ -138,17 +138,6 @@ public class AppWidgetProviderInfo implements Parcelable {
public int icon;
/**
- * The previous name, if any, of the app widget receiver. If not supplied, it will be
- * ignored.
- *
- * <p>This field corresponds to the <code>&lt;meta-data /&gt;</code> with the name
- * <code>android.appwidget.oldName</code>.
- *
- * @hide Pending API approval
- */
- public String oldName;
-
- /**
* The view id of the AppWidget subview which should be auto-advanced by the widget's host.
*
* <p>This field corresponds to the <code>android:autoAdvanceViewId</code> attribute in
diff --git a/core/java/android/content/SyncManager.java b/core/java/android/content/SyncManager.java
index 5be6ec1fff86..496da41c8bc0 100644
--- a/core/java/android/content/SyncManager.java
+++ b/core/java/android/content/SyncManager.java
@@ -1573,8 +1573,11 @@ public class SyncManager implements OnAccountsUpdateListener {
final Long periodInSeconds = info.periodicSyncs.get(i).second;
// find when this periodic sync was last scheduled to run
final long lastPollTimeAbsolute = status.getPeriodicSyncTime(i);
- // compute when this periodic sync should next run
- long nextPollTimeAbsolute = lastPollTimeAbsolute + periodInSeconds * 1000;
+ // compute when this periodic sync should next run - this can be in the future
+ // for example if the user changed the time, synced and changed back.
+ final long nextPollTimeAbsolute = lastPollTimeAbsolute > nowAbsolute
+ ? nowAbsolute
+ : lastPollTimeAbsolute + periodInSeconds * 1000;
// if it is ready to run then schedule it and mark it as having been scheduled
if (nextPollTimeAbsolute <= nowAbsolute) {
final Pair<Long, Long> backoff =
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index eb9cd213dd8e..53fd50ddf16e 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -260,11 +260,18 @@ public class ConnectivityManager {
*/
public static final int TYPE_MOBILE_CBS = 12;
+ /**
+ * A Wi-Fi p2p connection. Only requesting processes will have access to
+ * the peers connected.
+ * {@hide}
+ */
+ public static final int TYPE_WIFI_P2P = 13;
+
/** {@hide} */
- public static final int MAX_RADIO_TYPE = TYPE_MOBILE_CBS;
+ public static final int MAX_RADIO_TYPE = TYPE_WIFI_P2P;
/** {@hide} */
- public static final int MAX_NETWORK_TYPE = TYPE_MOBILE_CBS;
+ public static final int MAX_NETWORK_TYPE = TYPE_WIFI_P2P;
public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
@@ -303,6 +310,8 @@ public class ConnectivityManager {
return "MOBILE_IMS";
case TYPE_MOBILE_CBS:
return "MOBILE_CBS";
+ case TYPE_WIFI_P2P:
+ return "WIFI_P2P";
default:
return Integer.toString(type);
}
diff --git a/core/java/android/net/DhcpInfoInternal.java b/core/java/android/net/DhcpInfoInternal.java
index 860da0a335a9..9b0a2d7056fb 100644
--- a/core/java/android/net/DhcpInfoInternal.java
+++ b/core/java/android/net/DhcpInfoInternal.java
@@ -100,7 +100,8 @@ public class DhcpInfoInternal {
if (TextUtils.isEmpty(dns1) == false) {
p.addDns(NetworkUtils.numericToInetAddress(dns1));
} else {
- Log.d(TAG, "makeLinkProperties with empty dns1!");
+ p.addDns(NetworkUtils.numericToInetAddress(serverAddress));
+ Log.d(TAG, "empty dns1, use dhcp server as dns1!");
}
if (TextUtils.isEmpty(dns2) == false) {
p.addDns(NetworkUtils.numericToInetAddress(dns2));
diff --git a/core/java/android/provider/ContactsContract.java b/core/java/android/provider/ContactsContract.java
index d867e35c2422..a66fa81904a5 100644
--- a/core/java/android/provider/ContactsContract.java
+++ b/core/java/android/provider/ContactsContract.java
@@ -6455,6 +6455,37 @@ public final class ContactsContract {
}
}
}
+
+ /**
+ * A data kind representing an Identity related to the contact.
+ * <p>
+ * This can be used as a signal by the aggregator to combine raw contacts into
+ * contacts, e.g. if two contacts have Identity rows with
+ * the same NAMESPACE and IDENTITY values the aggregator can know that they refer
+ * to the same person.
+ * </p>
+ */
+ public static final class Identity implements DataColumnsWithJoins {
+ /**
+ * This utility class cannot be instantiated
+ */
+ private Identity() {}
+
+ /** MIME type used when storing this in data table. */
+ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/identity";
+
+ /**
+ * The identity string.
+ * <P>Type: TEXT</P>
+ */
+ public static final String IDENTITY = DataColumns.DATA1;
+
+ /**
+ * The namespace of the identity string, e.g. "com.google"
+ * <P>Type: TEXT</P>
+ */
+ public static final String NAMESPACE = DataColumns.DATA2;
+ }
}
/**
diff --git a/core/java/android/text/style/SuggestionSpan.java b/core/java/android/text/style/SuggestionSpan.java
index 555aac5de6bf..fb94bc7e5690 100644
--- a/core/java/android/text/style/SuggestionSpan.java
+++ b/core/java/android/text/style/SuggestionSpan.java
@@ -17,10 +17,13 @@
package android.text.style;
import android.content.Context;
+import android.content.res.TypedArray;
+import android.graphics.Color;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.text.ParcelableSpan;
+import android.text.TextPaint;
import android.text.TextUtils;
import android.widget.TextView;
@@ -34,23 +37,36 @@ import java.util.Locale;
* display a popup dialog listing suggestion replacement for that text. The user can then replace
* the original text by one of the suggestions.
*
- * These spans should typically be created by the input method to privide correction and alternates
+ * These spans should typically be created by the input method to provide correction and alternates
* for the text.
*
* @see TextView#setSuggestionsEnabled(boolean)
*/
-public class SuggestionSpan implements ParcelableSpan {
+public class SuggestionSpan extends CharacterStyle implements ParcelableSpan {
+
+ /**
+ * Sets this flag if the suggestions should be easily accessible with few interactions.
+ * This flag should be set for every suggestions that the user is likely to use.
+ */
+ public static final int FLAG_EASY_CORRECT = 0x0001;
+
/**
- * Flag for indicating that the input is verbatim. TextView refers to this flag to determine
- * how it displays a word with SuggestionSpan.
+ * Sets this flag if the suggestions apply to a misspelled word/text. This type of suggestion is
+ * rendered differently to highlight the error.
*/
- public static final int FLAG_VERBATIM = 0x0001;
+ public static final int FLAG_MISSPELLED = 0x0002;
public static final String ACTION_SUGGESTION_PICKED = "android.text.style.SUGGESTION_PICKED";
public static final String SUGGESTION_SPAN_PICKED_AFTER = "after";
public static final String SUGGESTION_SPAN_PICKED_BEFORE = "before";
public static final String SUGGESTION_SPAN_PICKED_HASHCODE = "hashcode";
+ /**
+ * The default underline thickness as a percentage of the system's default underline thickness
+ * (i.e., 100 means the default thickness, and 200 is a double thickness).
+ */
+ private static final int DEFAULT_UNDERLINE_PERCENTAGE = 100;
+
public static final int SUGGESTIONS_MAX_SIZE = 5;
/*
@@ -66,6 +82,11 @@ public class SuggestionSpan implements ParcelableSpan {
private final String mNotificationTargetClassName;
private final int mHashCode;
+ private float mMisspelledUnderlineThickness;
+ private int mMisspelledUnderlineColor;
+ private float mEasyCorrectUnderlineThickness;
+ private int mEasyCorrectUnderlineColor;
+
/*
* TODO: If switching IME is required, needs to add parameters for ids of InputMethodInfo
* and InputMethodSubtype.
@@ -107,6 +128,7 @@ public class SuggestionSpan implements ParcelableSpan {
} else {
mLocaleString = locale.toString();
}
+
if (notificationTargetClass != null) {
mNotificationTargetClassName = notificationTargetClass.getCanonicalName();
} else {
@@ -114,6 +136,36 @@ public class SuggestionSpan implements ParcelableSpan {
}
mHashCode = hashCodeInternal(
mFlags, mSuggestions, mLocaleString, mNotificationTargetClassName);
+
+ initStyle(context);
+ }
+
+ private void initStyle(Context context) {
+ // Read the colors. We need to store the color and the underline thickness, as the span
+ // does not have access to the context when it is read from a parcel.
+ TypedArray typedArray;
+
+ typedArray = context.obtainStyledAttributes(null,
+ com.android.internal.R.styleable.SuggestionSpan,
+ com.android.internal.R.attr.textAppearanceEasyCorrectSuggestion, 0);
+
+ mEasyCorrectUnderlineThickness = getThicknessPercentage(typedArray,
+ com.android.internal.R.styleable.SuggestionSpan_textUnderlineThicknessPercentage);
+ mEasyCorrectUnderlineColor = typedArray.getColor(
+ com.android.internal.R.styleable.SuggestionSpan_textUnderlineColor, Color.BLACK);
+
+ typedArray = context.obtainStyledAttributes(null,
+ com.android.internal.R.styleable.SuggestionSpan,
+ com.android.internal.R.attr.textAppearanceMisspelledSuggestion, 0);
+ mMisspelledUnderlineThickness = getThicknessPercentage(typedArray,
+ com.android.internal.R.styleable.SuggestionSpan_textUnderlineThicknessPercentage);
+ mMisspelledUnderlineColor = typedArray.getColor(
+ com.android.internal.R.styleable.SuggestionSpan_textUnderlineColor, Color.BLACK);
+ }
+
+ private static float getThicknessPercentage(TypedArray typedArray, int index) {
+ int value = typedArray.getInteger(index, DEFAULT_UNDERLINE_PERCENTAGE);
+ return value / 100.0f;
}
public SuggestionSpan(Parcel src) {
@@ -122,6 +174,10 @@ public class SuggestionSpan implements ParcelableSpan {
mLocaleString = src.readString();
mNotificationTargetClassName = src.readString();
mHashCode = src.readInt();
+ mEasyCorrectUnderlineColor = src.readInt();
+ mEasyCorrectUnderlineThickness = src.readFloat();
+ mMisspelledUnderlineColor = src.readInt();
+ mMisspelledUnderlineThickness = src.readFloat();
}
/**
@@ -167,6 +223,10 @@ public class SuggestionSpan implements ParcelableSpan {
dest.writeString(mLocaleString);
dest.writeString(mNotificationTargetClassName);
dest.writeInt(mHashCode);
+ dest.writeInt(mEasyCorrectUnderlineColor);
+ dest.writeFloat(mEasyCorrectUnderlineThickness);
+ dest.writeInt(mMisspelledUnderlineColor);
+ dest.writeFloat(mMisspelledUnderlineThickness);
}
@Override
@@ -205,4 +265,13 @@ public class SuggestionSpan implements ParcelableSpan {
return new SuggestionSpan[size];
}
};
+
+ @Override
+ public void updateDrawState(TextPaint tp) {
+ if ((getFlags() & FLAG_MISSPELLED) != 0) {
+ tp.setUnderlineText(true, mMisspelledUnderlineColor, mMisspelledUnderlineThickness);
+ } else if ((getFlags() & FLAG_EASY_CORRECT) != 0) {
+ tp.setUnderlineText(true, mEasyCorrectUnderlineColor, mEasyCorrectUnderlineThickness);
+ }
+ }
}
diff --git a/core/java/android/view/GLES20Canvas.java b/core/java/android/view/GLES20Canvas.java
index e586370b4830..cfbb47c30d55 100644
--- a/core/java/android/view/GLES20Canvas.java
+++ b/core/java/android/view/GLES20Canvas.java
@@ -151,6 +151,7 @@ class GLES20Canvas extends HardwareCanvas {
static native void nResizeLayer(int layerId, int width, int height, int[] layerInfo);
static native void nUpdateTextureLayer(int layerId, int width, int height, boolean opaque,
SurfaceTexture surface);
+ static native void nSetTextureLayerTransform(int layerId, int matrix);
static native void nDestroyLayer(int layerId);
static native void nDestroyLayerDeferred(int layerId);
static native boolean nCopyLayer(int layerId, int bitmap);
diff --git a/core/java/android/view/GLES20RenderLayer.java b/core/java/android/view/GLES20RenderLayer.java
index 41f16e27da8a..23a716621589 100644
--- a/core/java/android/view/GLES20RenderLayer.java
+++ b/core/java/android/view/GLES20RenderLayer.java
@@ -17,6 +17,7 @@
package android.view;
import android.graphics.Canvas;
+import android.graphics.Matrix;
/**
* An OpenGL ES 2.0 implementation of {@link HardwareLayer}. This
@@ -87,4 +88,11 @@ class GLES20RenderLayer extends GLES20Layer {
}
return getCanvas();
}
+
+ /**
+ * Ignored
+ */
+ @Override
+ void setTransform(Matrix matrix) {
+ }
}
diff --git a/core/java/android/view/GLES20TextureLayer.java b/core/java/android/view/GLES20TextureLayer.java
index 391d9f465994..6c41023c98bb 100644
--- a/core/java/android/view/GLES20TextureLayer.java
+++ b/core/java/android/view/GLES20TextureLayer.java
@@ -17,6 +17,7 @@
package android.view;
import android.graphics.Canvas;
+import android.graphics.Matrix;
import android.graphics.SurfaceTexture;
/**
@@ -75,4 +76,9 @@ class GLES20TextureLayer extends GLES20Layer {
super.update(width, height, isOpaque);
GLES20Canvas.nUpdateTextureLayer(mLayer, width, height, isOpaque, mSurface);
}
+
+ @Override
+ void setTransform(Matrix matrix) {
+ GLES20Canvas.nSetTextureLayerTransform(mLayer, matrix.native_instance);
+ }
}
diff --git a/core/java/android/view/HardwareLayer.java b/core/java/android/view/HardwareLayer.java
index dfb39ae04543..28389abc3421 100644
--- a/core/java/android/view/HardwareLayer.java
+++ b/core/java/android/view/HardwareLayer.java
@@ -18,6 +18,7 @@ package android.view;
import android.graphics.Bitmap;
import android.graphics.Canvas;
+import android.graphics.Matrix;
/**
* A hardware layer can be used to render graphics operations into a hardware
@@ -150,4 +151,11 @@ abstract class HardwareLayer {
mHeight = height;
mOpaque = isOpaque;
}
+
+ /**
+ * Sets an optional transform on this layer.
+ *
+ * @param matrix The transform to apply to the layer.
+ */
+ abstract void setTransform(Matrix matrix);
}
diff --git a/core/java/android/view/HardwareRenderer.java b/core/java/android/view/HardwareRenderer.java
index f2c3131ffd84..a05637d82e52 100644
--- a/core/java/android/view/HardwareRenderer.java
+++ b/core/java/android/view/HardwareRenderer.java
@@ -718,7 +718,9 @@ public abstract class HardwareRenderer {
if (!createSurface(holder)) {
return;
}
- setEnabled(true);
+ if (mCanvas != null) {
+ setEnabled(true);
+ }
}
}
diff --git a/core/java/android/view/TextureView.java b/core/java/android/view/TextureView.java
index 53a6bcba98c8..b72222ee9f99 100644
--- a/core/java/android/view/TextureView.java
+++ b/core/java/android/view/TextureView.java
@@ -19,6 +19,7 @@ package android.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
+import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
@@ -104,6 +105,9 @@ public class TextureView extends View {
private boolean mOpaque = true;
+ private final Matrix mMatrix = new Matrix();
+ private boolean mMatrixChanged;
+
private final Object[] mLock = new Object[0];
private boolean mUpdateLayer;
@@ -312,6 +316,11 @@ public class TextureView extends View {
applyUpdate();
+ if (mMatrixChanged) {
+ mLayer.setTransform(mMatrix);
+ mMatrixChanged = false;
+ }
+
return mLayer;
}
@@ -358,6 +367,50 @@ public class TextureView extends View {
}
/**
+ * <p>Sets the transform to associate with this texture view.
+ * The specified transform applies to the underlying surface
+ * texture and does not affect the size or position of the view
+ * itself, only of its content.</p>
+ *
+ * <p>Some transforms might prevent the content from drawing
+ * all the pixels contained within this view's bounds. In such
+ * situations, make sure this texture view is not marked opaque.</p>
+ *
+ * @param transform The transform to apply to the content of
+ * this view.
+ *
+ * @see #getTransform(android.graphics.Matrix)
+ * @see #isOpaque()
+ * @see #setOpaque(boolean)
+ */
+ public void setTransform(Matrix transform) {
+ mMatrix.set(transform);
+ mMatrixChanged = true;
+ invalidate();
+ }
+
+ /**
+ * Returns the transform associated with this texture view.
+ *
+ * @param transform The {@link Matrix} in which to copy the current
+ * transform. Can be null.
+ *
+ * @return The specified matrix if not null or a new {@link Matrix}
+ * instance otherwise.
+ *
+ * @see #setTransform(android.graphics.Matrix)
+ */
+ public Matrix getTransform(Matrix transform) {
+ if (transform == null) {
+ transform = new Matrix();
+ }
+
+ transform.set(mMatrix);
+
+ return transform;
+ }
+
+ /**
* <p>Returns a {@link android.graphics.Bitmap} representation of the content
* of the associated surface texture. If the surface texture is not available,
* this method returns null.</p>
diff --git a/core/java/android/view/Window.java b/core/java/android/view/Window.java
index 6ac679ca88d5..e0e1a1a83b91 100644
--- a/core/java/android/view/Window.java
+++ b/core/java/android/view/Window.java
@@ -1219,4 +1219,12 @@ public abstract class Window {
* @param uiOptions Flags specifying extra options for this window.
*/
public void setUiOptions(int uiOptions) { }
+
+ /**
+ * Set extra options that will influence the UI for this window.
+ * Only the bits filtered by mask will be modified.
+ * @param uiOptions Flags specifying extra options for this window.
+ * @param mask Flags specifying which options should be modified. Others will remain unchanged.
+ */
+ public void setUiOptions(int uiOptions, int mask) { }
}
diff --git a/core/java/android/webkit/HTML5Audio.java b/core/java/android/webkit/HTML5Audio.java
index 6fc0d119f9c9..1e958549809d 100644
--- a/core/java/android/webkit/HTML5Audio.java
+++ b/core/java/android/webkit/HTML5Audio.java
@@ -27,6 +27,8 @@ import android.os.Message;
import android.util.Log;
import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
@@ -46,6 +48,8 @@ class HTML5Audio extends Handler
// The C++ MediaPlayerPrivateAndroid object.
private int mNativePointer;
+ // The private status of the view that created this player
+ private boolean mIsPrivate;
private static int IDLE = 0;
private static int INITIALIZED = 1;
@@ -64,6 +68,9 @@ class HTML5Audio extends Handler
// Timer thread -> UI thread
private static final int TIMEUPDATE = 100;
+ private static final String COOKIE = "Cookie";
+ private static final String HIDE_URL_LOGS = "x-hide-urls-from-log";
+
// The spec says the timer should fire every 250 ms or less.
private static final int TIMEUPDATE_PERIOD = 250; // ms
// The timer for timeupate events.
@@ -138,10 +145,11 @@ class HTML5Audio extends Handler
/**
* @param nativePtr is the C++ pointer to the MediaPlayerPrivate object.
*/
- public HTML5Audio(int nativePtr) {
+ public HTML5Audio(WebViewCore webViewCore, int nativePtr) {
// Save the native ptr
mNativePointer = nativePtr;
resetMediaPlayer();
+ mIsPrivate = webViewCore.getWebView().isPrivateBrowsingEnabled();
}
private void resetMediaPlayer() {
@@ -169,7 +177,17 @@ class HTML5Audio extends Handler
if (mState != IDLE) {
resetMediaPlayer();
}
- mMediaPlayer.setDataSource(url);
+ String cookieValue = CookieManager.getInstance().getCookie(url, mIsPrivate);
+ Map<String, String> headers = new HashMap<String, String>();
+
+ if (cookieValue != null) {
+ headers.put(COOKIE, cookieValue);
+ }
+ if (mIsPrivate) {
+ headers.put(HIDE_URL_LOGS, "true");
+ }
+
+ mMediaPlayer.setDataSource(url, headers);
mState = INITIALIZED;
mMediaPlayer.prepareAsync();
} catch (IOException e) {
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 2bb9da157788..6374b471eadd 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -27,7 +27,6 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
-import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
@@ -8104,8 +8103,7 @@ public class WebView extends AbsoluteLayout
// nativeCreate sets mNativeClass to a non-zero value
String drawableDir = BrowserFrame.getRawResFilename(
BrowserFrame.DRAWABLEDIR, mContext);
- AssetManager am = mContext.getAssets();
- nativeCreate(msg.arg1, drawableDir, am);
+ nativeCreate(msg.arg1, drawableDir);
if (mDelaySetPicture != null) {
setNewPicture(mDelaySetPicture, true);
mDelaySetPicture = null;
@@ -9140,7 +9138,7 @@ public class WebView extends AbsoluteLayout
private native Rect nativeCacheHitNodeBounds();
private native int nativeCacheHitNodePointer();
/* package */ native void nativeClearCursor();
- private native void nativeCreate(int ptr, String drawableDir, AssetManager am);
+ private native void nativeCreate(int ptr, String drawableDir);
private native int nativeCursorFramePointer();
private native Rect nativeCursorNodeBounds();
private native int nativeCursorNodePointer();
diff --git a/core/java/android/webkit/ZoomManager.java b/core/java/android/webkit/ZoomManager.java
index 70e48ad74e8d..2bcb0202955f 100644
--- a/core/java/android/webkit/ZoomManager.java
+++ b/core/java/android/webkit/ZoomManager.java
@@ -709,10 +709,14 @@ class ZoomManager {
final WebSettings settings = mWebView.getSettings();
final PackageManager pm = context.getPackageManager();
- mSupportMultiTouch = pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)
+ mSupportMultiTouch =
+ (pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)
+ || pm.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT))
&& settings.supportZoom() && settings.getBuiltInZoomControls();
- mAllowPanAndScale = pm.hasSystemFeature(
- PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT);
+ mAllowPanAndScale =
+ pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)
+ || pm.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT);
+
if (mSupportMultiTouch && (mScaleDetector == null)) {
mScaleDetector = new ScaleGestureDetector(context, new ScaleDetectorListener());
} else if (!mSupportMultiTouch && (mScaleDetector != null)) {
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index db4df40a43b5..dae118e29f24 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -637,6 +637,11 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te
private boolean mIsAttached;
/**
+ * Track the item count from the last time we handled a data change.
+ */
+ private int mLastHandledItemCount;
+
+ /**
* Interface definition for a callback to be invoked when the list or grid
* has been scrolled.
*/
@@ -1829,10 +1834,10 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te
// Check if our previous measured size was at a point where we should scroll later.
if (mTranscriptMode == TRANSCRIPT_MODE_NORMAL) {
final int childCount = getChildCount();
- final int listBottom = getBottom() - getPaddingBottom();
+ final int listBottom = getHeight() - getPaddingBottom();
final View lastChild = getChildAt(childCount - 1);
final int lastBottom = lastChild != null ? lastChild.getBottom() : listBottom;
- mForceTranscriptScroll = mFirstPosition + childCount >= mOldItemCount &&
+ mForceTranscriptScroll = mFirstPosition + childCount >= mLastHandledItemCount &&
lastBottom <= listBottom;
}
}
@@ -4744,6 +4749,8 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te
@Override
protected void handleDataChanged() {
int count = mItemCount;
+ int lastHandledItemCount = mLastHandledItemCount;
+ mLastHandledItemCount = mItemCount;
if (count > 0) {
int newPos;
@@ -4765,10 +4772,11 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te
return;
}
final int childCount = getChildCount();
- final int listBottom = getBottom() - getPaddingBottom();
+ final int listBottom = getHeight() - getPaddingBottom();
final View lastChild = getChildAt(childCount - 1);
final int lastBottom = lastChild != null ? lastChild.getBottom() : listBottom;
- if (mFirstPosition + childCount >= mOldItemCount && lastBottom <= listBottom) {
+ if (mFirstPosition + childCount >= lastHandledItemCount &&
+ lastBottom <= listBottom) {
mLayoutMode = LAYOUT_FORCE_BOTTOM;
return;
}
diff --git a/core/java/android/widget/SearchView.java b/core/java/android/widget/SearchView.java
index 4eecd6458145..aba6834fc530 100644
--- a/core/java/android/widget/SearchView.java
+++ b/core/java/android/widget/SearchView.java
@@ -627,12 +627,33 @@ public class SearchView extends LinearLayout implements CollapsibleActionView {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
- if ((widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.EXACTLY) && mMaxWidth > 0
- && width > mMaxWidth) {
- super.onMeasure(MeasureSpec.makeMeasureSpec(mMaxWidth, widthMode), heightMeasureSpec);
- } else {
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
+ switch (widthMode) {
+ case MeasureSpec.AT_MOST:
+ // If there is an upper limit, don't exceed maximum width (explicit or implicit)
+ if (mMaxWidth > 0) {
+ width = Math.min(mMaxWidth, width);
+ } else {
+ width = Math.min(getPreferredWidth(), width);
+ }
+ break;
+ case MeasureSpec.EXACTLY:
+ // If an exact width is specified, still don't exceed any specified maximum width
+ if (mMaxWidth > 0) {
+ width = Math.min(mMaxWidth, width);
+ }
+ break;
+ case MeasureSpec.UNSPECIFIED:
+ // Use maximum width, if specified, else preferred width
+ width = mMaxWidth > 0 ? mMaxWidth : getPreferredWidth();
+ break;
}
+ widthMode = MeasureSpec.EXACTLY;
+ super.onMeasure(MeasureSpec.makeMeasureSpec(width, widthMode), heightMeasureSpec);
+ }
+
+ private int getPreferredWidth() {
+ return getContext().getResources()
+ .getDimensionPixelSize(R.dimen.search_view_preferred_width);
}
private void updateViewsVisibility(final boolean collapsed) {
@@ -695,7 +716,7 @@ public class SearchView extends LinearLayout implements CollapsibleActionView {
// Should we show the close button? It is not shown if there's no focus,
// field is not iconified by default and there is no text in it.
final boolean showClose = hasText || (mIconifiedByDefault && !mExpandedInActionView);
- mCloseButton.setVisibility(showClose ? VISIBLE : INVISIBLE);
+ mCloseButton.setVisibility(showClose ? VISIBLE : GONE);
mCloseButton.getDrawable().setState(hasText ? ENABLED_STATE_SET : EMPTY_STATE_SET);
}
@@ -991,7 +1012,7 @@ public class SearchView extends LinearLayout implements CollapsibleActionView {
*/
private void updateVoiceButton(boolean empty) {
int visibility = GONE;
- if (mVoiceButtonEnabled && !isIconified() && (empty || !mSubmitButtonEnabled)) {
+ if (mVoiceButtonEnabled && !isIconified() && empty) {
visibility = VISIBLE;
mSubmitButton.setVisibility(GONE);
}
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index d1a51964d7d9..d6cb61dfa708 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -139,11 +139,6 @@ import com.android.internal.widget.EditableInputConnection;
import org.xmlpull.v1.XmlPullParserException;
-import com.android.internal.util.FastMath;
-import com.android.internal.widget.EditableInputConnection;
-
-import org.xmlpull.v1.XmlPullParserException;
-
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.BreakIterator;
@@ -7966,8 +7961,12 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener
startSelectionActionMode();
} else {
hideControllers();
- if (hasInsertionController() && !selectAllGotFocus && mText.length() > 0) {
- getInsertionController().show();
+ if (!selectAllGotFocus && mText.length() > 0) {
+ if (isCursorInsideEasyCorrectionSpan()) {
+ showSuggestions();
+ } else if (hasInsertionController()) {
+ getInsertionController().show();
+ }
}
}
}
@@ -7980,6 +7979,22 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener
return superResult;
}
+ /**
+ * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
+ * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
+ */
+ private boolean isCursorInsideEasyCorrectionSpan() {
+ Spannable spannable = (Spannable) TextView.this.mText;
+ SuggestionSpan[] suggestionSpans = spannable.getSpans(getSelectionStart(),
+ getSelectionEnd(), SuggestionSpan.class);
+ for (int i = 0; i < suggestionSpans.length; i++) {
+ if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (mMovement != null && mText instanceof Spannable && mLayout != null) {
diff --git a/core/java/com/android/internal/view/menu/ActionMenuView.java b/core/java/com/android/internal/view/menu/ActionMenuView.java
index 267221bec8a4..d6139218e3d0 100644
--- a/core/java/com/android/internal/view/menu/ActionMenuView.java
+++ b/core/java/com/android/internal/view/menu/ActionMenuView.java
@@ -109,6 +109,13 @@ public class ActionMenuView extends LinearLayout implements MenuBuilder.ItemInvo
// Divide the view into cells.
final int cellCount = widthSize / mMinCellSize;
final int cellSizeRemaining = widthSize % mMinCellSize;
+
+ if (cellCount == 0) {
+ // Give up, nothing fits.
+ setMeasuredDimension(widthSize, 0);
+ return;
+ }
+
final int cellSize = mMinCellSize + cellSizeRemaining / cellCount;
int cellsRemaining = cellCount;
@@ -213,7 +220,8 @@ public class ActionMenuView extends LinearLayout implements MenuBuilder.ItemInvo
}
}
- final int extraPixels = (int) (cellsRemaining * cellSize / expandCount);
+ final int extraPixels = expandCount > 0 ?
+ (int) (cellsRemaining * cellSize / expandCount) : 0;
for (int i = 0; i < childCount; i++) {
if ((smallestItemsAt & (1 << i)) == 0) continue;
diff --git a/core/jni/android/graphics/TextLayoutCache.cpp b/core/jni/android/graphics/TextLayoutCache.cpp
index 23a4ec741f99..89440c9dc0bd 100644
--- a/core/jni/android/graphics/TextLayoutCache.cpp
+++ b/core/jni/android/graphics/TextLayoutCache.cpp
@@ -360,31 +360,7 @@ void TextLayoutCacheValue::setupShaperItem(HB_ShaperItem* shaperItem, HB_FontRec
shaperItem->item.length = count;
shaperItem->item.bidiLevel = isRTL;
- ssize_t nextCodePoint = 0;
- uint32_t codePoint = utf16_to_code_point(chars, count, &nextCodePoint);
-
- HB_Script script = code_point_to_script(codePoint);
-
- if (script == HB_Script_Inherited) {
-#if DEBUG_GLYPHS
- LOGD("Cannot find a correct script for code point=%d "
- " Need to look at the next code points.", codePoint);
-#endif
- while (script == HB_Script_Inherited && nextCodePoint < count) {
- codePoint = utf16_to_code_point(chars, count, &nextCodePoint);
- script = code_point_to_script(codePoint);
- }
- }
-
- if (script == HB_Script_Inherited) {
-#if DEBUG_GLYPHS
- LOGD("Cannot find a correct script from the text."
- " Need to select a default script depending on the passed text direction.");
-#endif
- script = isRTL ? HB_Script_Arabic : HB_Script_Common;
- }
-
- shaperItem->item.script = script;
+ shaperItem->item.script = isRTL ? HB_Script_Arabic : HB_Script_Common;
shaperItem->string = chars;
shaperItem->stringLength = contextCount;
diff --git a/core/jni/android_view_GLES20Canvas.cpp b/core/jni/android_view_GLES20Canvas.cpp
index 039c5ba32ce1..80c79fd9dbdc 100644
--- a/core/jni/android_view_GLES20Canvas.cpp
+++ b/core/jni/android_view_GLES20Canvas.cpp
@@ -683,6 +683,12 @@ static void android_view_GLES20Canvas_updateTextureLayer(JNIEnv* env, jobject cl
LayerRenderer::updateTextureLayer(layer, width, height, isOpaque, renderTarget, transform);
}
+static void android_view_GLES20Canvas_setTextureLayerTransform(JNIEnv* env, jobject clazz,
+ Layer* layer, SkMatrix* matrix) {
+
+ layer->getTransform().load(*matrix);
+}
+
static void android_view_GLES20Canvas_destroyLayer(JNIEnv* env, jobject clazz, Layer* layer) {
LayerRenderer::destroyLayer(layer);
}
@@ -827,6 +833,7 @@ static JNINativeMethod gMethods[] = {
{ "nCreateTextureLayer", "(Z[I)I", (void*) android_view_GLES20Canvas_createTextureLayer },
{ "nUpdateTextureLayer", "(IIIZLandroid/graphics/SurfaceTexture;)V",
(void*) android_view_GLES20Canvas_updateTextureLayer },
+ { "nSetTextureLayerTransform", "(II)V", (void*) android_view_GLES20Canvas_setTextureLayerTransform },
{ "nDestroyLayer", "(I)V", (void*) android_view_GLES20Canvas_destroyLayer },
{ "nDestroyLayerDeferred", "(I)V", (void*) android_view_GLES20Canvas_destroyLayerDeferred },
{ "nDrawLayer", "(IIFFI)V", (void*) android_view_GLES20Canvas_drawLayer },
diff --git a/core/res/res/drawable-hdpi/day_picker_week_view_dayline_holo.9.png b/core/res/res/drawable-hdpi/day_picker_week_view_dayline_holo.9.png
index 2edae8ff8382..1deaad714971 100644
--- a/core/res/res/drawable-hdpi/day_picker_week_view_dayline_holo.9.png
+++ b/core/res/res/drawable-hdpi/day_picker_week_view_dayline_holo.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_commit.png b/core/res/res/drawable-hdpi/ic_commit.png
deleted file mode 100644
index 404051c55688..000000000000
--- a/core/res/res/drawable-hdpi/ic_commit.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_commit_search_api_holo_dark.png b/core/res/res/drawable-hdpi/ic_commit_search_api_holo_dark.png
new file mode 100644
index 000000000000..83f36a94cf14
--- /dev/null
+++ b/core/res/res/drawable-hdpi/ic_commit_search_api_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_commit_search_api_holo_light.png b/core/res/res/drawable-hdpi/ic_commit_search_api_holo_light.png
index b01688fa3225..a3cc21e6ba3d 100644
--- a/core/res/res/drawable-hdpi/ic_commit_search_api_holo_light.png
+++ b/core/res/res/drawable-hdpi/ic_commit_search_api_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/day_picker_week_view_dayline_holo.9.png b/core/res/res/drawable-mdpi/day_picker_week_view_dayline_holo.9.png
index a8cfd773cb34..7b750192462e 100644
--- a/core/res/res/drawable-mdpi/day_picker_week_view_dayline_holo.9.png
+++ b/core/res/res/drawable-mdpi/day_picker_week_view_dayline_holo.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_commit_search_api_holo_dark.png b/core/res/res/drawable-mdpi/ic_commit_search_api_holo_dark.png
new file mode 100644
index 000000000000..844c99c22f9c
--- /dev/null
+++ b/core/res/res/drawable-mdpi/ic_commit_search_api_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_commit_search_api_holo_light.png b/core/res/res/drawable-mdpi/ic_commit_search_api_holo_light.png
index c048f41ca290..86c170e97b10 100644
--- a/core/res/res/drawable-mdpi/ic_commit_search_api_holo_light.png
+++ b/core/res/res/drawable-mdpi/ic_commit_search_api_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/day_picker_week_view_dayline_holo.9.png b/core/res/res/drawable-xhdpi/day_picker_week_view_dayline_holo.9.png
index bc6a6e47569b..701a1b24d042 100644
--- a/core/res/res/drawable-xhdpi/day_picker_week_view_dayline_holo.9.png
+++ b/core/res/res/drawable-xhdpi/day_picker_week_view_dayline_holo.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_dark.png b/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_dark.png
new file mode 100644
index 000000000000..d8faf900ae77
--- /dev/null
+++ b/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_light.png b/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_light.png
index 7b1054a50869..e7c7280add8f 100644
--- a/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_light.png
+++ b/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_light.png
Binary files differ
diff --git a/core/res/res/layout/search_bar.xml b/core/res/res/layout/search_bar.xml
index 673c96c62364..c81c716b04b6 100644
--- a/core/res/res/layout/search_bar.xml
+++ b/core/res/res/layout/search_bar.xml
@@ -38,7 +38,7 @@
<LinearLayout
android:id="@id/closeButton"
android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ android:layout_height="48dp"
android:orientation="horizontal"
android:focusable="true"
android:background="?android:attr/selectableItemBackground">
@@ -51,9 +51,10 @@
<ImageView
android:id="@+id/search_app_icon"
- android:layout_height="48dip"
- android:layout_width="48dip"
+ android:layout_height="32dip"
+ android:layout_width="32dip"
android:layout_gravity="center_vertical"
+ android:scaleType="centerInside"
/>
</LinearLayout>
diff --git a/core/res/res/layout/search_view.xml b/core/res/res/layout/search_view.xml
index 03e870611f0f..0ffd571ce1e2 100644
--- a/core/res/res/layout/search_view.xml
+++ b/core/res/res/layout/search_view.xml
@@ -22,8 +22,6 @@
android:id="@+id/search_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
- android:paddingLeft="8dip"
- android:paddingRight="8dip"
android:orientation="horizontal"
>
@@ -59,6 +57,8 @@
android:layout_gravity="center_vertical"
android:layout_marginTop="4dip"
android:layout_marginBottom="4dip"
+ android:layout_marginLeft="8dip"
+ android:layout_marginRight="8dip"
android:orientation="horizontal">
<ImageView
@@ -105,7 +105,7 @@
<ImageView
android:id="@+id/search_close_btn"
- android:layout_width="@dimen/dropdownitem_icon_width"
+ android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingLeft="8dip"
android:paddingRight="8dip"
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index f63eb62379af..40355e33753d 100755
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -152,6 +152,18 @@
<!-- Text color, typeface, size, and style for small text inside of a popup menu. -->
<attr name="textAppearanceSmallPopupMenu" format="reference" />
+ <!-- The underline color and thickness for easy correct suggestion -->
+ <attr name="textAppearanceEasyCorrectSuggestion" format="reference" />
+
+ <!-- The underline color and thickness for misspelled suggestion -->
+ <attr name="textAppearanceMisspelledSuggestion" format="reference" />
+
+ <!-- The underline color -->
+ <attr name="textUnderlineColor" format="reference|color" />
+ <!-- The underline thickness, expressed as a percentage of the default underline thickness
+ (i.e., 100 means default thickness, and 200 means double thickness). -->
+ <attr name="textUnderlineThicknessPercentage" format="reference|integer" />
+
<!-- EditText text foreground color. -->
<attr name="editTextColor" format="reference|color" />
<!-- EditText background drawable. -->
@@ -3136,6 +3148,10 @@
<!-- Present the text in ALL CAPS. This may use a small-caps form when available. -->
<attr name="textAllCaps" />
</declare-styleable>
+ <declare-styleable name="SuggestionSpan">
+ <attr name="textUnderlineColor" />
+ <attr name="textUnderlineThicknessPercentage" />
+ </declare-styleable>
<!-- An <code>input-extras</code> is a container for extra data to supply to
an input method. Contains
one more more {@link #Extra <extra>} tags. -->
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 3f67d1ba6f64..74989e617eac 100755
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -116,6 +116,7 @@
<item>"mobile_fota,10,0,2,60000,true"</item>
<item>"mobile_ims,11,0,2,60000,true"</item>
<item>"mobile_cbs,12,0,2,60000,true"</item>
+ <item>"wifi_p2p,13,1,0,-1,true"</item>
</string-array>
<!-- Array of ConnectivityManager.TYPE_xxxx constants for networks that may only
diff --git a/core/res/res/values/dimens.xml b/core/res/res/values/dimens.xml
index 92953888dcb8..8855645c4a9d 100644
--- a/core/res/res/values/dimens.xml
+++ b/core/res/res/values/dimens.xml
@@ -125,6 +125,9 @@
<!-- Minimum width of the search view text entry area. -->
<dimen name="search_view_text_min_width">160dip</dimen>
+ <!-- Preferred width of the search view. -->
+ <dimen name="search_view_preferred_width">320dip</dimen>
+
<!-- Dialog title height -->
<dimen name="alert_dialog_title_height">64dip</dimen>
<!-- Dialog button bar height -->
@@ -155,12 +158,12 @@
<dimen name="default_gap">16dip</dimen>
<!-- Text padding for dropdown items -->
- <dimen name="dropdownitem_text_padding_left">6dip</dimen>
+ <dimen name="dropdownitem_text_padding_left">8dip</dimen>
<!-- Text padding for dropdown items -->
- <dimen name="dropdownitem_text_padding_right">6dip</dimen>
+ <dimen name="dropdownitem_text_padding_right">8dip</dimen>
<!-- Width of the icon in a dropdown list -->
- <dimen name="dropdownitem_icon_width">48dip</dimen>
+ <dimen name="dropdownitem_icon_width">32dip</dimen>
</resources>
diff --git a/core/res/res/values/styles.xml b/core/res/res/values/styles.xml
index d54eddf04fa3..6f2f1e57056e 100644
--- a/core/res/res/values/styles.xml
+++ b/core/res/res/values/styles.xml
@@ -243,6 +243,18 @@ please see styles_device_defaults.xml.
<item name="android:textStyle">bold</item>
</style>
+ <style name="TextAppearance.Suggestion">
+ <item name="android:textUnderlineThicknessPercentage">200</item>
+ </style>
+
+ <style name="TextAppearance.EasyCorrectSuggestion" parent="TextAppearance.Suggestion">
+ <item name="android:textUnderlineColor">@color/holo_blue_dark</item>
+ </style>
+
+ <style name="TextAppearance.MisspelledSuggestion" parent="TextAppearance.Suggestion">
+ <item name="android:textUnderlineColor">@color/holo_red_light</item>
+ </style>
+
<!-- Widget Styles -->
<style name="Widget">
diff --git a/core/res/res/values/themes.xml b/core/res/res/values/themes.xml
index 397278ccac69..786cdb544f94 100644
--- a/core/res/res/values/themes.xml
+++ b/core/res/res/values/themes.xml
@@ -88,7 +88,10 @@ please see themes_device_defaults.xml.
<item name="textAppearanceSmallInverse">@android:style/TextAppearance.Small.Inverse</item>
<item name="textAppearanceSearchResultTitle">@android:style/TextAppearance.SearchResult.Title</item>
<item name="textAppearanceSearchResultSubtitle">@android:style/TextAppearance.SearchResult.Subtitle</item>
-
+
+ <item name="textAppearanceEasyCorrectSuggestion">@android:style/TextAppearance.EasyCorrectSuggestion</item>
+ <item name="textAppearanceMisspelledSuggestion">@android:style/TextAppearance.MisspelledSuggestion</item>
+
<item name="textAppearanceButton">@android:style/TextAppearance.Widget.Button</item>
<item name="editTextColor">?android:attr/textColorPrimaryInverse</item>
@@ -326,7 +329,7 @@ please see themes_device_defaults.xml.
<item name="searchViewSearchIcon">@android:drawable/ic_search</item>
<item name="searchViewGoIcon">@android:drawable/ic_go</item>
<item name="searchViewVoiceIcon">@android:drawable/ic_voice_search</item>
- <item name="searchViewEditQuery">@android:drawable/ic_commit</item>
+ <item name="searchViewEditQuery">@android:drawable/ic_commit_search_api_holo_dark</item>
<item name="searchViewEditQueryBackground">?attr/selectableItemBackground</item>
<item name="searchDialogTheme">@style/Theme.SearchBar</item>
diff --git a/data/fonts/Lohit_Hindi.ttf b/data/fonts/Lohit_Hindi.ttf
new file mode 100644
index 000000000000..73caae34aac0
--- /dev/null
+++ b/data/fonts/Lohit_Hindi.ttf
Binary files differ
diff --git a/data/fonts/fallback_fonts.xml b/data/fonts/fallback_fonts.xml
index 6ac615df2af4..1bee47a6a867 100644
--- a/data/fonts/fallback_fonts.xml
+++ b/data/fonts/fallback_fonts.xml
@@ -46,6 +46,11 @@
</family>
<family>
<fileset>
+ <file>Lohit_Hindi.ttf</file>
+ </fileset>
+ </family>
+ <family>
+ <fileset>
<file>DroidSansFallback.ttf</file>
</fileset>
</family>
diff --git a/data/fonts/fonts.mk b/data/fonts/fonts.mk
index 73fb11155f3b..d8c1fa2a83ad 100644
--- a/data/fonts/fonts.mk
+++ b/data/fonts/fonts.mk
@@ -31,6 +31,7 @@ PRODUCT_COPY_FILES := \
frameworks/base/data/fonts/DroidSerif-Italic.ttf:system/fonts/DroidSerif-Italic.ttf \
frameworks/base/data/fonts/DroidSerif-BoldItalic.ttf:system/fonts/DroidSerif-BoldItalic.ttf \
frameworks/base/data/fonts/DroidSansMono.ttf:system/fonts/DroidSansMono.ttf \
+ frameworks/base/data/fonts/Lohit_Hindi.ttf:system/fonts/Lohit_Hindi.ttf \
frameworks/base/data/fonts/Clockopia.ttf:system/fonts/Clockopia.ttf \
frameworks/base/data/fonts/DroidSansFallback.ttf:system/fonts/DroidSansFallback.ttf \
frameworks/base/data/fonts/AndroidClock.ttf:system/fonts/AndroidClock.ttf \
diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs
index 68c9a9161974..9c3a0bea18e8 100644
--- a/docs/html/guide/guide_toc.cs
+++ b/docs/html/guide/guide_toc.cs
@@ -244,7 +244,7 @@
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/graphics/opengl.html">
<span class="en">3D with OpenGL</span>
- </a></li>
+ </a><span class="new">updated</span></li>
<li><a href="<?cs var:toroot ?>guide/topics/graphics/animation.html">
<span class="en">Property Animation</span>
</a></li>
diff --git a/docs/html/guide/topics/graphics/opengl.jd b/docs/html/guide/topics/graphics/opengl.jd
index cc467f2ce8a1..2edc63d507b3 100644
--- a/docs/html/guide/topics/graphics/opengl.jd
+++ b/docs/html/guide/topics/graphics/opengl.jd
@@ -8,22 +8,37 @@ parent.link=index.html
<h2>In this document</h2>
<ol>
- <li><a href="#basics">The Basics</a></li>
+ <li><a href="#basics">The Basics</a>
+ <ol>
+ <li><a href="#packages">OpenGL packages</a></li>
+ </ol>
+ <li><a href="#manifest">Declaring OpenGL Requirements</a></li>
+ </li>
+ <li><a href="#coordinate-mapping">Coordinate Mapping for Drawn Objects</a>
+ <ol>
+ <li><a href="#proj-es1">Projection and camera in ES 1.0</a></li>
+ <li><a href="#proj-es1">Projection and camera in ES 2.0</a></li>
+ </ol>
+ </li>
<li><a href="#compatibility">OpenGL Versions and Device Compatibility</a>
<ol>
- <li><a href="#textures">Texture Compression Support</a></li>
- <li><a href="#declare-compression">Declaring Use of Compressed Textures</a></li>
+ <li><a href="#textures">Texture compression support</a></li>
+ <li><a href="#gl-extension-query">Determining OpenGL Extensions</a></li>
</ol>
</li>
+ <li><a href="#choosing-version">Choosing an OpenGL API Version</a></li>
</ol>
<h2>Key classes</h2>
<ol>
<li>{@link android.opengl.GLSurfaceView}</li>
<li>{@link android.opengl.GLSurfaceView.Renderer}</li>
- <li>{@link javax.microedition.khronos.opengles}</li>
- <li>{@link android.opengl}</li>
</ol>
- <h2>Related Samples</h2>
+ <h2>Related tutorials</h2>
+ <ol>
+ <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es10.html">OpenGL ES 1.0</a></li>
+ <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es20.html">OpenGL ES 2.0</a></li>
+ </ol>
+ <h2>Related samples</h2>
<ol>
<li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/
GLSurfaceViewActivity.html">GLSurfaceViewActivity</a></li>
@@ -46,11 +61,11 @@ GLSurfaceView</a></li>
</div>
<p>Android includes support for high performance 2D and 3D graphics with the Open Graphics Library
-(OpenGL) API&mdash;specifically, the OpenGL ES API. OpenGL is a cross-platform graphics API that
-specifies a standard software interface for 3D graphics processing hardware. OpenGL ES is a flavor
-of the OpenGL specification intended for embedded devices. The OpenGL ES 1.0 and 1.1 API
-specifications have been supported since Android 1.0. Beginning with Android 2.2 (API
-Level 8), the framework supports the OpenGL ES 2.0 API specification.</p>
+(OpenGL), specifically, the OpenGL ES API. OpenGL is a cross-platform graphics API that specifies a
+standard software interface for 3D graphics processing hardware. OpenGL ES is a flavor of the OpenGL
+specification intended for embedded devices. The OpenGL ES 1.0 and 1.1 API specifications have been
+supported since Android 1.0. Beginning with Android 2.2 (API Level 8), the framework supports the
+OpenGL ES 2.0 API specification.</p>
<p class="note"><b>Note:</b> The specific API provided by the Android framework is similar to the
J2ME JSR239 OpenGL ES API, but is not identical. If you are familiar with J2ME JSR239
@@ -71,18 +86,19 @@ understanding how to implement these classes in an activity should be your first
</p>
<dl>
- <dt>{@link android.opengl.GLSurfaceView}</dt>
- <dd>This class is a container on which you can draw and manipulate objects using OpenGL API calls.
- This class is similar in function to a {@link android.view.SurfaceView}, except that it is
- specifically for use with OpenGL. You can use this class by simply creating an instance of
- {@link android.opengl.GLSurfaceView} and adding your
+ <dt><strong>{@link android.opengl.GLSurfaceView}</strong></dt>
+ <dd>This class is a {@link android.view.View} where you can draw and manipulate objects using
+ OpenGL API calls and is similar in function to a {@link android.view.SurfaceView}. You can use
+ this class by creating an instance of {@link android.opengl.GLSurfaceView} and adding your
{@link android.opengl.GLSurfaceView.Renderer Renderer} to it. However, if you want to capture
touch screen events, you should extend the {@link android.opengl.GLSurfaceView} class to
- implement the touch listeners, as shown in the <a
+ implement the touch listeners, as shown in OpenGL Tutorials for
+ <a href="{@docRoot}resources/tutorials/opengl/opengl-es10.html#touch">ES 1.0</a>,
+ <a href="{@docRoot}resources/tutorials/opengl/opengl-es20.html#touch">ES 2.0</a> and the <a
href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/TouchRotateActivity
.html">TouchRotateActivity</a> sample.</dd>
- <dt>{@link android.opengl.GLSurfaceView.Renderer}</dt>
+ <dt><strong>{@link android.opengl.GLSurfaceView.Renderer}</strong></dt>
<dd>This interface defines the methods required for drawing graphics in an OpenGL {@link
android.opengl.GLSurfaceView}. You must provide an implementation of this interface as a
separate class and attach it to your {@link android.opengl.GLSurfaceView} instance using
@@ -119,6 +135,7 @@ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics
</dd>
</dl>
+<h3 id="packages">OpenGL packages</h3>
<p>Once you have established a container view for OpenGL using {@link
android.opengl.GLSurfaceView} and {@link android.opengl.GLSurfaceView.Renderer}, you can begin
calling OpenGL APIs using the following classes:</p>
@@ -126,8 +143,17 @@ calling OpenGL APIs using the following classes:</p>
<ul>
<li>OpenGL ES 1.0/1.1 API Packages
<ul>
+ <li>{@link android.opengl} - This package provides a static interface to the OpenGL ES
+1.0/1.1 classes and better performance than the javax.microedition.khronos package interfaces.
+ <ul>
+ <li>{@link android.opengl.GLES10}</li>
+ <li>{@link android.opengl.GLES10Ext}</li>
+ <li>{@link android.opengl.GLES11}</li>
+ <li>{@link android.opengl.GLES10Ext}</li>
+ </ul>
+ </li>
<li>{@link javax.microedition.khronos.opengles} - This package provides the standard
-implementation of OpenGL ES 1.0 and 1.1.
+implementation of OpenGL ES 1.0/1.1.
<ul>
<li>{@link javax.microedition.khronos.opengles.GL10}</li>
<li>{@link javax.microedition.khronos.opengles.GL10Ext}</li>
@@ -136,42 +162,243 @@ implementation of OpenGL ES 1.0 and 1.1.
<li>{@link javax.microedition.khronos.opengles.GL11ExtensionPack}</li>
</ul>
</li>
- <li>{@link android.opengl} - This package provides a static interface to the OpenGL classes
- above. These interfaces were added with Android 1.6 (API Level 4).
- <ul>
- <li>{@link android.opengl.GLES10}</li>
- <li>{@link android.opengl.GLES10Ext}</li>
- <li>{@link android.opengl.GLES11}</li>
- <li>{@link android.opengl.GLES10Ext}</li>
- </ul>
- </li>
</ul>
</li>
<li>OpenGL ES 2.0 API Class
<ul>
- <li>{@link android.opengl.GLES20 android.opengl.GLES20}</li>
+ <li>{@link android.opengl.GLES20 android.opengl.GLES20} - This package provides the
+interface to OpenGL ES 2.0 and is available starting with Android 2.2 (API Level 8).</li>
</ul>
</li>
</ul>
+<p>If you'd like to start building an app with OpenGL right away, have a look at the tutorials for
+<a href="{@docRoot}resources/tutorials/opengl/opengl-es10.html">OpenGL ES 1.0</a> or
+<a href="{@docRoot}resources/tutorials/opengl/opengl-es20.html">OpenGL ES 2.0</a>!
+</p>
+
+<h2 id="manifest">Declaring OpenGL Requirements</h2>
+<p>If your application uses OpenGL features that are not available on all devices, you must include
+these requirements in your <a
+href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a></code> file.
+Here are the most common OpenGL manifest declarations:</p>
+
+<ul>
+ <li><strong>OpenGL ES version requirements</strong> - If your application only supports OpenGL ES
+2.0, you must declare that requirement by adding the following settings to your manifest as
+shown below.
+
+<pre>
+ &lt;!-- Tell the system this app requires OpenGL ES 2.0. --&gt;
+ &lt;uses-feature android:glEsVersion="0x00020000" android:required="true" /&gt;
+</pre>
+
+ <p>Adding this declaration causes the Android Market to restrict your application from being
+ installed on devices that do not support OpenGL ES 2.0.</p>
+ </li>
+ <li><strong>Texture compression requirements</strong> - If your application uses texture
+compression formats that are not supported by all devices, you must declare them in your manifest
+file using <a href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html">
+{@code &lt;supports-gl-texture&gt;}</a>. For more information about available texture compression
+formats, see <a href="#textures">Texture compression support</a>.
+
+<p>Declaring texture compression requirements in your manifest hides your application from users
+with devices that do not support at least one of your declared compression types. For more
+information on how Android Market filtering works for texture compressions, see the <a
+href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html#market-texture-filtering">
+Android Market and texture compression filtering</a> section of the {@code
+&lt;supports-gl-texture&gt;} documentation.</p>
+ </li>
+</ul>
+
+
+<h2 id="coordinate-mapping">Coordinate Mapping for Drawn Objects</h2>
+
+<p>One of the basic problems in displaying graphics on Android devices is that their screens can
+vary in size and shape. OpenGL assumes a square, uniform coordinate system and, by default, happily
+draws those coordinates onto your typically non-square screen as if it is perfectly square.</p>
+
+<img src="{@docRoot}images/opengl/coordinates.png">
+<p class="img-caption">
+ <strong>Figure 1.</strong> Default OpenGL coordinate system (left) mapped to a typical Android
+device screen (right).
+</p>
+
+<p>The illustration above shows the uniform coordinate system assumed for an OpenGL frame on the
+left, and how these coordinates actually map to a typical device screen in landscape orientation
+on the right. To solve this problem, you can apply OpenGL projection modes and camera views to
+transform coordinates so your graphic objects have the correct proportions on any display.</p>
+
+<p>In order to apply projection and camera views, you create a projection matrix and a camera view
+matrix and apply them to the OpenGL rendering pipeline. The projection matrix recalculates the
+coordinates of your graphics so that they map correctly to Android device screens. The camera view
+matrix creates a transformation that renders objects from a specific eye position.</p>
+
+<h3 id="proj-es1">Projection and camera view in OpenGL ES 1.0</h3>
+<p>In the ES 1.0 API, you apply projection and camera view by creating each matrix and then
+adding them to the OpenGL environment.</p>
+
+<ol>
+<li><strong>Projection matrix</strong> - Create a projection matrix using the geometry of the
+device screen in order to recalculate object coordinates so they are drawn with correct proportions.
+The following example code demonstrates how to modify the {@code onSurfaceChanged()} method of a
+{@link android.opengl.GLSurfaceView.Renderer} implementation to create a projection matrix based on
+the screen's aspect ratio and apply it to the OpenGL rendering environment.
+
+<pre>
+ public void onSurfaceChanged(GL10 gl, int width, int height) {
+ gl.glViewport(0, 0, width, height);
+
+ // make adjustments for screen ratio
+ float ratio = (float) width / height;
+ gl.glMatrixMode(GL10.GL_PROJECTION); // set matrix to projection mode
+ gl.glLoadIdentity(); // reset the matrix to its default state
+ gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); // apply the projection matrix
+ }
+</pre>
+</li>
+
+<li><strong>Camera transformation matrix</strong> - Once you have adjusted the coordinate system
+using a projection matrix, you must also apply a camera view. The following example code shows how
+to modify the {@code onDrawFrame()} method of a {@link android.opengl.GLSurfaceView.Renderer}
+implementation to apply a model view and use the {@link
+android.opengl.GLU#gluLookAt(javax.microedition.khronos.opengles.GL10, float, float, float, float,
+float, float, float, float, float) GLU.gluLookAt()} utility to create a viewing tranformation which
+simulates a camera position.
+
+<pre>
+ public void onDrawFrame(GL10 gl) {
+ ...
+ // Set GL_MODELVIEW transformation mode
+ gl.glMatrixMode(GL10.GL_MODELVIEW);
+ gl.glLoadIdentity(); // reset the matrix to its default state
+
+ // When using GL_MODELVIEW, you must set the camera view
+ GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
+ ...
+ }
+</pre>
+</li>
+</ol>
+
+<p>For a complete example of how to apply projection and camera views with OpenGL ES 1.0, see the <a
+href="{@docRoot}resources/tutorials/opengl/opengl-es10.html#projection-and-views">OpenGL ES 1.0
+tutorial</a>.</p>
+
+
+<h3 id="proj-es2">Projection and camera view in OpenGL ES 2.0</h3>
+<p>In the ES 2.0 API, you apply projection and camera view by first adding a matrix member to
+the vertex shaders of your graphics objects. With this matrix member added, you can then
+generate and apply projection and camera viewing matrices to your objects.</p>
+
+<ol>
+<li><strong>Add matrix to vertex shaders</strong> - Create a variable for the view projection matrix
+and include it as a multiplier of the shader's position. In the following example vertex shader
+code, the included {@code uMVPMatrix} member allows you to apply projection and camera viewing
+matrices to the coordinates of objects that use this shader.
+
+<pre>
+ private final String vertexShaderCode =
+
+ // This matrix member variable provides a hook to manipulate
+ // the coordinates of objects that use this vertex shader
+ "uniform mat4 uMVPMatrix; \n" +
+
+ "attribute vec4 vPosition; \n" +
+ "void main(){ \n" +
+
+ // the matrix must be included as part of gl_Position
+ " gl_Position = uMVPMatrix * vPosition; \n" +
+
+ "} \n";
+</pre>
+ <p class="note"><strong>Note:</strong> The example above defines a single transformation matrix
+member in the vertex shader into which you apply a combined projection matrix and camera view
+matrix. Depending on your application requirements, you may want to define separate projection
+matrix and camera viewing matrix members in your vertex shaders so you can change them
+independently.</p>
+</li>
+<li><strong>Access the shader matrix</strong> - After creating a hook in your vertex shaders to
+apply projection and camera view, you can then access that variable to apply projection and
+camera viewing matrices. The following code shows how to modify the {@code onSurfaceCreated()}
+method of a {@link android.opengl.GLSurfaceView.Renderer} implementation to access the matrix
+variable defined in the vertex shader above.
+
+<pre>
+ public void onSurfaceCreated(GL10 unused, EGLConfig config) {
+ ...
+ muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
+ ...
+ }
+</pre>
+</li>
+<li><strong>Create projection and camera viewing matrices</strong> - Generate the projection and
+viewing matrices to be applied the graphic objects. The following example code shows how to modify
+the {@code onSurfaceCreated()} and {@code onSurfaceChanged()} methods of a {@link
+android.opengl.GLSurfaceView.Renderer} implementation to create camera view matrix and a projection
+matrix based on the screen aspect ratio of the device.
+
+<pre>
+ public void onSurfaceCreated(GL10 unused, EGLConfig config) {
+ ...
+ // Create a camera view matrix
+ Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
+ }
+
+ public void onSurfaceChanged(GL10 unused, int width, int height) {
+ GLES20.glViewport(0, 0, width, height);
+
+ float ratio = (float) width / height;
+
+ // create a projection matrix from device screen geometry
+ Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
+ }
+</pre>
+</li>
+
+<li><strong>Apply projection and camera viewing matrices</strong> - To apply the projection and
+camera view transformations, multiply the matrices together and then set them into the vertex
+shader. The following example code shows how modify the {@code onDrawFrame()} method of a {@link
+android.opengl.GLSurfaceView.Renderer} implementation to combine the projection matrix and camera
+view created in the code above and then apply it to the graphic objects to be rendered by OpenGL.
+
+<pre>
+ public void onDrawFrame(GL10 unused) {
+ ...
+ // Combine the projection and camera view matrices
+ Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);
+
+ // Apply the combined projection and camera view transformations
+ GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
+
+ // Draw objects
+ ...
+ }
+</pre>
+</li>
+</ol>
+<p>For a complete example of how to apply projection and camera view with OpenGL ES 2.0, see the <a
+href="{@docRoot}resources/tutorials/opengl/opengl-es20.html#projection-and-views">OpenGL ES 2.0
+tutorial</a>.</p>
+
+
<h2 id="compatibility">OpenGL Versions and Device Compatibility</h2>
-<p>
- The OpenGL ES 1.0 and 1.1 API specifications have been supported since Android 1.0.
+<p>The OpenGL ES 1.0 and 1.1 API specifications have been supported since Android 1.0.
Beginning with Android 2.2 (API Level 8), the framework supports the OpenGL ES 2.0 API
specification. OpenGL ES 2.0 is supported by most Android devices and is recommended for new
applications being developed with OpenGL. For information about the relative number of
Android-powered devices that support a given version of OpenGL ES, see the <a
href="{@docRoot}resources/dashboard/opengl.html">OpenGL ES Versions Dashboard</a>.</p>
+
<h3 id="textures">Texture compression support</h3>
<p>Texture compression can significantly increase the performance of your OpenGL application by
reducing memory requirements and making more efficient use of memory bandwidth. The Android
framework provides support for the ETC1 compression format as a standard feature, including a {@link
-android.opengl.ETC1Util} utility class and the {@code etc1tool} compression tool (located in your
-Android SDK at {@code &lt;sdk&gt;/tools/}).</p>
-
-<p>For an example of an Android application that uses texture compression, see the <a
+android.opengl.ETC1Util} utility class and the {@code etc1tool} compression tool (located in the
+Android SDK at {@code &lt;sdk&gt;/tools/}). For an example of an Android application that uses
+texture compression, see the <a
href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/
CompressedTextureActivity.html">CompressedTextureActivity</a> code sample.
</p>
@@ -184,34 +411,110 @@ alpha channel. If your application requires textures with an alpha channel, you
investigate other texture compression formats available on your target devices.</p>
<p>Beyond the ETC1 format, Android devices have varied support for texture compression based on
-their GPU chipsets. You should investigate texture compression support on the the devices you are
-are targeting to determine what compression types your application should support.</p>
+their GPU chipsets and OpenGL implementations. You should investigate texture compression support on
+the the devices you are are targeting to determine what compression types your application should
+support. In order to determine what texture formats are supported on a given device, you must <a
+href="#gl-extension-query">query the device</a> and review the <em>OpenGL extension names</em>,
+which identify what texture compression formats (and other OpenGL features) are supported by the
+device. Some commonly supported texture compression formats are as follows:</p>
-<p>To determine if texture compression formats other than ETC1 are supported on a particular
-device:</p>
+<ul>
+ <li><strong>ATITC (ATC)</strong> - ATI texture compression (ATITC or ATC) is available on a
+wide variety of devices and supports fixed rate compression for RGB textures with and without
+an alpha channel. This format may be represented by several OpenGL extension names, for example:
+ <ul>
+ <li>{@code GL_AMD_compressed_ATC_texture}</li>
+ <li>{@code GL_ATI_texture_compression_atitc}</li>
+ </ul>
+ </li>
+ <li><strong>PVRTC</strong> - PowerVR texture compression (PVRTC) is available on a wide
+variety of devices and supports 2-bit and 4-bit per pixel textures with or without an alpha channel.
+This format is represented by the following OpenGL extension name:
+ <ul>
+ <li>{@code GL_IMG_texture_compression_pvrtc}</li>
+ </ul>
+ </li>
+ <li><strong>S3TC (DXT<em>n</em>/DXTC)</strong> - S3 texture compression (S3TC) has several
+format variations (DXT1 to DXT5) and is less widely available. The format supports RGB textures with
+4-bit alpha or 8-bit alpha channels. This format may be represented by several OpenGL extension
+names, for example:
+ <ul>
+ <li>{@code GL_OES_texture_compression_S3TC}</li>
+ <li>{@code GL_EXT_texture_compression_s3tc}</li>
+ <li>{@code GL_EXT_texture_compression_dxt1}</li>
+ <li>{@code GL_EXT_texture_compression_dxt3}</li>
+ <li>{@code GL_EXT_texture_compression_dxt5}</li>
+ </ul>
+ </li>
+ <li><strong>3DC</strong> - 3DC texture compression (3DC) is a less widely available format that
+supports RGB textures with an an alpha channel. This format is represented by the following OpenGL
+extension name:</li>
+ <ul>
+ <li>{@code GL_AMD_compressed_3DC_texture}</li>
+ </ul>
+</ul>
+
+<p class="warning"><strong>Warning:</strong> These texture compression formats are <em>not
+supported</em> on all devices. Support for these formats can vary by manufacturer and device. For
+information on how to determine what texture compression formats are on a particular device, see
+the next section.
+</p>
+
+<p class="note"><strong>Note:</strong> Once you decide which texture compression formats your
+application will support, make sure you declare them in your manifest using <a
+href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html">&lt;supports-gl-texture&gt;
+</a>. Using this declaration enables filtering by external services such as Android Market, so that
+your app is installed only on devices that support the formats your app requires. For details, see
+<a
+href="{@docRoot}guide/topics/graphics/opengl.html#manifest">OpenGL manifest declarations</a>.</p>
+
+<h3 id="gl-extension-query">Determining OpenGL extensions</h3>
+<p>Implementations of OpenGL vary by Android device in terms of the extensions to the OpenGL ES API
+that are supported. These extensions include texture compressions, but typically also include other
+extensions to the OpenGL feature set.</p>
+
+<p>To determine what texture compression formats, and other OpenGL extensions, are supported on a
+particular device:</p>
<ol>
<li>Run the following code on your target devices to determine what texture compression
formats are supported:
<pre>
String extensions = javax.microedition.khronos.opengles.GL10.glGetString(GL10.GL_EXTENSIONS);
</pre>
- <p class="warning"><b>Warning:</b> The results of this call vary by device! You must run this
-call on several target devices to determine what compression types are commonly supported on
-your target devices.</p>
+ <p class="warning"><b>Warning:</b> The results of this call <em>vary by device!</em> You
+must run this call on several target devices to determine what compression types are commonly
+supported.</p>
</li>
- <li>Review the output of this method to determine what extensions are supported on the
+ <li>Review the output of this method to determine what OpenGL extensions are supported on the
device.</li>
</ol>
-<h3 id="declare-compression">Declaring compressed textures</h3>
-<p>Once you have decided which texture compression types your application will support, you
-must declare them in your manifest file using <a
-href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html">
-&lt;supports-gl-texture&gt;</a>. Declaring this information in your manifest file hides your
-application from users with devices that do not support at least one of your declared
-compression types. For more information on how Android Market filtering works for texture
-compressions, see the <a
-href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html#market-texture-filtering">
-Android Market and texture compression filtering</a> section of the {@code
-&lt;supports-gl-texture&gt;} documentation.
+<h2 id="choosing-version">Choosing an OpenGL API Version</h2>
+
+<p>OpenGL ES API version 1.0 (and the 1.1 extensions) and version 2.0 both provide high
+performance graphics interfaces for creating 3D games, visualizations and user interfaces. Graphics
+programming for the OpenGL ES 1.0/1.1 API versus ES 2.0 differs significantly, and so developers
+should carefully consider the following factors before starting development with either API:</p>
+
+<ul>
+ <li><strong>Performance</strong> - In general, OpenGL ES 2.0 provides faster graphics performance
+than the ES 1.0/1.1 APIs. However, the performance difference can vary depending on the Android
+device your OpenGL application is running on, due to differences in the implementation of the OpenGL
+graphics pipeline.</li>
+ <li><strong>Device Compatibility</strong> - Developers should consider the types of devices,
+Android versions and the OpenGL ES versions available to their customers. For more information
+on OpenGL compatibility across devices, see the <a href="#compatibility">OpenGL Versions and Device
+Compatibility</a> section.</li>
+ <li><strong>Coding Convenience</strong> - The OpenGL ES 1.0/1.1 API provides a fixed function
+pipeline and convenience functions which are not available in the ES 2.0 API. Developers who are new
+to OpenGL may find coding for OpenGL ES 1.0/1.1 faster and more convenient.</li>
+ <li><strong>Graphics Control</strong> - The OpenGL ES 2.0 API provides a higher degree
+of control by providing a fully programmable pipeline through the use of shaders. With more
+direct control of the graphics processing pipeline, developers can create effects that would be
+very difficult to generate using the 1.0/1.1 API.</li>
+</ul>
+
+<p>While performance, compatibility, convenience, control and other factors may influence your
+decision, you should pick an OpenGL API version based on what you think provides the best experience
+for your users.</p>
diff --git a/docs/html/images/opengl/coordinates.png b/docs/html/images/opengl/coordinates.png
new file mode 100644
index 000000000000..7180cd5cecf3
--- /dev/null
+++ b/docs/html/images/opengl/coordinates.png
Binary files differ
diff --git a/docs/html/images/opengl/helloopengl-es10-1.png b/docs/html/images/opengl/helloopengl-es10-1.png
new file mode 100644
index 000000000000..9aa2376ed720
--- /dev/null
+++ b/docs/html/images/opengl/helloopengl-es10-1.png
Binary files differ
diff --git a/docs/html/images/opengl/helloopengl-es10-2.png b/docs/html/images/opengl/helloopengl-es10-2.png
new file mode 100644
index 000000000000..cdfd9c70539a
--- /dev/null
+++ b/docs/html/images/opengl/helloopengl-es10-2.png
Binary files differ
diff --git a/docs/html/images/opengl/helloopengl-es20-1.png b/docs/html/images/opengl/helloopengl-es20-1.png
new file mode 100644
index 000000000000..1f76c22cb23b
--- /dev/null
+++ b/docs/html/images/opengl/helloopengl-es20-1.png
Binary files differ
diff --git a/docs/html/images/opengl/helloopengl-es20-2.png b/docs/html/images/opengl/helloopengl-es20-2.png
new file mode 100644
index 000000000000..0fbbe60010e3
--- /dev/null
+++ b/docs/html/images/opengl/helloopengl-es20-2.png
Binary files differ
diff --git a/docs/html/resources/resources-data.js b/docs/html/resources/resources-data.js
index 0fc10bf746ce..720e14314c2a 100644
--- a/docs/html/resources/resources-data.js
+++ b/docs/html/resources/resources-data.js
@@ -782,6 +782,26 @@ var ANDROID_RESOURCES = [
}
},
{
+ tags: ['tutorial', 'gl', 'new'],
+ path: 'tutorials/opengl/opengl-es10.html',
+ title: {
+ en: 'OpenGL ES 1.0'
+ },
+ description: {
+ en: 'The basics of implementing an application using the OpenGL ES 1.0 APIs.'
+ }
+ },
+ {
+ tags: ['tutorial', 'gl', 'new'],
+ path: 'tutorials/opengl/opengl-es20.html',
+ title: {
+ en: 'OpenGL ES 2.0'
+ },
+ description: {
+ en: 'The basics of implementing an application using the OpenGL ES 2.0 APIs.'
+ }
+ },
+ {
tags: ['tutorial', 'testing'],
path: 'tutorials/testing/helloandroid_test.html',
title: {
diff --git a/docs/html/resources/tutorials/opengl/opengl-es10.jd b/docs/html/resources/tutorials/opengl/opengl-es10.jd
new file mode 100644
index 000000000000..40304fd41521
--- /dev/null
+++ b/docs/html/resources/tutorials/opengl/opengl-es10.jd
@@ -0,0 +1,532 @@
+page.title=OpenGL ES 1.0
+parent.title=Tutorials
+parent.link=../../browser.html?tag=tutorial
+@jd:body
+
+
+<div id="qv-wrapper">
+ <div id="qv">
+ <h2>In this document</h2>
+
+ <ol>
+ <li><a href="#creating">Create an Activity with GLSurfaceView</a></li>
+ <li>
+ <a href="#drawing">Draw a Shape on GLSurfaceView</a>
+ <ol>
+ <li><a href="#define-triangle">Define a Triangle</a></li>
+ <li><a href="#draw-triangle">Draw the Triangle</a></li>
+ </ol>
+ </li>
+ <li><a href="#projection-and-views">Apply Projection and Camera Views</a></li>
+ <li><a href="#motion">Add Motion</a></li>
+ <li><a href="#touch">Respond to Touch Events</a></li>
+ </ol>
+ <h2 id="code-samples-list">Related Samples</h2>
+ <ol>
+ <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/
+index.html">API Demos - graphics</a></li>
+ <li><a
+ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/
+GLSurfaceViewActivity.html">OpenGL ES 1.0 Sample</a></li>
+ <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/
+TouchRotateActivity.html">TouchRotateActivity</a></li>
+ </ol>
+ <h2>See also</h2>
+ <ol>
+ <li><a href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a></li>
+ <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es20.html">OpenGL
+ES 2.0</a></li>
+ </ol>
+ </div>
+ </div>
+
+<p>This tutorial shows you how to create a simple Android application that uses the OpenGL ES 1.0
+API to perform some basic graphics operations. You'll learn how to:</p>
+
+<ul>
+ <li>Create an activity using {@link android.opengl.GLSurfaceView} and {@link
+android.opengl.GLSurfaceView.Renderer}</li>
+ <li>Create and draw a graphic object</li>
+ <li>Define a projection to correct for screen geometry</li>
+ <li>Define a camera view</li>
+ <li>Rotate a graphic object</li>
+ <li>Make graphics touch-interactive</li>
+</ul>
+
+<p>The Android framework supports both the OpenGL ES 1.0/1.1 and OpenGL ES 2.0 APIs. You should
+carefully consider which version of the OpenGL ES API (1.0/1.1 or 2.0) is most appropriate for your
+needs. For more information, see
+<a href="{@docRoot}guide/topics/graphics/opengl.html#choosing-version">Choosing an OpenGL API
+Version</a>. If you would prefer to use OpenGL ES 2.0, see the <a
+href="{@docRoot}resources/tutorials/opengl/opengl-es20.jd">OpenGL ES 2.0 tutorial</a>.</p>
+
+<p>Before you start, you should understand how to create a basic Android application. If you do not
+know how to create an app, follow the <a href="{@docRoot}resources/tutorials/hello-world.html">Hello
+World Tutorial</a> to familiarize yourself with the process.</p>
+
+<h2 id="creating">Create an Activity with GLSurfaceView</h2>
+
+<p>To get started using OpenGL, you must implement both a {@link android.opengl.GLSurfaceView} and a
+{@link android.opengl.GLSurfaceView.Renderer}. The {@link android.opengl.GLSurfaceView} is the main
+view type for applications that use OpenGL and the {@link android.opengl.GLSurfaceView.Renderer}
+controls what is drawn within that view. (For more information about these classes, see the <a
+href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a> document.)</p>
+
+<p>To create an activity using {@code GLSurfaceView}:</p>
+
+<ol>
+ <li>Start a new Android project that targets Android 1.6 (API Level 4) or higher.
+ </li>
+ <li>Name the project <strong>HelloOpenGLES10</strong> and make sure it includes an activity called
+{@code HelloOpenGLES10}.
+ </li>
+ <li>Modify the {@code HelloOpenGLES10} class as follows:
+<pre>
+package com.example.android.apis.graphics;
+
+import android.app.Activity;
+import android.content.Context;
+import android.opengl.GLSurfaceView;
+import android.os.Bundle;
+
+public class HelloOpenGLES10 extends Activity {
+
+ private GLSurfaceView mGLView;
+
+ &#64;Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ // Create a GLSurfaceView instance and set it
+ // as the ContentView for this Activity.
+ mGLView = new HelloOpenGLES10SurfaceView(this);
+ setContentView(mGLView);
+ }
+
+ &#64;Override
+ protected void onPause() {
+ super.onPause();
+ // The following call pauses the rendering thread.
+ // If your OpenGL application is memory intensive,
+ // you should consider de-allocating objects that
+ // consume significant memory here.
+ mGLView.onPause();
+ }
+
+ &#64;Override
+ protected void onResume() {
+ super.onResume();
+ // The following call resumes a paused rendering thread.
+ // If you de-allocated graphic objects for onPause()
+ // this is a good place to re-allocate them.
+ mGLView.onResume();
+ }
+}
+
+class HelloOpenGLES10SurfaceView extends GLSurfaceView {
+
+ public HelloOpenGLES10SurfaceView(Context context){
+ super(context);
+
+ // Set the Renderer for drawing on the GLSurfaceView
+ setRenderer(new HelloOpenGLES10Renderer());
+ }
+}
+</pre>
+ <p class="note"><strong>Note:</strong> You will get a compile error for the {@code
+HelloOpenGLES10Renderer} class reference. That's expected; you will fix this error in the next step.
+ </p>
+
+ <p>As shown above, this activity uses a single {@link android.opengl.GLSurfaceView} for its
+view. Notice that this activity implements crucial lifecycle callbacks for pausing and resuming its
+work.</p>
+
+ <p>The {@code HelloOpenGLES10SurfaceView} class in this example code above is just a thin wrapper
+for an instance of {@link android.opengl.GLSurfaceView} and is not strictly necessary for this
+example. However, if you want your application to monitor and respond to touch screen
+events&#8212;and we are guessing you do&#8212;you must extend {@link android.opengl.GLSurfaceView}
+to add touch event listeners, which you will learn how to do in the <a href="#touch">Reponding to
+Touch Events</a> section.</p>
+
+ <p>In order to draw graphics in the {@link android.opengl.GLSurfaceView}, you must define an
+implementation of {@link android.opengl.GLSurfaceView.Renderer}. In the next step, you create
+a renderer class to complete this OpenGL application.</p>
+ </li>
+
+ <li>Create a new file for the following class {@code HelloOpenGLES10Renderer}, which implements
+the {@link android.opengl.GLSurfaceView.Renderer} interface:
+
+<pre>
+package com.example.android.apis.graphics;
+
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10;
+
+import android.opengl.GLSurfaceView;
+
+public class HelloOpenGLES10Renderer implements GLSurfaceView.Renderer {
+
+ public void onSurfaceCreated(GL10 gl, EGLConfig config) {
+ // Set the background frame color
+ gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
+ }
+
+ public void onDrawFrame(GL10 gl) {
+ // Redraw background color
+ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
+ }
+
+ public void onSurfaceChanged(GL10 gl, int width, int height) {
+ gl.glViewport(0, 0, width, height);
+ }
+
+}
+</pre>
+ <p>This minimal implementation of {@link android.opengl.GLSurfaceView.Renderer} provides the
+code structure needed to use OpenGL drawing methods:
+<ul>
+ <li>{@link
+ android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10,
+ javax.microedition.khronos.egl.EGLConfig) onSurfaceCreated()} is called once to set up the
+{@link android.opengl.GLSurfaceView}
+environment.</li>
+ <li>{@link
+ android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.khronos.opengles.GL10)
+ onDrawFrame()} is called for each redraw of the {@link
+android.opengl.GLSurfaceView}.</li>
+ <li>{@link
+ android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition.khronos.opengles.GL10,
+ int, int) onSurfaceChanged()} is called if the geometry of the {@link
+android.opengl.GLSurfaceView} changes, for example when the device's screen orientation
+changes.</li>
+</ul>
+ </p>
+ <p>For more information about these methods, see the <a
+href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a> document.
+</p>
+ </li>
+</ol>
+
+<p>The code example above creates a simple Android application that displays a grey screen using
+OpenGL ES 1.0 calls. While this application does not do anything very interesting, by creating these
+classes, you have layed the foundation needed to start drawing graphic elements with OpenGL ES
+1.0.</p>
+
+<p>If you are familiar with the OpenGL ES APIs, these classes should give you enough information
+to use the OpenGL ES 1.0 API and create graphics. However, if you need a bit more help getting
+started with OpenGL, head on to the next sections for a few more hints.</p>
+
+<h2 id="drawing">Draw a Shape on GLSurfaceView</h2>
+
+<p>Once you have implemented a {@link android.opengl.GLSurfaceView.Renderer}, the next step is to
+draw something with it. This section shows you how to define and draw a triangle.</p>
+
+<h3 id="define-triangle">Define a Triangle</h3>
+
+<p>OpenGL allows you to define objects using coordinates in three-dimensional space. So, before you
+ can draw a triangle, you must define its coordinates. In OpenGL, the typical way to do this is to
+ define a vertex array for the coordinates.</p>
+
+<p>By default, OpenGL ES assumes a coordinate system where [0,0,0] (X,Y,Z) specifies the center of
+ the {@link android.opengl.GLSurfaceView} frame, [1,1,0] is the top right corner of the frame and
+[-1,-1,0] is bottom left corner of the frame.</p>
+
+<p>To define a vertex array for a triangle:</p>
+
+<ol>
+ <li>In your {@code HelloOpenGLES10Renderer} class, add new member variable to contain the
+vertices of a triangle shape:
+<pre>
+ private FloatBuffer triangleVB;
+</pre>
+ </li>
+
+ <li>Create a method, {@code initShapes()} which populates this member variable:
+<pre>
+ private void initShapes(){
+
+ float triangleCoords[] = {
+ // X, Y, Z
+ -0.5f, -0.25f, 0,
+ 0.5f, -0.25f, 0,
+ 0.0f, 0.559016994f, 0
+ };
+
+ // initialize vertex Buffer for triangle
+ ByteBuffer vbb = ByteBuffer.allocateDirect(
+ // (# of coordinate values * 4 bytes per float)
+ triangleCoords.length * 4);
+ vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order
+ triangleVB = vbb.asFloatBuffer(); // create a floating point buffer from the ByteBuffer
+ triangleVB.put(triangleCoords); // add the coordinates to the FloatBuffer
+ triangleVB.position(0); // set the buffer to read the first coordinate
+
+ }
+</pre>
+ <p>This method defines a two-dimensional triangle with three equal sides.</p>
+ </li>
+ <li>Modify your {@code onSurfaceCreated()} method to initialize your triangle:
+ <pre>
+ public void onSurfaceCreated(GL10 gl, EGLConfig config) {
+
+ // Set the background frame color
+ gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
+
+ // initialize the triangle vertex array
+ initShapes();
+ }
+</pre>
+ <p class="caution"><strong>Caution:</strong> Shapes and other static objects should be initialized
+ once in your {@code onSurfaceCreated()} method for best performance. Avoid initializing the
+ new objects in {@code onDrawFrame()}, as this causes the system to re-create the objects
+ for every frame redraw and slows down your application.
+ </p>
+ </li>
+
+</ol>
+
+<p>You have now defined a triangle shape, but if you run the application, nothing appears. What?!
+You also have to tell OpenGL to draw the triangle, which you'll do in the next section.
+</p>
+
+
+<h3 id="draw-triangle">Draw the Triangle</h3>
+
+<p>Before you can draw your triangle, you must tell OpenGL that you are using vertex arrays. After
+that setup step, you can call the drawing APIs to display the triangle.</p>
+
+<p>To draw the triangle:</p>
+
+<ol>
+ <li>Add the {@code glEnableClientState()} method to the end of {@code onSurfaceCreated()} to
+enable vertex arrays.
+<pre>
+ // Enable use of vertex arrays
+ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
+</pre>
+ <p>At this point, you are ready to draw the triangle object in the OpenGL view.</p>
+ </li>
+
+ <li>Add the following code to the end of your {@code onDrawFrame()} method to draw the triangle.
+<pre>
+ // Draw the triangle
+ gl.glColor4f(0.63671875f, 0.76953125f, 0.22265625f, 0.0f);
+ gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triangleVB);
+ gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
+</pre>
+ </li>
+ <li id="squashed-triangle">Run the app! Your application should look something like this:
+ </li>
+</ol>
+
+<img src="{@docRoot}images/opengl/helloopengl-es10-1.png">
+<p class="img-caption">
+ <strong>Figure 1.</strong> Triangle drawn without a projection or camera view.
+</p>
+
+<p>There are a few problems with this example. First of all, it is not going to impress your
+friends. Secondly, the triangle is a bit squashed and changes shape when you change the screen
+orientation of the device. The reason the shape is skewed is due to the fact that the object is
+being rendered in a frame which is not perfectly square. You'll fix that problem using a projection
+and camera view in the next section.</p>
+
+<p>Lastly, because the triangle is stationary, the system is redrawing the object repeatedly in
+exactly the same place, which is not the most efficient use of the OpenGL graphics pipeline. In the
+<a href="#motion">Add Motion</a> section, you'll make this shape rotate and justify
+this use of processing power.</p>
+
+<h2 id="projection-and-views">Apply Projection and Camera View</h2>
+
+<p>One of the basic problems in displaying graphics is that Android device displays are typically
+not square and, by default, OpenGL happily maps a perfectly square, uniform coordinate
+system onto your typically non-square screen. To solve this problem, you can apply an OpenGL
+projection mode and camera view (eye point) to transform the coordinates of your graphic objects
+so they have the correct proportions on any display. For more information about OpenGL coordinate
+mapping, see <a href="{@docRoot}guide/topics/graphics/opengl.html#coordinate-mapping">Coordinate
+Mapping for Drawn Objects</a>.</p>
+
+<p>To apply projection and camera view transformations to your triangle:
+</p>
+<ol>
+ <li>Modify your {@code onSurfaceChanged()} method to enable {@link
+ javax.microedition.khronos.opengles.GL10#GL_PROJECTION GL10.GL_PROJECTION} mode, calculate the
+ screen ratio and apply the ratio as a transformation of the object coordinates.
+<pre>
+ public void onSurfaceChanged(GL10 gl, int width, int height) {
+ gl.glViewport(0, 0, width, height);
+
+ // make adjustments for screen ratio
+ float ratio = (float) width / height;
+ gl.glMatrixMode(GL10.GL_PROJECTION); // set matrix to projection mode
+ gl.glLoadIdentity(); // reset the matrix to its default state
+ gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); // apply the projection matrix
+ }
+</pre>
+ </li>
+
+ <li>Next, modify your {@code onDrawFrame()} method to apply the {@link
+javax.microedition.khronos.opengles.GL10#GL_MODELVIEW GL_MODELVIEW} mode and set
+a view point using {@link android.opengl.GLU#gluLookAt(javax.microedition.khronos.opengles.GL10,
+float, float, float, float, float, float, float, float, float) GLU.gluLookAt()}.
+<pre>
+ public void onDrawFrame(GL10 gl) {
+ // Redraw background color
+ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
+
+ // Set GL_MODELVIEW transformation mode
+ gl.glMatrixMode(GL10.GL_MODELVIEW);
+ gl.glLoadIdentity(); // reset the matrix to its default state
+
+ // When using GL_MODELVIEW, you must set the view point
+ GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
+
+ // Draw the triangle
+ ...
+ }
+</pre>
+ </li>
+ <li>Run the updated application and you should see something like this:</li>
+</ol>
+
+<img src="{@docRoot}images/opengl/helloopengl-es10-2.png">
+<p class="img-caption">
+ <strong>Figure 2.</strong> Triangle drawn with a projection and camera view applied.
+</p>
+
+<p>Now that you have applied this transformation, the triangle has three equal sides, instead of the
+<a href="#squashed-triangle">squashed triangle</a> in the earlier version.</p>
+
+<h2 id="motion">Add Motion</h2>
+
+<p>While it may be an interesting exercise to create static graphic objects with OpenGL ES, chances
+are you want at least <em>some</em> of your objects to move. In this section, you'll add motion to
+your triangle by rotating it.</p>
+
+<p>To add rotation to your triangle:</p>
+<ol>
+ <li>Modify your {@code onDrawFrame()} method to rotate the triangle object:
+<pre>
+ public void onDrawFrame(GL10 gl) {
+ ...
+ // When using GL_MODELVIEW, you must set the view point
+ GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
+
+ // Create a rotation for the triangle
+ long time = SystemClock.uptimeMillis() % 4000L;
+ float angle = 0.090f * ((int) time);
+ gl.glRotatef(angle, 0.0f, 0.0f, 1.0f);
+
+ // Draw the triangle
+ ...
+ }
+</pre>
+ </li>
+ <li>Run the application and your triangle should rotate around its center.</li>
+</ol>
+
+
+<h2 id="touch">Respond to Touch Events</h2>
+<p>Making objects move according to a preset program like the rotating triangle is useful for
+getting some attention, but what if you want to have users interact with your OpenGL graphics? In
+this section, you'll learn how listen for touch events to let users interact with objects in your
+{@code HelloOpenGLES10SurfaceView}.</p>
+
+<p>The key to making your OpenGL application touch interactive is expanding your implementation of
+{@link android.opengl.GLSurfaceView} to override the {@link
+android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} to listen for touch events.
+Before you do that, however, you'll modify the renderer class to expose the rotation angle of the
+triangle. Afterwards, you'll modify the {@code HelloOpenGLES10SurfaceView} to process touch events
+and pass that data to your renderer.</p>
+
+<p>To make your triangle rotate in response to touch events:</p>
+
+<ol>
+ <li>Modify your {@code HelloOpenGLES10Renderer} class to include a new, public member so that
+your {@code HelloOpenGLES10SurfaceView} class is able to pass new rotation values your renderer:
+<pre>
+ public float mAngle;
+</pre>
+ </li>
+ <li>In your {@code onDrawFrame()} method, comment out the code that generates an angle and
+replace the {@code angle} variable with {@code mAngle}.
+<pre>
+ // Create a rotation for the triangle (Boring! Comment this out:)
+ // long time = SystemClock.uptimeMillis() % 4000L;
+ // float angle = 0.090f * ((int) time);
+
+ // Use the mAngle member as the rotation value
+ gl.glRotatef(mAngle, 0.0f, 0.0f, 1.0f);
+</pre>
+ </li>
+ <li>In your {@code HelloOpenGLES10SurfaceView} class, add the following member variables.
+<pre>
+ private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
+ private HelloOpenGLES10Renderer mRenderer;
+ private float mPreviousX;
+ private float mPreviousY;
+</pre>
+ </li>
+ <li>In the constructor method for {@code HelloOpenGLES10SurfaceView}, set the {@code mRenderer}
+member so you have a handle to pass in rotation input and set the render mode to {@link
+android.opengl.GLSurfaceView#RENDERMODE_WHEN_DIRTY}.
+<pre>
+ public HelloOpenGLES10SurfaceView(Context context){
+ super(context);
+ // set the mRenderer member
+ mRenderer = new HelloOpenGLES10Renderer();
+ setRenderer(mRenderer);
+
+ // Render the view only when there is a change
+ setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
+ }
+</pre>
+ </li>
+ <li>In your {@code HelloOpenGLES10SurfaceView} class, override the {@link
+android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} method to listen for touch
+events and pass them to your renderer.
+<pre>
+ &#64;Override
+ public boolean onTouchEvent(MotionEvent e) {
+ // MotionEvent reports input details from the touch screen
+ // and other input controls. In this case, you are only
+ // interested in events where the touch position changed.
+
+ float x = e.getX();
+ float y = e.getY();
+
+ switch (e.getAction()) {
+ case MotionEvent.ACTION_MOVE:
+
+ float dx = x - mPreviousX;
+ float dy = y - mPreviousY;
+
+ // reverse direction of rotation above the mid-line
+ if (y &gt; getHeight() / 2) {
+ dx = dx * -1 ;
+ }
+
+ // reverse direction of rotation to left of the mid-line
+ if (x &lt; getWidth() / 2) {
+ dy = dy * -1 ;
+ }
+
+ mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR;
+ requestRender();
+ }
+
+ mPreviousX = x;
+ mPreviousY = y;
+ return true;
+ }
+</pre>
+ <p class="note"><strong>Note:</strong> Touch events return pixel coordinates which <em>are not the
+same</em> as OpenGL coordinates. Touch coordinate [0,0] is the bottom-left of the screen and the
+highest value [max_X, max_Y] is the top-right corner of the screen. To match touch events to OpenGL
+graphic objects, you must translate touch coordinates into OpenGL coordinates.</p>
+ </li>
+ <li>Run the application and drag your finger or cursor around the screen to rotate the
+triangle.</li>
+</ol>
+<p>For another example of OpenGL touch event functionality, see <a
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/
+TouchRotateActivity.html">TouchRotateActivity</a>.</p> \ No newline at end of file
diff --git a/docs/html/resources/tutorials/opengl/opengl-es20.jd b/docs/html/resources/tutorials/opengl/opengl-es20.jd
new file mode 100644
index 000000000000..439f7d5b8631
--- /dev/null
+++ b/docs/html/resources/tutorials/opengl/opengl-es20.jd
@@ -0,0 +1,652 @@
+page.title=OpenGL ES 2.0
+parent.title=Tutorials
+parent.link=../../browser.html?tag=tutorial
+@jd:body
+
+
+<div id="qv-wrapper">
+ <div id="qv">
+ <h2>In this document</h2>
+
+ <ol>
+ <li><a href="#creating">Create an Activity with GLSurfaceView</a></li>
+ <li>
+ <a href="#drawing">Draw a Shape on GLSurfaceView</a>
+ <ol>
+ <li><a href="#define-triangle">Define a Triangle</a></li>
+ <li><a href="#draw-triangle">Draw the Triangle</a></li>
+ </ol>
+ </li>
+ <li><a href="#projection-and-views">Apply Projection and Camera Views</a></li>
+ <li><a href="#motion">Add Motion</a></li>
+ <li><a href="#touch">Respond to Touch Events</a></li>
+ </ol>
+ <h2 id="code-samples-list">Related Samples</h2>
+ <ol>
+ <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/
+index.html">API Demos - graphics</a></li>
+ <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/
+GLES20Activity.html">OpenGL ES 2.0 Sample</a></li>
+ <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/
+TouchRotateActivity.html">TouchRotateActivity</a></li>
+ </ol>
+ <h2>See also</h2>
+ <ol>
+ <li><a href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a></li>
+ <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es10.html">OpenGL
+ES 1.0</a></li>
+ </ol>
+ </div>
+ </div>
+
+<p>This tutorial shows you how to create a simple Android application that uses the OpenGL ES 2.0
+API to perform some basic graphics operations. You'll learn how to:</p>
+
+<ul>
+ <li>Create an activity using {@link android.opengl.GLSurfaceView} and {@link
+android.opengl.GLSurfaceView.Renderer}</li>
+ <li>Create and draw a graphic object</li>
+ <li>Define a projection to correct for screen geometry</li>
+ <li>Define a camera view</li>
+ <li>Rotate a graphic object</li>
+ <li>Make graphics touch interactive</li>
+</ul>
+
+<p>The Android framework supports both the OpenGL ES 1.0/1.1 and OpenGL ES 2.0 APIs. You should
+carefully consider which version of the OpenGL ES API (1.0/1.1 or 2.0) is most appropriate for your
+needs. For more information, see
+<a href="{@docRoot}guide/topics/graphics/opengl.html#choosing-version">Choosing an OpenGL API
+Version</a>. If you would prefer to use OpenGL ES 1.0, see the <a
+href="{@docRoot}resources/tutorials/opengl/opengl-es10.jd">OpenGL ES 1.0 tutorial</a>.</p>
+
+<p>Before you start, you should understand how to create a basic Android application. If you do not
+know how to create an app, follow the <a href="{@docRoot}resources/tutorials/hello-world.html">Hello
+World Tutorial</a> to familiarize yourself with the process.</p>
+
+<p class="caution"><strong>Caution:</strong> OpenGL ES 2.0 <em>is currently not supported</em> by
+the Android Emulator. You must have a physical test device running Android 2.2 (API Level 8) or
+higher in order to run and test the example code in this tutorial.</p>
+
+<h2 id="creating">Create an Activity with GLSurfaceView</h2>
+
+<p>To get started using OpenGL, you must implement both a {@link android.opengl.GLSurfaceView} and a
+{@link android.opengl.GLSurfaceView.Renderer}. The {@link android.opengl.GLSurfaceView} is the main
+view type for applications that use OpenGL and the {@link android.opengl.GLSurfaceView.Renderer}
+controls what is drawn within that view. (For more information about these classes, see the <a
+href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a> document.)</p>
+
+<p>To create an activity using {@code GLSurfaceView}:</p>
+
+<ol>
+ <li>Start a new Android project that targets Android 2.2 (API Level 8) or higher.
+ </li>
+ <li>Name the project <strong>HelloOpenGLES20</strong> and make sure it includes an activity called
+{@code HelloOpenGLES20}.
+ </li>
+ <li>Modify the {@code HelloOpenGLES20} class as follows:
+<pre>
+package com.example.android.apis.graphics;
+
+import android.app.Activity;
+import android.content.Context;
+import android.opengl.GLSurfaceView;
+import android.os.Bundle;
+
+public class HelloOpenGLES20 extends Activity {
+
+ private GLSurfaceView mGLView;
+
+ &#64;Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ // Create a GLSurfaceView instance and set it
+ // as the ContentView for this Activity
+ mGLView = new HelloOpenGLES20SurfaceView(this);
+ setContentView(mGLView);
+ }
+
+ &#64;Override
+ protected void onPause() {
+ super.onPause();
+ // The following call pauses the rendering thread.
+ // If your OpenGL application is memory intensive,
+ // you should consider de-allocating objects that
+ // consume significant memory here.
+ mGLView.onPause();
+ }
+
+ &#64;Override
+ protected void onResume() {
+ super.onResume();
+ // The following call resumes a paused rendering thread.
+ // If you de-allocated graphic objects for onPause()
+ // this is a good place to re-allocate them.
+ mGLView.onResume();
+ }
+}
+
+class HelloOpenGLES20SurfaceView extends GLSurfaceView {
+
+ public HelloOpenGLES20SurfaceView(Context context){
+ super(context);
+
+ // Create an OpenGL ES 2.0 context.
+ setEGLContextClientVersion(2);
+ // Set the Renderer for drawing on the GLSurfaceView
+ setRenderer(new HelloOpenGLES20Renderer());
+ }
+}
+</pre>
+ <p class="note"><strong>Note:</strong> You will get a compile error for the {@code
+HelloOpenGLES20Renderer} class reference. That's expected; you will fix this error in the next step.
+ </p>
+
+ <p>As shown above, this activity uses a single {@link android.opengl.GLSurfaceView} for its
+view. Notice that this activity implements crucial lifecycle callbacks for pausing and resuming its
+work.</p>
+
+ <p>The {@code HelloOpenGLES20SurfaceView} class in this example code above is just a thin wrapper
+for an instance of {@link android.opengl.GLSurfaceView} and is not strictly necessary for this
+example. However, if you want your application to monitor and respond to touch screen
+events&#8212;and we are guessing you do&#8212;you must extend {@link android.opengl.GLSurfaceView}
+to add touch event listeners, which you will learn how to do in the <a href="#touch">Reponding to
+Touch Events</a> section.</p>
+
+ <p>In order to draw graphics in the {@link android.opengl.GLSurfaceView}, you must define an
+implementation of {@link android.opengl.GLSurfaceView.Renderer}. In the next step, you create
+a renderer class to complete this OpenGL application.</p>
+ </li>
+
+ <li>Create a new file for the following class {@code HelloOpenGLES20Renderer}, which implements
+the {@link android.opengl.GLSurfaceView.Renderer} interface:
+
+<pre>
+package com.example.android.apis.graphics;
+
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10;
+
+import android.opengl.GLES20;
+import android.opengl.GLSurfaceView;
+
+public class HelloOpenGLES20Renderer implements GLSurfaceView.Renderer {
+
+ public void onSurfaceCreated(GL10 unused, EGLConfig config) {
+
+ // Set the background frame color
+ GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
+ }
+
+ public void onDrawFrame(GL10 unused) {
+
+ // Redraw background color
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
+ }
+
+ public void onSurfaceChanged(GL10 unused, int width, int height) {
+ GLES20.glViewport(0, 0, width, height);
+ }
+
+}
+</pre>
+ <p>This minimal implementation of {@link android.opengl.GLSurfaceView.Renderer} provides the
+code structure needed to use OpenGL drawing methods:
+<ul>
+ <li>{@link
+ android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10,
+ javax.microedition.khronos.egl.EGLConfig) onSurfaceCreated()} is called once to set up the
+{@link android.opengl.GLSurfaceView}
+environment.</li>
+ <li>{@link
+ android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.khronos.opengles.GL10)
+ onDrawFrame()} is called for each redraw of the {@link
+android.opengl.GLSurfaceView}.</li>
+ <li>{@link
+ android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition.khronos.opengles.GL10,
+ int, int) onSurfaceChanged()} is called if the geometry of the {@link
+android.opengl.GLSurfaceView} changes, for example when the device's screen orientation
+changes.</li>
+</ul>
+ </p>
+ <p>For more information about these methods, see the <a
+href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a> document.
+</p>
+ </li>
+</ol>
+
+<p>The code example above creates a simple Android application that displays a grey screen using
+OpenGL ES 2.0 calls. While this application does not do anything very interesting, by creating these
+classes, you have layed the foundation needed to start drawing graphic elements with OpenGL ES
+2.0.</p>
+
+<p>If you are familiar with the OpenGL ES APIs, these classes should give you enough information
+to use the OpenGL ES 2.0 API and create graphics. However, if you need a bit more help getting
+started with OpenGL, head on to the next sections for a few more hints.</p>
+
+<p class="note"><strong>Note:</strong> If your application requires OpenGL 2.0, make sure you
+declare this in your manifest:</p>
+<pre>
+ &lt;!-- Tell the system this app requires OpenGL ES 2.0. --&gt;
+ &lt;uses-feature android:glEsVersion="0x00020000" android:required="true" /&gt;
+</pre>
+<p>For more information, see <a
+href="{@docRoot}guide/topics/graphics/opengl.html#manifest">OpenGL manifest declarations</a> in the
+<em>3D with OpenGL</em> document.</p>
+
+
+<h2 id="drawing">Draw a Shape on GLSurfaceView</h2>
+
+<p>Once you have implemented a {@link android.opengl.GLSurfaceView.Renderer}, the next step is to
+draw something with it. This section shows you how to define and draw a triangle.</p>
+
+<h3 id="define-triangle">Define a Triangle</h3>
+
+<p>OpenGL allows you to define objects using coordinates in three-dimensional space. So, before you
+ can draw a triangle, you must define its coordinates. In OpenGL, the typical way to do this is to
+ define a vertex array for the coordinates.</p>
+
+<p>By default, OpenGL ES assumes a coordinate system where [0,0,0] (X,Y,Z) specifies the center of
+ the {@link android.opengl.GLSurfaceView} frame, [1,1,0] is the top-right corner of the frame and
+[-1,-1,0] is bottom-left corner of the frame.</p>
+
+<p>To define a vertex array for a triangle:</p>
+
+<ol>
+ <li>In your {@code HelloOpenGLES20Renderer} class, add new member variable to contain the
+vertices of a triangle shape:
+<pre>
+ private FloatBuffer triangleVB;
+</pre>
+ </li>
+
+ <li>Create a method, {@code initShapes()} which populates this member variable:
+<pre>
+ private void initShapes(){
+
+ float triangleCoords[] = {
+ // X, Y, Z
+ -0.5f, -0.25f, 0,
+ 0.5f, -0.25f, 0,
+ 0.0f, 0.559016994f, 0
+ };
+
+ // initialize vertex Buffer for triangle
+ ByteBuffer vbb = ByteBuffer.allocateDirect(
+ // (# of coordinate values * 4 bytes per float)
+ triangleCoords.length * 4);
+ vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order
+ triangleVB = vbb.asFloatBuffer(); // create a floating point buffer from the ByteBuffer
+ triangleVB.put(triangleCoords); // add the coordinates to the FloatBuffer
+ triangleVB.position(0); // set the buffer to read the first coordinate
+
+ }
+</pre>
+ <p>This method defines a two-dimensional triangle shape with three equal sides.</p>
+ </li>
+ <li>Modify your {@code onSurfaceCreated()} method to initialize your triangle:
+<pre>
+ public void onSurfaceCreated(GL10 unused, EGLConfig config) {
+
+ // Set the background frame color
+ GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
+
+ // initialize the triangle vertex array
+ initShapes();
+ }
+</pre>
+ <p class="caution"><strong>Caution:</strong> Shapes and other static objects should be initialized
+ once in your {@code onSurfaceCreated()} method for best performance. Avoid initializing the
+ new objects in {@code onDrawFrame()}, as this causes the system to re-create the objects
+ for every frame redraw and slows down your application.
+ </p>
+ </li>
+
+</ol>
+
+<p>You have now defined a triangle shape, but if you run the application, nothing appears. What?!
+You also have to tell OpenGL to draw the triangle, which you'll do in the next section.
+</p>
+
+
+<h3 id="draw-triangle">Draw the Triangle</h3>
+
+<p>The OpenGL ES 2.0 requires a bit more code than OpenGL ES 1.0/1.1 in order to draw objects. In
+this section, you'll create vertex and fragment shaders, a shader loader, apply the shaders, enable
+the use of vertex arrays for your triangle and, finally, draw it on screen.</p>
+
+<p>To draw the triangle:</p>
+
+<ol>
+ <li>In your {@code HelloOpenGLES20Renderer} class, define a vertex shader and a fragment
+shader. Shader code is defined as a string which is compiled and run by the OpenGL ES 2.0 rendering
+engine.
+<pre>
+ private final String vertexShaderCode =
+ "attribute vec4 vPosition; \n" +
+ "void main(){ \n" +
+ " gl_Position = vPosition; \n" +
+ "} \n";
+
+ private final String fragmentShaderCode =
+ "precision mediump float; \n" +
+ "void main(){ \n" +
+ " gl_FragColor = vec4 (0.63671875, 0.76953125, 0.22265625, 1.0); \n" +
+ "} \n";
+</pre>
+ <p>The vertex shader controls how OpenGL positions and draws the vertices of shapes in space.
+The fragment shader controls what OpenGL draws <em>between</em> the vertices of shapes.</p>
+ </li>
+ <li>In your {@code HelloOpenGLES20Renderer} class, create a method for loading the shaders.
+<pre>
+ private int loadShader(int type, String shaderCode){
+
+ // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
+ // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
+ int shader = GLES20.glCreateShader(type);
+
+ // add the source code to the shader and compile it
+ GLES20.glShaderSource(shader, shaderCode);
+ GLES20.glCompileShader(shader);
+
+ return shader;
+ }
+</pre>
+ </li>
+
+ <li>Add the following members to your {@code HelloOpenGLES20Renderer} class for an OpenGL
+Program and the positioning control for your triangle.
+<pre>
+ private int mProgram;
+ private int maPositionHandle;
+</pre>
+ <p>In OpenGL ES 2.0, you attach vertex and fragment shaders to a <em>Program</em> and then
+apply the program to the OpenGL graphics pipeline.</p>
+ </li>
+
+ <li>Add the following code to the end of your {@code onSurfaceCreated()} method to load the
+shaders and attach them to an OpenGL Program.
+<pre>
+ int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
+ int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
+
+ mProgram = GLES20.glCreateProgram(); // create empty OpenGL Program
+ GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader to program
+ GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
+ GLES20.glLinkProgram(mProgram); // creates OpenGL program executables
+
+ // get handle to the vertex shader's vPosition member
+ maPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
+</pre>
+ <p>At this point, you are ready to draw the triangle object in the OpenGL view.</p>
+ </li>
+
+ <li>Add the following code to the end of your {@code onDrawFrame()} method apply the OpenGL
+program you created, load the triangle object and draw the triangle.
+<pre>
+ // Add program to OpenGL environment
+ GLES20.glUseProgram(mProgram);
+
+ // Prepare the triangle data
+ GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, 12, triangleVB);
+ GLES20.glEnableVertexAttribArray(maPositionHandle);
+
+ // Draw the triangle
+ GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);
+</pre>
+ </li>
+ <li id="squashed-triangle">Run the app! Your application should look something like this:
+ </li>
+</ol>
+
+<img src="{@docRoot}images/opengl/helloopengl-es20-1.png">
+<p class="img-caption">
+ <strong>Figure 1.</strong> Triangle drawn without a projection or camera view.
+</p>
+
+<p>There are a few problems with this example. First of all, it is not going to impress your
+friends. Secondly, the triangle is a bit squashed and changes shape when you change the screen
+orientation of the device. The reason the shape is skewed is due to the fact that the object is
+being rendered in a frame which is not perfectly square. You'll fix that problem using a projection
+and camera view in the next section.</p>
+
+<p>Lastly, because the triangle is stationary, the system is redrawing the object repeatedly in
+exactly the same place, which is not the most efficient use of the OpenGL graphics pipeline. In the
+<a href="#motion">Add Motion</a> section, you'll make this shape rotate and justify
+this use of processing power.</p>
+
+<h2 id="projection-and-views">Apply Projection and Camera View</h2>
+
+<p>One of the basic problems in displaying graphics is that Android device displays are typically
+not square and, by default, OpenGL happily maps a perfectly square, uniform coordinate
+system onto your typically non-square screen. To solve this problem, you can apply an OpenGL
+projection mode and camera view (eye point) to transform the coordinates of your graphic objects
+so they have the correct proportions on any display. For more information about OpenGL coordinate
+mapping, see <a href="{@docRoot}guide/topics/graphics/opengl.html#coordinate-mapping">Coordinate
+Mapping for Drawn Objects</a>.</p>
+
+<p>To apply projection and camera view transformations to your triangle:
+</p>
+<ol>
+ <li>Add the following members to your {@code HelloOpenGLES20Renderer} class.
+<pre>
+ private int muMVPMatrixHandle;
+ private float[] mMVPMatrix = new float[16];
+ private float[] mMMatrix = new float[16];
+ private float[] mVMatrix = new float[16];
+ private float[] mProjMatrix = new float[16];
+</pre>
+ </li>
+ <li>Modify your {@code vertexShaderCode} string to add a variable for a model view
+projection matrix.
+<pre>
+ private final String vertexShaderCode =
+ // This matrix member variable provides a hook to manipulate
+ // the coordinates of the objects that use this vertex shader
+ "uniform mat4 uMVPMatrix; \n" +
+
+ "attribute vec4 vPosition; \n" +
+ "void main(){ \n" +
+
+ // the matrix must be included as a modifier of gl_Position
+ " gl_Position = uMVPMatrix * vPosition; \n" +
+
+ "} \n";
+</pre>
+ </li>
+ <li>Modify the {@code onSurfaceChanged()} method to calculate the device screen ratio and
+create a projection matrix.
+<pre>
+ public void onSurfaceChanged(GL10 unused, int width, int height) {
+ GLES20.glViewport(0, 0, width, height);
+
+ float ratio = (float) width / height;
+
+ // this projection matrix is applied to object coodinates
+ // in the onDrawFrame() method
+ Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
+ }
+</pre>
+ </li>
+ <li>Add the following code to the end of your {@code onSurfaceChanged()} method to
+reference the {@code uMVPMatrix} shader matrix variable you added in step 2.
+<pre>
+ muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
+</pre>
+ </li>
+ <li>Add the following code to the end of your {@code onSurfaceChanged()} method to define
+a camera view matrix.
+<pre>
+ Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
+</pre>
+ </li>
+ <li>Finally, modify your {@code onDrawFrame()} method to combine the projection and
+camera view matrices and then apply the combined transformation to the OpenGL rendering pipeline.
+<pre>
+ public void onDrawFrame(GL10 unused) {
+ ...
+ // Apply a ModelView Projection transformation
+ Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);
+ GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
+
+ // Draw the triangle
+ ...
+ }
+</pre>
+ </li>
+ <li>Run the updated application and you should see something like this:</li>
+</ol>
+
+<img src="{@docRoot}images/opengl/helloopengl-es20-2.png">
+<p class="img-caption">
+ <strong>Figure 2.</strong> Triangle drawn with a projection and camera view applied.
+</p>
+
+<p>Now that you have applied this transformation, the triangle has three equal sides, instead of the
+<a href="#squashed-triangle">squashed triangle</a> in the earlier version.</p>
+
+<h2 id="motion">Add Motion</h2>
+
+<p>While it may be an interesting exercise to create static graphic objects with OpenGL ES, chances
+are you want at least <em>some</em> of your objects to move. In this section, you'll add motion to
+your triangle by rotating it.</p>
+
+<p>To add rotation to your triangle:</p>
+<ol>
+ <li>Add an additional tranformation matrix member to your {@code HelloOpenGLES20Renderer}
+class.
+ <pre>
+ private float[] mMMatrix = new float[16];
+ </pre>
+ </li>
+ <li>Modify your {@code onDrawFrame()} method to rotate the triangle object.
+<pre>
+ public void onDrawFrame(GL10 gl) {
+ ...
+
+ // Create a rotation for the triangle
+ long time = SystemClock.uptimeMillis() % 4000L;
+ float angle = 0.090f * ((int) time);
+ Matrix.setRotateM(mMMatrix, 0, angle, 0, 0, 1.0f);
+ Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, mMMatrix, 0);
+ Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);
+
+ // Apply a ModelView Projection transformation
+ GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
+
+ // Draw the triangle
+ ...
+ }
+</pre>
+ </li>
+ <li>Run the application and your triangle should rotate around its center.</li>
+</ol>
+
+
+<h2 id="touch">Respond to Touch Events</h2>
+<p>Making objects move according to a preset program like the rotating triangle is useful for
+getting some attention, but what if you want to have users interact with your OpenGL graphics? In
+this section, you'll learn how listen for touch events to let users interact with objects in your
+{@code HelloOpenGLES20SurfaceView}.</p>
+
+<p>The key to making your OpenGL application touch interactive is expanding your implementation of
+{@link android.opengl.GLSurfaceView} to override the {@link
+android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} to listen for touch events.
+Before you do that, however, you'll modify the renderer class to expose the rotation angle of the
+triangle. Afterwards, you'll modify the {@code HelloOpenGLES20SurfaceView} to process touch events
+and pass that data to your renderer.</p>
+
+<p>To make your triangle rotate in response to touch events:</p>
+
+<ol>
+ <li>Modify your {@code HelloOpenGLES20Renderer} class to include a new, public member so that
+your {@code HelloOpenGLES10SurfaceView} class is able to pass new rotation values your renderer:
+<pre>
+ public float mAngle;
+</pre>
+ </li>
+ <li>In your {@code onDrawFrame()} method, comment out the code that generates an angle and
+replace the {@code angle} variable with {@code mAngle}.
+<pre>
+ // Create a rotation for the triangle (Boring! Comment this out:)
+ // long time = SystemClock.uptimeMillis() % 4000L;
+ // float angle = 0.090f * ((int) time);
+
+ // Use the mAngle member as the rotation value
+ Matrix.setRotateM(mMMatrix, 0, mAngle, 0, 0, 1.0f);
+</pre>
+ </li>
+ <li>In your {@code HelloOpenGLES20SurfaceView} class, add the following member variables.
+<pre>
+ private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
+ private HelloOpenGLES20Renderer mRenderer;
+ private float mPreviousX;
+ private float mPreviousY;
+</pre>
+ </li>
+ <li>In the constructor method for {@code HelloOpenGLES20SurfaceView}, set the {@code mRenderer}
+member so you have a handle to pass in rotation input and set the render mode to {@link
+android.opengl.GLSurfaceView#RENDERMODE_WHEN_DIRTY}.<pre>
+ public HelloOpenGLES20SurfaceView(Context context){
+ super(context);
+ // Create an OpenGL ES 2.0 context.
+ setEGLContextClientVersion(2);
+
+ // set the mRenderer member
+ mRenderer = new HelloOpenGLES20Renderer();
+ setRenderer(mRenderer);
+
+ // Render the view only when there is a change
+ setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
+ }
+</pre>
+ </li>
+ <li>In your {@code HelloOpenGLES20SurfaceView} class, override the {@link
+android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} method to listen for touch
+events and pass them to your renderer.
+<pre>
+ &#64;Override
+ public boolean onTouchEvent(MotionEvent e) {
+ // MotionEvent reports input details from the touch screen
+ // and other input controls. In this case, you are only
+ // interested in events where the touch position changed.
+
+ float x = e.getX();
+ float y = e.getY();
+
+ switch (e.getAction()) {
+ case MotionEvent.ACTION_MOVE:
+
+ float dx = x - mPreviousX;
+ float dy = y - mPreviousY;
+
+ // reverse direction of rotation above the mid-line
+ if (y &gt; getHeight() / 2) {
+ dx = dx * -1 ;
+ }
+
+ // reverse direction of rotation to left of the mid-line
+ if (x &lt; getWidth() / 2) {
+ dy = dy * -1 ;
+ }
+
+ mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR;
+ requestRender();
+ }
+
+ mPreviousX = x;
+ mPreviousY = y;
+ return true;
+ }
+</pre>
+ <p class="note"><strong>Note:</strong> Touch events return pixel coordinates which <em>are not the
+same</em> as OpenGL coordinates. Touch coordinate [0,0] is the bottom-left of the screen and the
+highest value [max_X, max_Y] is the top-right corner of the screen. To match touch events to OpenGL
+graphic objects, you must translate touch coordinates into OpenGL coordinates.</p>
+ </li>
+ <li>Run the application and drag your finger or cursor around the screen to rotate the
+triangle.</li>
+</ol>
+<p>For another example of OpenGL touch event functionality, see <a
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/
+TouchRotateActivity.html">TouchRotateActivity</a>.</p> \ No newline at end of file
diff --git a/docs/html/sdk/ndk/overview.jd b/docs/html/sdk/ndk/overview.jd
index 93c664dac5a4..85599f76600d 100644
--- a/docs/html/sdk/ndk/overview.jd
+++ b/docs/html/sdk/ndk/overview.jd
@@ -457,7 +457,8 @@ adb install bin/NativeActivity-debug.apk
<li>Mac OS X 10.4.8 or later (x86 only)</li>
- <li>Linux (32- or 64-bit, tested on Linux Ubuntu Dapper Drake)</li>
+ <li>Linux (32 or 64-bit; Ubuntu 8.04, or other Linux distributions using GLibc 2.7 or
+later)</li>
</ul>
<h4>Required development tools</h4>
diff --git a/include/media/stagefright/ACodec.h b/include/media/stagefright/ACodec.h
index f13e9bb5ac47..e965f1402445 100644
--- a/include/media/stagefright/ACodec.h
+++ b/include/media/stagefright/ACodec.h
@@ -36,6 +36,7 @@ struct ACodec : public AHierarchicalStateMachine {
kWhatShutdownCompleted = 'scom',
kWhatFlushCompleted = 'fcom',
kWhatOutputFormatChanged = 'outC',
+ kWhatError = 'erro',
};
ACodec();
@@ -58,7 +59,6 @@ private:
struct OutputPortSettingsChangedState;
struct ExecutingToIdleState;
struct IdleToLoadedState;
- struct ErrorState;
struct FlushingState;
enum {
@@ -102,7 +102,6 @@ private:
sp<OutputPortSettingsChangedState> mOutputPortSettingsChangedState;
sp<ExecutingToIdleState> mExecutingToIdleState;
sp<IdleToLoadedState> mIdleToLoadedState;
- sp<ErrorState> mErrorState;
sp<FlushingState> mFlushingState;
AString mComponentName;
diff --git a/libs/hwui/Layer.h b/libs/hwui/Layer.h
index dd75497c19a9..a8ae5c6eebd9 100644
--- a/libs/hwui/Layer.h
+++ b/libs/hwui/Layer.h
@@ -203,6 +203,10 @@ struct Layer {
return texTransform;
}
+ inline mat4& getTransform() {
+ return transform;
+ }
+
/**
* Bounds of the layer.
*/
@@ -282,6 +286,11 @@ private:
*/
mat4 texTransform;
+ /**
+ * Optional transform.
+ */
+ mat4 transform;
+
}; // struct Layer
}; // namespace uirenderer
diff --git a/libs/hwui/Matrix.cpp b/libs/hwui/Matrix.cpp
index 9fc5131ee931..769c99cf293a 100644
--- a/libs/hwui/Matrix.cpp
+++ b/libs/hwui/Matrix.cpp
@@ -51,6 +51,7 @@ void Matrix4::loadIdentity() {
data[kTranslateZ] = 0.0f;
data[kPerspective2] = 1.0f;
+ mIsIdentity = true;
mSimpleMatrix = true;
}
@@ -71,14 +72,21 @@ bool Matrix4::isSimple() {
return mSimpleMatrix;
}
+bool Matrix4::isIdentity() {
+ return mIsIdentity;
+}
+
void Matrix4::load(const float* v) {
memcpy(data, v, sizeof(data));
+ // TODO: Do something smarter here
mSimpleMatrix = false;
+ mIsIdentity = false;
}
void Matrix4::load(const Matrix4& v) {
memcpy(data, v.data, sizeof(data));
mSimpleMatrix = v.mSimpleMatrix;
+ mIsIdentity = v.mIsIdentity;
}
void Matrix4::load(const SkMatrix& v) {
@@ -99,6 +107,7 @@ void Matrix4::load(const SkMatrix& v) {
data[kScaleZ] = 1.0f;
mSimpleMatrix = (v.getType() <= (SkMatrix::kScale_Mask | SkMatrix::kTranslate_Mask));
+ mIsIdentity = v.isIdentity();
}
void Matrix4::copyTo(SkMatrix& v) const {
@@ -148,6 +157,7 @@ void Matrix4::loadInverse(const Matrix4& v) {
v.data[kSkewX] * v.data[kSkewY]) * scale;
mSimpleMatrix = v.mSimpleMatrix;
+ mIsIdentity = v.mIsIdentity;
}
void Matrix4::copyTo(float* v) const {
@@ -166,20 +176,27 @@ void Matrix4::multiply(float v) {
for (int i = 0; i < 16; i++) {
data[i] *= v;
}
+ mIsIdentity = false;
}
void Matrix4::loadTranslate(float x, float y, float z) {
loadIdentity();
+
data[kTranslateX] = x;
data[kTranslateY] = y;
data[kTranslateZ] = z;
+
+ mIsIdentity = false;
}
void Matrix4::loadScale(float sx, float sy, float sz) {
loadIdentity();
+
data[kScaleX] = sx;
data[kScaleY] = sy;
data[kScaleZ] = sz;
+
+ mIsIdentity = false;
}
void Matrix4::loadSkew(float sx, float sy) {
@@ -198,6 +215,7 @@ void Matrix4::loadSkew(float sx, float sy) {
data[kPerspective2] = 1.0f;
mSimpleMatrix = false;
+ mIsIdentity = false;
}
void Matrix4::loadRotate(float angle, float x, float y, float z) {
@@ -238,6 +256,7 @@ void Matrix4::loadRotate(float angle, float x, float y, float z) {
data[kScaleZ] = z * z * nc + c;
mSimpleMatrix = false;
+ mIsIdentity = false;
}
void Matrix4::loadMultiply(const Matrix4& u, const Matrix4& v) {
@@ -262,16 +281,20 @@ void Matrix4::loadMultiply(const Matrix4& u, const Matrix4& v) {
}
mSimpleMatrix = u.mSimpleMatrix && v.mSimpleMatrix;
+ mIsIdentity = false;
}
void Matrix4::loadOrtho(float left, float right, float bottom, float top, float near, float far) {
loadIdentity();
+
data[kScaleX] = 2.0f / (right - left);
data[kScaleY] = 2.0f / (top - bottom);
data[kScaleZ] = -2.0f / (far - near);
data[kTranslateX] = -(right + left) / (right - left);
data[kTranslateY] = -(top + bottom) / (top - bottom);
data[kTranslateZ] = -(far + near) / (far - near);
+
+ mIsIdentity = false;
}
#define MUL_ADD_STORE(a, b, c) a = (a) * (b) + (c)
diff --git a/libs/hwui/Matrix.h b/libs/hwui/Matrix.h
index 2fa6ab7757a7..56fd37de813b 100644
--- a/libs/hwui/Matrix.h
+++ b/libs/hwui/Matrix.h
@@ -112,6 +112,7 @@ public:
bool isPureTranslate();
bool isSimple();
+ bool isIdentity();
bool changesBounds();
@@ -128,6 +129,7 @@ public:
private:
bool mSimpleMatrix;
+ bool mIsIdentity;
inline float get(int i, int j) const {
return data[i * 4 + j];
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index 4864cff6931d..a0f806a209ba 100644
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -627,6 +627,12 @@ void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
float alpha = layer->getAlpha() / 255.0f;
+ mat4& transform = layer->getTransform();
+ if (!transform.isIdentity()) {
+ save(0);
+ mSnapshot->transform->multiply(transform);
+ }
+
setupDraw();
if (layer->getRenderTarget() == GL_TEXTURE_2D) {
setupDrawWithTexture();
@@ -663,6 +669,10 @@ void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
finishDrawTexture();
+
+ if (!transform.isIdentity()) {
+ restore();
+ }
}
void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java
index ff2e66bf3394..179b8a45ad60 100644
--- a/media/java/android/media/AudioService.java
+++ b/media/java/android/media/AudioService.java
@@ -1552,14 +1552,17 @@ public class AudioService extends IAudioService.Stub {
int newRingerMode = mRingerMode;
if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
- // audible mode, at the bottom of the scale
- if ((direction == AudioManager.ADJUST_LOWER &&
- mPrevVolDirection != AudioManager.ADJUST_LOWER) &&
- ((oldIndex + 5) / 10 == 0)) {
- // "silent mode", but which one?
- newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1
- ? AudioManager.RINGER_MODE_VIBRATE
- : AudioManager.RINGER_MODE_SILENT;
+ if ((direction == AudioManager.ADJUST_LOWER) && ((oldIndex + 5) / 10 <= 1)) {
+ // enter silent mode if current index is the last audible one and not repeating a
+ // volume key down
+ if (mPrevVolDirection != AudioManager.ADJUST_LOWER) {
+ // "silent mode", but which one?
+ newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1
+ ? AudioManager.RINGER_MODE_VIBRATE
+ : AudioManager.RINGER_MODE_SILENT;
+ } else {
+ adjustVolumeIndex = false;
+ }
}
} else {
if (direction == AudioManager.ADJUST_RAISE) {
diff --git a/media/java/android/media/videoeditor/MediaArtistNativeHelper.java b/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
index 5bfdcdbac2be..8caa04ce760f 100644
--- a/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
+++ b/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
@@ -3781,72 +3781,62 @@ class MediaArtistNativeHelper {
* @param startMs The starting time in ms
* @param endMs The end time in ms
* @param thumbnailCount The number of frames to be extracted
+ * @param indices The indices of thumbnails wanted
+ * @param callback The callback used to pass back the bitmaps
* from startMs to endMs
*
* @return The frames as bitmaps in bitmap array
**/
- Bitmap[] getPixelsList(String filename, int width, int height, long startMs, long endMs,
- int thumbnailCount) {
- int[] rgb888 = null;
- int thumbnailSize = 0;
- Bitmap tempBitmap = null;
-
+ void getPixelsList(String filename, final int width, final int height,
+ long startMs, long endMs, int thumbnailCount, int[] indices,
+ final MediaItem.GetThumbnailListCallback callback) {
/* Make width and height as even */
final int newWidth = (width + 1) & 0xFFFFFFFE;
final int newHeight = (height + 1) & 0xFFFFFFFE;
- thumbnailSize = newWidth * newHeight * 4;
+ final int thumbnailSize = newWidth * newHeight;
/* Create a temp bitmap for resized thumbnails */
- if ((newWidth != width) || (newHeight != height)) {
- tempBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
- }
- int i = 0;
- int deltaTime = (int)(endMs - startMs) / thumbnailCount;
- Bitmap[] bitmaps = null;
-
- try {
- // This may result in out of Memory Error
- rgb888 = new int[thumbnailSize * thumbnailCount];
- bitmaps = new Bitmap[thumbnailCount];
- } catch (Throwable e) {
- // Allocating to new size with Fixed count
- try {
- rgb888 = new int[thumbnailSize * MAX_THUMBNAIL_PERMITTED];
- bitmaps = new Bitmap[MAX_THUMBNAIL_PERMITTED];
- thumbnailCount = MAX_THUMBNAIL_PERMITTED;
- } catch (Throwable ex) {
- throw new RuntimeException("Memory allocation fails, thumbnail count too large: "
- + thumbnailCount);
- }
- }
- IntBuffer tmpBuffer = IntBuffer.allocate(thumbnailSize);
- nativeGetPixelsList(filename, rgb888, newWidth, newHeight, deltaTime, thumbnailCount,
- startMs, endMs);
+ final Bitmap tempBitmap =
+ (newWidth != width || newHeight != height)
+ ? Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888)
+ : null;
+
+ final int[] rgb888 = new int[thumbnailSize];
+ final IntBuffer tmpBuffer = IntBuffer.allocate(thumbnailSize);
+ nativeGetPixelsList(filename, rgb888, newWidth, newHeight,
+ thumbnailCount, startMs, endMs, indices,
+ new NativeGetPixelsListCallback() {
+ public void onThumbnail(int index) {
+ Bitmap bitmap = Bitmap.createBitmap(
+ width, height, Bitmap.Config.ARGB_8888);
+ tmpBuffer.put(rgb888, 0, thumbnailSize);
+ tmpBuffer.rewind();
+
+ if ((newWidth == width) && (newHeight == height)) {
+ bitmap.copyPixelsFromBuffer(tmpBuffer);
+ } else {
+ /* Copy the out rgb buffer to temp bitmap */
+ tempBitmap.copyPixelsFromBuffer(tmpBuffer);
- for (; i < thumbnailCount; i++) {
- bitmaps[i] = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
- tmpBuffer.put(rgb888, (i * thumbnailSize), thumbnailSize);
- tmpBuffer.rewind();
+ /* Create a canvas to resize */
+ final Canvas canvas = new Canvas(bitmap);
+ canvas.drawBitmap(tempBitmap,
+ new Rect(0, 0, newWidth, newHeight),
+ new Rect(0, 0, width, height), sResizePaint);
- if ((newWidth == width) && (newHeight == height)) {
- bitmaps[i].copyPixelsFromBuffer(tmpBuffer);
- } else {
- /* Copy the out rgb buffer to temp bitmap */
- tempBitmap.copyPixelsFromBuffer(tmpBuffer);
-
- /* Create a canvas to resize */
- final Canvas canvas = new Canvas(bitmaps[i]);
- canvas.drawBitmap(tempBitmap, new Rect(0, 0, newWidth, newHeight),
- new Rect(0, 0, width, height), sResizePaint);
- canvas.setBitmap(null);
+ canvas.setBitmap(null);
+ }
+ callback.onThumbnail(bitmap, index);
}
- }
+ });
if (tempBitmap != null) {
tempBitmap.recycle();
}
+ }
- return bitmaps;
+ interface NativeGetPixelsListCallback {
+ public void onThumbnail(int index);
}
/**
@@ -3957,8 +3947,9 @@ class MediaArtistNativeHelper {
private native int nativeGetPixels(String fileName, int[] pixelArray, int width, int height,
long timeMS);
- private native int nativeGetPixelsList(String fileName, int[] pixelArray, int width, int height,
- int timeMS, int nosofTN, long startTimeMs, long endTimeMs);
+ private native int nativeGetPixelsList(String fileName, int[] pixelArray,
+ int width, int height, int nosofTN, long startTimeMs, long endTimeMs,
+ int[] indices, NativeGetPixelsListCallback callback);
/**
* Releases the JNI and cleans up the core native module.. Should be called
diff --git a/media/java/android/media/videoeditor/MediaImageItem.java b/media/java/android/media/videoeditor/MediaImageItem.java
index f0cc1fe945d4..4ca6fad2a69b 100755
--- a/media/java/android/media/videoeditor/MediaImageItem.java
+++ b/media/java/android/media/videoeditor/MediaImageItem.java
@@ -616,17 +616,18 @@ public class MediaImageItem extends MediaItem {
* {@inheritDoc}
*/
@Override
- public Bitmap[] getThumbnailList(int width, int height, long startMs, long endMs,
- int thumbnailCount) throws IOException {
+ public void getThumbnailList(int width, int height,
+ long startMs, long endMs,
+ int thumbnailCount,
+ int[] indices,
+ GetThumbnailListCallback callback)
+ throws IOException {
//KenBurns was not applied on this.
if (getGeneratedImageClip() == null) {
final Bitmap thumbnail = scaleImage(mFilename, width, height);
- final Bitmap[] thumbnailArray = new Bitmap[thumbnailCount];
- for (int i = 0; i < thumbnailCount; i++) {
- thumbnailArray[i] = thumbnail;
+ for (int i = 0; i < indices.length; i++) {
+ callback.onThumbnail(thumbnail, i);
}
-
- return thumbnailArray;
} else {
if (startMs > endMs) {
throw new IllegalArgumentException("Start time is greater than end time");
@@ -636,15 +637,8 @@ public class MediaImageItem extends MediaItem {
throw new IllegalArgumentException("End time is greater than file duration");
}
- if (startMs == endMs) {
- Bitmap[] bitmap = new Bitmap[1];
- bitmap[0] = mMANativeHelper.getPixels(getGeneratedImageClip(),
- width, height,startMs);
- return bitmap;
- }
-
- return mMANativeHelper.getPixelsList(getGeneratedImageClip(), width,
- height,startMs,endMs,thumbnailCount);
+ mMANativeHelper.getPixelsList(getGeneratedImageClip(), width,
+ height, startMs, endMs, thumbnailCount, indices, callback);
}
}
diff --git a/media/java/android/media/videoeditor/MediaItem.java b/media/java/android/media/videoeditor/MediaItem.java
index 8c4841fc216d..4e9ea75a23a6 100755
--- a/media/java/android/media/videoeditor/MediaItem.java
+++ b/media/java/android/media/videoeditor/MediaItem.java
@@ -564,15 +564,41 @@ public abstract class MediaItem {
* @param startMs The start of time range in milliseconds
* @param endMs The end of the time range in milliseconds
* @param thumbnailCount The thumbnail count
- *
- * @return The array of Bitmaps
+ * @param indices The indices of the thumbnails wanted
+ * @param callback The callback used to pass back the bitmaps
*
* @throws IOException if a file error occurs
*/
- public abstract Bitmap[] getThumbnailList(int width, int height,
- long startMs, long endMs,
- int thumbnailCount)
- throws IOException;
+ public abstract void getThumbnailList(int width, int height,
+ long startMs, long endMs,
+ int thumbnailCount,
+ int[] indices,
+ GetThumbnailListCallback callback)
+ throws IOException;
+
+ public interface GetThumbnailListCallback {
+ public void onThumbnail(Bitmap bitmap, int index);
+ }
+
+ // This is for compatibility, only used in tests.
+ public Bitmap[] getThumbnailList(int width, int height,
+ long startMs, long endMs,
+ int thumbnailCount)
+ throws IOException {
+ final Bitmap[] bitmaps = new Bitmap[thumbnailCount];
+ int[] indices = new int[thumbnailCount];
+ for (int i = 0; i < thumbnailCount; i++) {
+ indices[i] = i;
+ }
+ getThumbnailList(width, height, startMs, endMs,
+ thumbnailCount, indices, new GetThumbnailListCallback() {
+ public void onThumbnail(Bitmap bitmap, int index) {
+ bitmaps[index] = bitmap;
+ }
+ });
+
+ return bitmaps;
+ }
/*
* {@inheritDoc}
diff --git a/media/java/android/media/videoeditor/MediaVideoItem.java b/media/java/android/media/videoeditor/MediaVideoItem.java
index 62486515548f..0ac354ba4846 100755
--- a/media/java/android/media/videoeditor/MediaVideoItem.java
+++ b/media/java/android/media/videoeditor/MediaVideoItem.java
@@ -293,8 +293,12 @@ public class MediaVideoItem extends MediaItem {
* {@inheritDoc}
*/
@Override
- public Bitmap[] getThumbnailList(int width, int height, long startMs,
- long endMs, int thumbnailCount) throws IOException {
+ public void getThumbnailList(int width, int height,
+ long startMs, long endMs,
+ int thumbnailCount,
+ int[] indices,
+ GetThumbnailListCallback callback)
+ throws IOException {
if (startMs > endMs) {
throw new IllegalArgumentException("Start time is greater than end time");
}
@@ -307,14 +311,8 @@ public class MediaVideoItem extends MediaItem {
throw new IllegalArgumentException("Invalid dimension");
}
- if (startMs == endMs) {
- final Bitmap[] bitmap = new Bitmap[1];
- bitmap[0] = mMANativeHelper.getPixels(super.getFilename(), width, height,startMs);
- return bitmap;
- }
-
- return mMANativeHelper.getPixelsList(super.getFilename(), width,
- height,startMs,endMs,thumbnailCount);
+ mMANativeHelper.getPixelsList(super.getFilename(), width,
+ height, startMs, endMs, thumbnailCount, indices, callback);
}
/*
diff --git a/media/jni/mediaeditor/VideoBrowserInternal.h b/media/jni/mediaeditor/VideoBrowserInternal.h
index 3cfb6b9270c1..f4eaab8a6df3 100755
--- a/media/jni/mediaeditor/VideoBrowserInternal.h
+++ b/media/jni/mediaeditor/VideoBrowserInternal.h
@@ -26,9 +26,6 @@
#define VIDEO_BROWSER_BGR565
-
-#define VIDEO_BROWSER_PREDECODE_TIME 2000 /* In miliseconds */
-
/*---------------------------- MACROS ----------------------------*/
#define CHECK_PTR(fct, p, err, errValue) \
{ \
diff --git a/media/jni/mediaeditor/VideoBrowserMain.c b/media/jni/mediaeditor/VideoBrowserMain.c
index 2de55e311422..c6c6000ce6bc 100755
--- a/media/jni/mediaeditor/VideoBrowserMain.c
+++ b/media/jni/mediaeditor/VideoBrowserMain.c
@@ -447,13 +447,9 @@ M4OSA_ERR videoBrowserPrepareFrame(M4OSA_Context pContext, M4OSA_UInt32* pTime,
VideoBrowserContext* pC = (VideoBrowserContext*)pContext;
M4OSA_ERR err = M4NO_ERROR;
M4OSA_UInt32 targetTime = 0;
- M4OSA_UInt32 jumpTime = 0;
M4_MediaTime timeMS = 0;
- M4OSA_Int32 rapTime = 0;
- M4OSA_Bool isBackward = M4OSA_FALSE;
M4OSA_Bool bJumpNeeded = M4OSA_FALSE;
-
/*--- Sanity checks ---*/
CHECK_PTR(videoBrowserPrepareFrame, pContext, err, M4ERR_PARAMETER);
CHECK_PTR(videoBrowserPrepareFrame, pTime, err, M4ERR_PARAMETER);
@@ -472,16 +468,11 @@ M4OSA_ERR videoBrowserPrepareFrame(M4OSA_Context pContext, M4OSA_UInt32* pTime,
goto videoBrowserPrepareFrame_cleanUp;
}
- /*--- Check the duration ---*/
- /*--- If we jump backward, we need to jump ---*/
- if (targetTime < pC->m_currentCTS)
- {
- isBackward = M4OSA_TRUE;
- bJumpNeeded = M4OSA_TRUE;
- }
- /*--- If we jumpt to a time greater than "currentTime" + "predecodeTime"
- we need to jump ---*/
- else if (targetTime > (pC->m_currentCTS + VIDEO_BROWSER_PREDECODE_TIME))
+ // If we jump backward or forward to a time greater than current position by
+ // 85ms (~ 2 frames), we want to jump.
+ if (pC->m_currentCTS == 0 ||
+ targetTime < pC->m_currentCTS ||
+ targetTime > (pC->m_currentCTS + 85))
{
bJumpNeeded = M4OSA_TRUE;
}
diff --git a/media/jni/mediaeditor/VideoEditorMain.cpp b/media/jni/mediaeditor/VideoEditorMain.cpp
index 14972a2f7623..7d0f56f51f4d 100755
--- a/media/jni/mediaeditor/VideoEditorMain.cpp
+++ b/media/jni/mediaeditor/VideoEditorMain.cpp
@@ -182,10 +182,11 @@ static int videoEditor_getPixelsList(
jintArray pixelArray,
M4OSA_UInt32 width,
M4OSA_UInt32 height,
- M4OSA_UInt32 deltatimeMS,
M4OSA_UInt32 noOfThumbnails,
- M4OSA_UInt32 startTime,
- M4OSA_UInt32 endTime);
+ jlong startTime,
+ jlong endTime,
+ jintArray indexArray,
+ jobject callback);
static void
videoEditor_startPreview(
@@ -288,7 +289,7 @@ static JNINativeMethod gManualEditMethods[] = {
(void *)videoEditor_release },
{"nativeGetPixels", "(Ljava/lang/String;[IIIJ)I",
(void*)videoEditor_getPixels },
- {"nativeGetPixelsList", "(Ljava/lang/String;[IIIIIJJ)I",
+ {"nativeGetPixelsList", "(Ljava/lang/String;[IIIIJJ[ILandroid/media/videoeditor/MediaArtistNativeHelper$NativeGetPixelsListCallback;)I",
(void*)videoEditor_getPixelsList },
{"getMediaProperties",
"(Ljava/lang/String;)Landroid/media/videoeditor/MediaArtistNativeHelper$Properties;",
@@ -2150,75 +2151,72 @@ static int videoEditor_getPixels(
}
static int videoEditor_getPixelsList(
- JNIEnv* env,
- jobject thiz,
- jstring path,
- jintArray pixelArray,
- M4OSA_UInt32 width,
- M4OSA_UInt32 height,
- M4OSA_UInt32 deltatimeMS,
+ JNIEnv* env,
+ jobject thiz,
+ jstring path,
+ jintArray pixelArray,
+ M4OSA_UInt32 width,
+ M4OSA_UInt32 height,
M4OSA_UInt32 noOfThumbnails,
- M4OSA_UInt32 startTime,
- M4OSA_UInt32 endTime)
+ jlong startTime,
+ jlong endTime,
+ jintArray indexArray,
+ jobject callback)
{
- M4OSA_ERR err;
+ M4OSA_ERR err = M4NO_ERROR;
M4OSA_Context mContext = M4OSA_NULL;
- jint* m_dst32;
- M4OSA_UInt32 timeMS = startTime;
- int arrayOffset = 0;
-
-
-
- // Add a text marker (the condition must always be true).
- ADD_TEXT_MARKER_FUN(NULL != env)
const char *pString = env->GetStringUTFChars(path, NULL);
if (pString == M4OSA_NULL) {
- if (env != NULL) {
- jniThrowException(env, "java/lang/RuntimeException", "Input string null");
- }
+ jniThrowException(env, "java/lang/RuntimeException", "Input string null");
return M4ERR_ALLOC;
}
err = ThumbnailOpen(&mContext,(const M4OSA_Char*)pString, M4OSA_FALSE);
if (err != M4NO_ERROR || mContext == M4OSA_NULL) {
- if (env != NULL) {
- jniThrowException(env, "java/lang/RuntimeException", "ThumbnailOpen failed");
- }
+ jniThrowException(env, "java/lang/RuntimeException", "ThumbnailOpen failed");
if (pString != NULL) {
env->ReleaseStringUTFChars(path, pString);
}
return err;
}
- m_dst32 = env->GetIntArrayElements(pixelArray, NULL);
+ jlong duration = (endTime - startTime);
+ M4OSA_UInt32 tolerance = duration / (2 * noOfThumbnails);
+ jint* m_dst32 = env->GetIntArrayElements(pixelArray, NULL);
+ jint* indices = env->GetIntArrayElements(indexArray, NULL);
+ jsize len = env->GetArrayLength(indexArray);
- M4OSA_UInt32 tolerance = deltatimeMS / 2;
- do {
- err = ThumbnailGetPixels32(mContext, ((M4OSA_Int32 *)m_dst32 + arrayOffset),
- width,height,&timeMS, tolerance);
- if (err != M4NO_ERROR ) {
- if (env != NULL) {
- jniThrowException(env, "java/lang/RuntimeException",\
- "ThumbnailGetPixels32 failed");
- }
- return err;
+ jclass cls = env->GetObjectClass(callback);
+ jmethodID mid = env->GetMethodID(cls, "onThumbnail", "(I)V");
+
+ for (int i = 0; i < len; i++) {
+ int k = indices[i];
+ M4OSA_UInt32 timeMS = startTime;
+ timeMS += (2 * k + 1) * duration / (2 * noOfThumbnails);
+ err = ThumbnailGetPixels32(mContext, ((M4OSA_Int32 *)m_dst32),
+ width, height, &timeMS, tolerance);
+ if (err != M4NO_ERROR) {
+ break;
}
- timeMS += deltatimeMS;
- arrayOffset += (width * height * 4);
- noOfThumbnails--;
- } while(noOfThumbnails > 0);
+ env->CallVoidMethod(callback, mid, (jint)k);
+ }
env->ReleaseIntArrayElements(pixelArray, m_dst32, 0);
+ env->ReleaseIntArrayElements(indexArray, indices, 0);
ThumbnailClose(mContext);
if (pString != NULL) {
env->ReleaseStringUTFChars(path, pString);
}
- return err;
+ if (err != M4NO_ERROR) {
+ jniThrowException(env, "java/lang/RuntimeException",\
+ "ThumbnailGetPixels32 failed");
+ }
+ return err;
}
static M4OSA_ERR
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index b06f20d55c80..7fb141a02124 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -340,6 +340,11 @@ void NuPlayer::onMessageReceived(const sp<AMessage> &msg) {
}
finishFlushIfPossible();
+ } else if (what == ACodec::kWhatError) {
+ LOGE("Received error from %s decoder, aborting playback.",
+ audio ? "audio" : "video");
+
+ mRenderer->queueEOS(audio, UNKNOWN_ERROR);
} else {
CHECK_EQ((int)what, (int)ACodec::kWhatDrainThisBuffer);
@@ -358,13 +363,24 @@ void NuPlayer::onMessageReceived(const sp<AMessage> &msg) {
int32_t audio;
CHECK(msg->findInt32("audio", &audio));
+ int32_t finalResult;
+ CHECK(msg->findInt32("finalResult", &finalResult));
+
if (audio) {
mAudioEOS = true;
} else {
mVideoEOS = true;
}
- LOGV("reached %s EOS", audio ? "audio" : "video");
+ if (finalResult == ERROR_END_OF_STREAM) {
+ LOGV("reached %s EOS", audio ? "audio" : "video");
+ } else {
+ LOGE("%s track encountered an error (0x%08x)",
+ audio ? "audio" : "video", finalResult);
+
+ notifyListener(
+ MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult);
+ }
if ((mAudioEOS || mAudioDecoder == NULL)
&& (mVideoEOS || mVideoDecoder == NULL)) {
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
index 828e00863ea8..35ed43fc441e 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
@@ -200,19 +200,6 @@ void NuPlayer::Renderer::signalAudioSinkChanged() {
void NuPlayer::Renderer::onDrainAudioQueue() {
for (;;) {
- uint32_t numFramesPlayed;
- CHECK_EQ(mAudioSink->getPosition(&numFramesPlayed), (status_t)OK);
-
- ssize_t numFramesAvailableToWrite =
- mAudioSink->frameCount() - (mNumFramesWritten - numFramesPlayed);
-
- size_t numBytesAvailableToWrite =
- numFramesAvailableToWrite * mAudioSink->frameSize();
-
- if (numBytesAvailableToWrite == 0) {
- break;
- }
-
if (mAudioQueue.empty()) {
break;
}
@@ -222,13 +209,26 @@ void NuPlayer::Renderer::onDrainAudioQueue() {
if (entry->mBuffer == NULL) {
// EOS
- notifyEOS(true /* audio */);
+ notifyEOS(true /* audio */, entry->mFinalResult);
mAudioQueue.erase(mAudioQueue.begin());
entry = NULL;
return;
}
+ uint32_t numFramesPlayed;
+ CHECK_EQ(mAudioSink->getPosition(&numFramesPlayed), (status_t)OK);
+
+ ssize_t numFramesAvailableToWrite =
+ mAudioSink->frameCount() - (mNumFramesWritten - numFramesPlayed);
+
+ size_t numBytesAvailableToWrite =
+ numFramesAvailableToWrite * mAudioSink->frameSize();
+
+ if (numBytesAvailableToWrite == 0) {
+ break;
+ }
+
if (entry->mOffset == 0) {
int64_t mediaTimeUs;
CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
@@ -330,7 +330,7 @@ void NuPlayer::Renderer::onDrainVideoQueue() {
if (entry->mBuffer == NULL) {
// EOS
- notifyEOS(false /* audio */);
+ notifyEOS(false /* audio */, entry->mFinalResult);
mVideoQueue.erase(mVideoQueue.begin());
entry = NULL;
@@ -352,10 +352,11 @@ void NuPlayer::Renderer::onDrainVideoQueue() {
notifyPosition();
}
-void NuPlayer::Renderer::notifyEOS(bool audio) {
+void NuPlayer::Renderer::notifyEOS(bool audio, status_t finalResult) {
sp<AMessage> notify = mNotify->dup();
notify->setInt32("what", kWhatEOS);
notify->setInt32("audio", static_cast<int32_t>(audio));
+ notify->setInt32("finalResult", finalResult);
notify->post();
}
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
index 703e9715ad94..2713031f4b70 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
@@ -111,7 +111,7 @@ private:
void onPause();
void onResume();
- void notifyEOS(bool audio);
+ void notifyEOS(bool audio, status_t finalResult);
void notifyFlushComplete(bool audio);
void notifyPosition();
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index 174ec926c692..5d91f6a97e72 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -285,21 +285,6 @@ private:
////////////////////////////////////////////////////////////////////////////////
-struct ACodec::ErrorState : public ACodec::BaseState {
- ErrorState(ACodec *codec);
-
-protected:
- virtual bool onMessageReceived(const sp<AMessage> &msg);
- virtual void stateEntered();
-
- virtual bool onOMXEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2);
-
-private:
- DISALLOW_EVIL_CONSTRUCTORS(ErrorState);
-};
-
-////////////////////////////////////////////////////////////////////////////////
-
struct ACodec::FlushingState : public ACodec::BaseState {
FlushingState(ACodec *codec);
@@ -335,7 +320,6 @@ ACodec::ACodec()
mExecutingToIdleState = new ExecutingToIdleState(this);
mIdleToLoadedState = new IdleToLoadedState(this);
- mErrorState = new ErrorState(this);
mFlushingState = new FlushingState(this);
mPortEOS[kPortIndexInput] = mPortEOS[kPortIndexOutput] = false;
@@ -594,7 +578,10 @@ status_t ACodec::cancelBufferToNativeWindow(BufferInfo *info) {
ACodec::BufferInfo *ACodec::dequeueBufferFromNativeWindow() {
ANativeWindowBuffer *buf;
- CHECK_EQ(mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf), 0);
+ if (mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf) != 0) {
+ LOGE("dequeueBuffer failed.");
+ return NULL;
+ }
for (size_t i = mBuffers[kPortIndexOutput].size(); i-- > 0;) {
BufferInfo *info =
@@ -1263,10 +1250,12 @@ bool ACodec::BaseState::onOMXEvent(
return false;
}
- LOGE("[%s] ERROR(0x%08lx, 0x%08lx)",
- mCodec->mComponentName.c_str(), data1, data2);
+ LOGE("[%s] ERROR(0x%08lx)", mCodec->mComponentName.c_str(), data1);
- mCodec->changeState(mCodec->mErrorState);
+ sp<AMessage> notify = mCodec->mNotify->dup();
+ notify->setInt32("what", ACodec::kWhatError);
+ notify->setInt32("omx-error", data1);
+ notify->post();
return true;
}
@@ -1595,13 +1584,15 @@ void ACodec::BaseState::onOutputBufferDrained(const sp<AMessage> &msg) {
info = mCodec->dequeueBufferFromNativeWindow();
}
- LOGV("[%s] calling fillBuffer %p",
- mCodec->mComponentName.c_str(), info->mBufferID);
+ if (info != NULL) {
+ LOGV("[%s] calling fillBuffer %p",
+ mCodec->mComponentName.c_str(), info->mBufferID);
- CHECK_EQ(mCodec->mOMX->fillBuffer(mCodec->mNode, info->mBufferID),
- (status_t)OK);
+ CHECK_EQ(mCodec->mOMX->fillBuffer(mCodec->mNode, info->mBufferID),
+ (status_t)OK);
- info->mStatus = BufferInfo::OWNED_BY_COMPONENT;
+ info->mStatus = BufferInfo::OWNED_BY_COMPONENT;
+ }
}
break;
}
@@ -1642,6 +1633,7 @@ bool ACodec::UninitializedState::onMessageReceived(const sp<AMessage> &msg) {
notify->post();
handled = true;
+ break;
}
case ACodec::kWhatFlush:
@@ -1651,6 +1643,7 @@ bool ACodec::UninitializedState::onMessageReceived(const sp<AMessage> &msg) {
notify->post();
handled = true;
+ break;
}
default:
@@ -1696,7 +1689,16 @@ void ACodec::UninitializedState::onSetup(
node = NULL;
}
- CHECK(node != NULL);
+ if (node == NULL) {
+ LOGE("Unable to instantiate a decoder for type '%s'.", mime.c_str());
+
+ sp<AMessage> notify = mCodec->mNotify->dup();
+ notify->setInt32("what", ACodec::kWhatError);
+ notify->setInt32("omx-error", OMX_ErrorComponentNotFound);
+ notify->post();
+
+ return;
+ }
sp<AMessage> notify = new AMessage(kWhatOMXMessage, mCodec->id());
observer->setNotificationMessage(notify);
@@ -2236,26 +2238,6 @@ bool ACodec::IdleToLoadedState::onOMXEvent(
////////////////////////////////////////////////////////////////////////////////
-ACodec::ErrorState::ErrorState(ACodec *codec)
- : BaseState(codec) {
-}
-
-bool ACodec::ErrorState::onMessageReceived(const sp<AMessage> &msg) {
- return BaseState::onMessageReceived(msg);
-}
-
-void ACodec::ErrorState::stateEntered() {
- LOGV("[%s] Now in ErrorState", mCodec->mComponentName.c_str());
-}
-
-bool ACodec::ErrorState::onOMXEvent(
- OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
- LOGV("EVENT(%d, 0x%08lx, 0x%08lx)", event, data1, data2);
- return true;
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
ACodec::FlushingState::FlushingState(ACodec *codec)
: BaseState(codec) {
}
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
index b9e4f9fb1223..0b1a2af46bc5 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -131,11 +131,9 @@ LOCAL_SHARED_LIBRARIES += \
libdl \
LOCAL_STATIC_LIBRARIES += \
- libstagefright_chromium_http \
- libwebcore \
- libchromium_net \
+ libstagefright_chromium_http
-LOCAL_SHARED_LIBRARIES += libstlport
+LOCAL_SHARED_LIBRARIES += libstlport libchromium_net
include external/stlport/libstlport.mk
LOCAL_CPPFLAGS += -DCHROMIUM_AVAILABLE=1
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index 0ea880b35a7a..99242ab9ff92 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -574,6 +574,8 @@ void AwesomePlayer::reset_l() {
mStats.mTracks.clear();
}
+ mWatchForAudioSeekComplete = false;
+ mWatchForAudioEOS = false;
}
void AwesomePlayer::notifyListener_l(int msg, int ext1, int ext2) {
diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp
index 644c413f6fee..27dfeab4cb6f 100755
--- a/media/libstagefright/OMXCodec.cpp
+++ b/media/libstagefright/OMXCodec.cpp
@@ -3199,9 +3199,16 @@ void OMXCodec::setState(State newState) {
}
status_t OMXCodec::waitForBufferFilled_l() {
+
+ if (mIsEncoder) {
+ // For timelapse video recording, the timelapse video recording may
+ // not send an input frame for a _long_ time. Do not use timeout
+ // for video encoding.
+ return mBufferFilled.wait(mLock);
+ }
status_t err = mBufferFilled.waitRelative(mLock, kBufferFilledEventTimeOutUs);
if (err != OK) {
- LOGE("Timed out waiting for buffers from video encoder: %d/%d",
+ CODEC_LOGE("Timed out waiting for output buffers: %d/%d",
countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
countBuffersWeOwn(mPortBuffers[kPortIndexOutput]));
}
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java
index 369a067165ce..e5ecd5cde2ee 100755
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java
@@ -16,8 +16,7 @@
package com.android.mediaframeworktest;
-import android.media.EncoderCapabilities.AudioEncoderCap;
-import android.media.EncoderCapabilities.VideoEncoderCap;
+import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.test.InstrumentationTestRunner;
@@ -29,20 +28,21 @@ import junit.framework.TestSuite;
public class MediaRecorderStressTestRunner extends InstrumentationTestRunner {
- public static List<VideoEncoderCap> videoEncoders = MediaProfileReader.getVideoEncoders();
- public static List<AudioEncoderCap> audioEncoders = MediaProfileReader.getAudioEncoders();
-
- //Get the first capability as the default
- public static VideoEncoderCap videoEncoder = videoEncoders.get(0);
- public static AudioEncoderCap audioEncoder = audioEncoders.get(0);
+ // MediaRecorder stress test sets one of the cameras as the video source. As
+ // a result, we should make sure that the encoding parameters as input to
+ // the test must be supported by the corresponding camera.
+ public static int mCameraId = 0;
+ public static int mProfileQuality = CamcorderProfile.QUALITY_HIGH;
+ public static CamcorderProfile profile =
+ CamcorderProfile.get(mCameraId, mProfileQuality);
public static int mIterations = 100;
- public static int mVideoEncoder = videoEncoder.mCodec;
- public static int mAudioEncdoer = audioEncoder.mCodec;
- public static int mFrameRate = videoEncoder.mMaxFrameRate;
- public static int mVideoWidth = videoEncoder.mMaxFrameWidth;
- public static int mVideoHeight = videoEncoder.mMaxFrameHeight;
- public static int mBitRate = audioEncoder.mMaxBitRate;
+ public static int mVideoEncoder = profile.videoCodec;
+ public static int mAudioEncdoer = profile.audioCodec;
+ public static int mFrameRate = profile.videoFrameRate;
+ public static int mVideoWidth = profile.videoFrameWidth;
+ public static int mVideoHeight = profile.videoFrameHeight;
+ public static int mBitRate = profile.videoBitRate;
public static boolean mRemoveVideo = true;
public static int mDuration = 10000;
diff --git a/packages/SystemUI/res/layout-sw600dp/status_bar_notification_area.xml b/packages/SystemUI/res/layout-sw600dp/status_bar_notification_area.xml
index 955d8aee1c0f..d2358592ca91 100644
--- a/packages/SystemUI/res/layout-sw600dp/status_bar_notification_area.xml
+++ b/packages/SystemUI/res/layout-sw600dp/status_bar_notification_area.xml
@@ -130,6 +130,7 @@
android:id="@+id/battery"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
+ android:paddingLeft="6dip"
/>
</LinearLayout>
</LinearLayout>
diff --git a/packages/SystemUI/res/layout/navigation_bar.xml b/packages/SystemUI/res/layout/navigation_bar.xml
index 6732feeb7a38..d1919ca2a44e 100644
--- a/packages/SystemUI/res/layout/navigation_bar.xml
+++ b/packages/SystemUI/res/layout/navigation_bar.xml
@@ -66,6 +66,7 @@
android:layout_height="match_parent"
android:src="@drawable/ic_sysbar_home"
systemui:keyCode="3"
+ systemui:keyRepeat="false"
android:layout_weight="0"
systemui:glowBackground="@drawable/ic_sysbar_highlight"
android:contentDescription="@string/accessibility_home"
@@ -148,6 +149,7 @@
android:layout_width="match_parent"
android:src="@drawable/ic_sysbar_home_land"
systemui:keyCode="3"
+ systemui:keyRepeat="false"
android:layout_weight="0"
android:contentDescription="@string/accessibility_home"
systemui:glowBackground="@drawable/ic_sysbar_highlight_land"
diff --git a/packages/SystemUI/res/values/attrs.xml b/packages/SystemUI/res/values/attrs.xml
index b2b6d506b0ed..56d1295fc18e 100644
--- a/packages/SystemUI/res/values/attrs.xml
+++ b/packages/SystemUI/res/values/attrs.xml
@@ -16,7 +16,11 @@
<resources>
<declare-styleable name="KeyButtonView">
+ <!-- key code to send when pressed; if absent or 0, no key is sent -->
<attr name="keyCode" format="integer" />
+ <!-- does this button generate longpress / repeat events? -->
+ <attr name="keyRepeat" format="boolean" />
+ <!-- drawable to use for a swelling, glowing background on press -->
<attr name="glowBackground" format="reference" />
</declare-styleable>
<declare-styleable name="ToggleSlider">
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
index 71cbc612ac5a..2e14bef6850a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -468,7 +468,7 @@ public class PhoneStatusBar extends StatusBar {
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
| WindowManager.LayoutParams.FLAG_SLIPPERY,
- PixelFormat.TRANSLUCENT);
+ PixelFormat.OPAQUE);
lp.setTitle("NavigationBar");
switch (rotation) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java
index 38a10299fa12..fc18eefd61f3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java
@@ -57,11 +57,12 @@ public class KeyButtonView extends ImageView {
int mTouchSlop;
Drawable mGlowBG;
float mGlowAlpha = 0f, mGlowScale = 1f, mDrawingAlpha = 1f;
+ boolean mSupportsLongpress = true;
Runnable mCheckLongPress = new Runnable() {
public void run() {
if (isPressed()) {
-
+ // Slog.d("KeyButtonView", "longpressed: " + this);
if (mCode != 0) {
mRepeat++;
sendEvent(KeyEvent.ACTION_DOWN,
@@ -89,6 +90,8 @@ public class KeyButtonView extends ImageView {
defStyle, 0);
mCode = a.getInteger(R.styleable.KeyButtonView_keyCode, 0);
+
+ mSupportsLongpress = a.getBoolean(R.styleable.KeyButtonView_keyRepeat, true);
mGlowBG = a.getDrawable(R.styleable.KeyButtonView_glowBackground);
if (mGlowBG != null) {
@@ -207,11 +210,19 @@ public class KeyButtonView extends ImageView {
mDownTime = SystemClock.uptimeMillis();
mRepeat = 0;
mSending = true;
+ setPressed(true);
sendEvent(KeyEvent.ACTION_DOWN,
KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY, mDownTime);
- setPressed(true);
- removeCallbacks(mCheckLongPress);
- postDelayed(mCheckLongPress, ViewConfiguration.getLongPressTimeout());
+ if (mSupportsLongpress) {
+ removeCallbacks(mCheckLongPress);
+ postDelayed(mCheckLongPress, ViewConfiguration.getLongPressTimeout());
+ } else {
+ mSending = false;
+ sendEvent(KeyEvent.ACTION_UP,
+ KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY, mDownTime);
+ sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
+ playSoundEffect(SoundEffectConstants.CLICK);
+ }
break;
case MotionEvent.ACTION_MOVE:
if (mSending) {
@@ -230,7 +241,9 @@ public class KeyButtonView extends ImageView {
sendEvent(KeyEvent.ACTION_UP,
KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY
| KeyEvent.FLAG_CANCELED);
- removeCallbacks(mCheckLongPress);
+ if (mSupportsLongpress) {
+ removeCallbacks(mCheckLongPress);
+ }
}
break;
case MotionEvent.ACTION_UP:
@@ -239,15 +252,15 @@ public class KeyButtonView extends ImageView {
if (mSending) {
mSending = false;
final int flags = KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY;
- removeCallbacks(mCheckLongPress);
+ if (mSupportsLongpress) {
+ removeCallbacks(mCheckLongPress);
+ }
if (mCode != 0) {
if (doIt) {
sendEvent(KeyEvent.ACTION_UP, flags);
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
playSoundEffect(SoundEffectConstants.CLICK);
- } else {
- sendEvent(KeyEvent.ACTION_UP, flags | KeyEvent.FLAG_CANCELED);
}
} else {
// no key code, just a regular ImageView
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindow.java b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
index 3dcc297dde25..0ee6488c1816 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindow.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
@@ -235,6 +235,11 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback {
}
@Override
+ public void setUiOptions(int uiOptions, int mask) {
+ mUiOptions = (mUiOptions & ~mask) | (uiOptions & mask);
+ }
+
+ @Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index f88b311147b8..b60a0381533a 100755
--- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -2850,7 +2850,7 @@ public class PhoneWindowManager implements WindowManagerPolicy {
// or orientation sensor disabled
//or case.unspecified
if (mHdmiPlugged) {
- return Surface.ROTATION_0;
+ return mLandscapeRotation;
} else if (mLidOpen == LID_OPEN) {
return mLidOpenRotation;
} else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
diff --git a/services/input/InputDispatcher.cpp b/services/input/InputDispatcher.cpp
index cbdfe8c4ac38..3cd3ac3c06e1 100644
--- a/services/input/InputDispatcher.cpp
+++ b/services/input/InputDispatcher.cpp
@@ -3196,10 +3196,12 @@ void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inpu
LOGD("Focus left window: %s",
mFocusedWindowHandle->name.string());
#endif
- CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
- "focus left window");
- synthesizeCancelationEventsForInputChannelLocked(
- mFocusedWindowHandle->inputChannel, options);
+ if (mFocusedWindowHandle->inputChannel != NULL) {
+ CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
+ "focus left window");
+ synthesizeCancelationEventsForInputChannelLocked(
+ mFocusedWindowHandle->inputChannel, options);
+ }
}
if (newFocusedWindowHandle != NULL) {
#if DEBUG_FOCUS
@@ -3216,10 +3218,12 @@ void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inpu
#if DEBUG_FOCUS
LOGD("Touched window was removed: %s", touchedWindow.windowHandle->name.string());
#endif
- CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
- "touched window was removed");
- synthesizeCancelationEventsForInputChannelLocked(
- touchedWindow.windowHandle->inputChannel, options);
+ if (touchedWindow.windowHandle->inputChannel != NULL) {
+ CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
+ "touched window was removed");
+ synthesizeCancelationEventsForInputChannelLocked(
+ touchedWindow.windowHandle->inputChannel, options);
+ }
mTouchState.windows.removeAt(i--);
}
}
diff --git a/services/java/com/android/server/AppWidgetService.java b/services/java/com/android/server/AppWidgetService.java
index a679ca72daa2..f5fd6bd866a5 100644
--- a/services/java/com/android/server/AppWidgetService.java
+++ b/services/java/com/android/server/AppWidgetService.java
@@ -817,11 +817,10 @@ class AppWidgetService extends IAppWidgetService.Stub
}
Provider lookupProviderLocked(ComponentName provider) {
- final String className = provider.getClassName();
final int N = mInstalledProviders.size();
for (int i=0; i<N; i++) {
Provider p = mInstalledProviders.get(i);
- if (p.info.provider.equals(provider) || className.equals(p.info.oldName)) {
+ if (p.info.provider.equals(provider)) {
return p;
}
}
@@ -1006,11 +1005,6 @@ class AppWidgetService extends IAppWidgetService.Stub
p = new Provider();
AppWidgetProviderInfo info = p.info = new AppWidgetProviderInfo();
- // If metaData was null, we would have returned earlier when getting
- // the parser No need to do the check here
- info.oldName = activityInfo.metaData.getString(
- AppWidgetManager.META_DATA_APPWIDGET_OLD_NAME);
-
info.provider = component;
p.uid = activityInfo.applicationInfo.uid;
diff --git a/services/java/com/android/server/BatteryService.java b/services/java/com/android/server/BatteryService.java
index 1aff9a2b80d0..ab9ae69b9945 100644
--- a/services/java/com/android/server/BatteryService.java
+++ b/services/java/com/android/server/BatteryService.java
@@ -498,7 +498,7 @@ class BatteryService extends Binder {
return;
}
- if (args == null || args.length == 0) {
+ if (args == null || args.length == 0 || "-a".equals(args[0])) {
synchronized (this) {
pw.println("Current Battery Service state:");
pw.println(" AC powered: " + mAcOnline);
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index a5066367e2cb..22ce48447598 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -468,14 +468,10 @@ public class ConnectivityService extends IConnectivityManager.Stub {
for (int netType : mPriorityList) {
switch (mNetConfigs[netType].radio) {
case ConnectivityManager.TYPE_WIFI:
- if (DBG) log("Starting Wifi Service.");
- WifiStateTracker wst = new WifiStateTracker();
- WifiService wifiService = new WifiService(context);
- ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
- wifiService.checkAndStartWifi();
- mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
- wst.startMonitoring(context, mHandler);
- break;
+ mNetTrackers[netType] = new WifiStateTracker(netType,
+ mNetConfigs[netType].name);
+ mNetTrackers[netType].startMonitoring(context, mHandler);
+ break;
case ConnectivityManager.TYPE_MOBILE:
mNetTrackers[netType] = new MobileDataStateTracker(netType,
mNetConfigs[netType].name);
@@ -882,15 +878,8 @@ public class ConnectivityService extends IConnectivityManager.Stub {
FeatureUser f = new FeatureUser(networkType, feature, binder);
- // TODO - move this into the MobileDataStateTracker
- int usedNetworkType = networkType;
- if(networkType == ConnectivityManager.TYPE_MOBILE) {
- usedNetworkType = convertFeatureToNetworkType(feature);
- if (usedNetworkType < 0) {
- loge("Can't match any netTracker!");
- usedNetworkType = networkType;
- }
- }
+ // TODO - move this into individual networktrackers
+ int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
if (mProtectedNetworks.contains(usedNetworkType)) {
enforceConnectivityInternalPermission();
@@ -900,7 +889,6 @@ public class ConnectivityService extends IConnectivityManager.Stub {
if (network != null) {
Integer currentPid = new Integer(getCallingPid());
if (usedNetworkType != networkType) {
- NetworkStateTracker radio = mNetTrackers[networkType];
NetworkInfo ni = network.getNetworkInfo();
if (ni.isAvailable() == false) {
@@ -1046,14 +1034,9 @@ public class ConnectivityService extends IConnectivityManager.Stub {
}
}
- // TODO - move to MobileDataStateTracker
- int usedNetworkType = networkType;
- if (networkType == ConnectivityManager.TYPE_MOBILE) {
- usedNetworkType = convertFeatureToNetworkType(feature);
- if (usedNetworkType < 0) {
- usedNetworkType = networkType;
- }
- }
+ // TODO - move to individual network trackers
+ int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
+
tracker = mNetTrackers[usedNetworkType];
if (tracker == null) {
if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
@@ -1780,14 +1763,20 @@ public class ConnectivityService extends IConnectivityManager.Stub {
mCurrentLinkProperties[netType] = newLp;
boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
- if (doReset || resetMask != 0 || resetDns) {
+ if (resetMask != 0 || resetDns) {
LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
if (linkProperties != null) {
String iface = linkProperties.getInterfaceName();
if (TextUtils.isEmpty(iface) == false) {
- if (doReset || resetMask != 0) {
+ if (resetMask != 0) {
if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
NetworkUtils.resetConnections(iface, resetMask);
+
+ // Tell VPN the interface is down. It is a temporary
+ // but effective fix to make VPN aware of the change.
+ if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
+ mVpn.interfaceStatusChanged(iface, false);
+ }
}
if (resetDns) {
if (DBG) log("resetting DNS cache for " + iface);
@@ -2666,25 +2655,38 @@ public class ConnectivityService extends IConnectivityManager.Stub {
Slog.e(TAG, s);
}
- int convertFeatureToNetworkType(String feature){
- int networkType = -1;
- if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
- networkType = ConnectivityManager.TYPE_MOBILE_MMS;
- } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
- networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
- } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
- TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
- networkType = ConnectivityManager.TYPE_MOBILE_DUN;
- } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
- networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
- } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
- networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
- } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
- networkType = ConnectivityManager.TYPE_MOBILE_IMS;
- } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
- networkType = ConnectivityManager.TYPE_MOBILE_CBS;
- }
- return networkType;
+ int convertFeatureToNetworkType(int networkType, String feature) {
+ int usedNetworkType = networkType;
+
+ if(networkType == ConnectivityManager.TYPE_MOBILE) {
+ if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
+ usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
+ } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
+ usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
+ } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
+ TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
+ usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
+ } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
+ usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
+ } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
+ usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
+ } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
+ usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
+ } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
+ usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
+ } else {
+ Slog.e(TAG, "Can't match any mobile netTracker!");
+ }
+ } else if (networkType == ConnectivityManager.TYPE_WIFI) {
+ if (TextUtils.equals(feature, "p2p")) {
+ usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
+ } else {
+ Slog.e(TAG, "Can't match any wifi netTracker!");
+ }
+ } else {
+ Slog.e(TAG, "Unexpected network type");
+ }
+ return usedNetworkType;
}
private static <T> T checkNotNull(T value, String message) {
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 77d045709b10..5dd3c5b117ba 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -110,6 +110,7 @@ class ServerThread extends Thread {
NetworkPolicyManagerService networkPolicy = null;
ConnectivityService connectivity = null;
WifiP2pService wifiP2p = null;
+ WifiService wifi = null;
IPackageManager pm = null;
Context context = null;
WindowManagerService wm = null;
@@ -309,6 +310,15 @@ class ServerThread extends Thread {
Slog.e(TAG, "Failure starting Wi-Fi P2pService", e);
}
+ try {
+ Slog.i(TAG, "Wi-Fi Service");
+ wifi = new WifiService(context);
+ ServiceManager.addService(Context.WIFI_SERVICE, wifi);
+ wifi.checkAndStartWifi();
+ } catch (Throwable e) {
+ Slog.e(TAG, "Failure starting Wi-Fi Service", e);
+ }
+
try {
Slog.i(TAG, "Connectivity Service");
connectivity = new ConnectivityService(context, networkManagement, networkPolicy);
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index 33a4e51012d7..e9c91e6fbf25 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -10732,8 +10732,10 @@ public final class ActivityManagerService extends ActivityManagerNative
if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
+ " at " + b + ": apps="
+ (b != null ? b.apps.size() : 0));
+
+ boolean inStopping = mStoppingServices.contains(r);
if (b != null) {
- if (b.apps.size() > 0) {
+ if (b.apps.size() > 0 && !inStopping) {
// Applications have already bound since the last
// unbind, so just rebind right here.
requestServiceBindingLocked(r, b, true);
@@ -10744,7 +10746,7 @@ public final class ActivityManagerService extends ActivityManagerNative
}
}
- serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
+ serviceDoneExecutingLocked(r, inStopping);
Binder.restoreCallingIdentity(origId);
}
diff --git a/services/java/com/android/server/am/BatteryStatsService.java b/services/java/com/android/server/am/BatteryStatsService.java
index 293702dfe750..226723fbed6c 100644
--- a/services/java/com/android/server/am/BatteryStatsService.java
+++ b/services/java/com/android/server/am/BatteryStatsService.java
@@ -478,6 +478,8 @@ public final class BatteryStatsService extends IBatteryStats.Stub {
} else if ("-h".equals(arg)) {
dumpHelp(pw);
return;
+ } else if ("-a".equals(arg)) {
+ // fall through
} else {
pw.println("Unknown option: " + arg);
dumpHelp(pw);
diff --git a/services/java/com/android/server/connectivity/Vpn.java b/services/java/com/android/server/connectivity/Vpn.java
index d9da92cc3d01..6b65e07ee570 100644
--- a/services/java/com/android/server/connectivity/Vpn.java
+++ b/services/java/com/android/server/connectivity/Vpn.java
@@ -265,7 +265,6 @@ public class Vpn extends INetworkManagementEventObserver.Stub {
// INetworkManagementEventObserver.Stub
@Override
public void interfaceLinkStateChanged(String interfaze, boolean up) {
- interfaceStatusChanged(interfaze, up);
}
// INetworkManagementEventObserver.Stub
@@ -280,6 +279,9 @@ public class Vpn extends INetworkManagementEventObserver.Stub {
if (mConnection != null) {
mContext.unbindService(mConnection);
mConnection = null;
+ } else if (mLegacyVpnRunner != null) {
+ mLegacyVpnRunner.exit();
+ mLegacyVpnRunner = null;
}
}
}
diff --git a/services/java/com/android/server/usb/UsbDeviceManager.java b/services/java/com/android/server/usb/UsbDeviceManager.java
index 91c5e332304b..a01c9758bb58 100644
--- a/services/java/com/android/server/usb/UsbDeviceManager.java
+++ b/services/java/com/android/server/usb/UsbDeviceManager.java
@@ -253,13 +253,6 @@ public class UsbDeviceManager {
}
};
- private static final int NOTIFICATION_NONE = 0;
- private static final int NOTIFICATION_MTP = 1;
- private static final int NOTIFICATION_PTP = 2;
- private static final int NOTIFICATION_INSTALLER = 3;
- private static final int NOTIFICATION_ACCESSORY = 4;
- private static final int NOTIFICATION_ADB = 5;
-
public UsbHandler(Looper looper) {
super(looper);
try {
@@ -536,27 +529,18 @@ public class UsbDeviceManager {
private void updateUsbNotification() {
if (mNotificationManager == null || !mUseUsbNotification) return;
- int id = NOTIFICATION_NONE;
+ int id = 0;
Resources r = mContext.getResources();
- CharSequence title = null;
if (mConnected) {
if (containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_MTP)) {
- title = r.getText(
- com.android.internal.R.string.usb_mtp_notification_title);
- id = NOTIFICATION_MTP;
+ id = com.android.internal.R.string.usb_mtp_notification_title;
} else if (containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_PTP)) {
- title = r.getText(
- com.android.internal.R.string.usb_ptp_notification_title);
- id = NOTIFICATION_PTP;
+ id = com.android.internal.R.string.usb_ptp_notification_title;
} else if (containsFunction(mCurrentFunctions,
UsbManager.USB_FUNCTION_MASS_STORAGE)) {
- title = r.getText(
- com.android.internal.R.string.usb_cd_installer_notification_title);
- id = NOTIFICATION_INSTALLER;
+ id = com.android.internal.R.string.usb_cd_installer_notification_title;
} else if (containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_ACCESSORY)) {
- title = r.getText(
- com.android.internal.R.string.usb_accessory_notification_title);
- id = NOTIFICATION_ACCESSORY;
+ id = com.android.internal.R.string.usb_accessory_notification_title;
} else {
// There is a different notification for USB tethering so we don't need one here
if (!containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_RNDIS)) {
@@ -566,13 +550,14 @@ public class UsbDeviceManager {
}
if (id != mUsbNotificationId) {
// clear notification if title needs changing
- if (mUsbNotificationId != NOTIFICATION_NONE) {
+ if (mUsbNotificationId != 0) {
mNotificationManager.cancel(mUsbNotificationId);
- mUsbNotificationId = NOTIFICATION_NONE;
+ mUsbNotificationId = 0;
}
- if (id != NOTIFICATION_NONE) {
+ if (id != 0) {
CharSequence message = r.getText(
com.android.internal.R.string.usb_notification_message);
+ CharSequence title = r.getText(id);
Notification notification = new Notification();
notification.icon = com.android.internal.R.drawable.stat_sys_data_usb;
@@ -600,13 +585,13 @@ public class UsbDeviceManager {
private void updateAdbNotification() {
if (mNotificationManager == null) return;
+ final int id = com.android.internal.R.string.adb_active_notification_title;
if (mAdbEnabled && mConnected) {
if ("0".equals(SystemProperties.get("persist.adb.notify"))) return;
if (!mAdbNotificationShown) {
Resources r = mContext.getResources();
- CharSequence title = r.getText(
- com.android.internal.R.string.adb_active_notification_title);
+ CharSequence title = r.getText(id);
CharSequence message = r.getText(
com.android.internal.R.string.adb_active_notification_message);
@@ -629,11 +614,11 @@ public class UsbDeviceManager {
intent, 0);
notification.setLatestEventInfo(mContext, title, message, pi);
mAdbNotificationShown = true;
- mNotificationManager.notify(NOTIFICATION_ADB, notification);
+ mNotificationManager.notify(id, notification);
}
} else if (mAdbNotificationShown) {
mAdbNotificationShown = false;
- mNotificationManager.cancel(NOTIFICATION_ADB);
+ mNotificationManager.cancel(id);
}
}
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index 5967428a33b6..8fd4f9589df0 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -6573,8 +6573,10 @@ public class WindowManagerService extends IWindowManager.Stub
}
synchronized (mWindowMap) {
// !!! TODO: ANR the drag-receiving app
- mDragState.mDragResult = false;
- mDragState.endDragLw();
+ if (mDragState != null) {
+ mDragState.mDragResult = false;
+ mDragState.endDragLw();
+ }
}
break;
}
diff --git a/services/surfaceflinger/Android.mk b/services/surfaceflinger/Android.mk
index b178e4979b2c..51eb0a376d06 100644
--- a/services/surfaceflinger/Android.mk
+++ b/services/surfaceflinger/Android.mk
@@ -5,6 +5,7 @@ LOCAL_SRC_FILES:= \
Layer.cpp \
LayerBase.cpp \
LayerDim.cpp \
+ DdmConnection.cpp \
DisplayHardware/DisplayHardware.cpp \
DisplayHardware/DisplayHardwareBase.cpp \
DisplayHardware/HWComposer.cpp \
@@ -36,6 +37,9 @@ LOCAL_SHARED_LIBRARIES := \
libui \
libgui
+# this is only needed for DDMS debugging
+LOCAL_SHARED_LIBRARIES += libdvm libandroid_runtime
+
LOCAL_C_INCLUDES := \
$(call include-path-for, corecg graphics)
diff --git a/services/surfaceflinger/DdmConnection.cpp b/services/surfaceflinger/DdmConnection.cpp
new file mode 100644
index 000000000000..467a915ed8b9
--- /dev/null
+++ b/services/surfaceflinger/DdmConnection.cpp
@@ -0,0 +1,75 @@
+/*
+ * 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.
+ */
+
+#include <android_runtime/AndroidRuntime.h>
+
+#include "jni.h"
+#include "DdmConnection.h"
+
+extern "C" jint Java_com_android_internal_util_WithFramework_registerNatives(
+ JNIEnv* env, jclass clazz);
+
+namespace android {
+
+void DdmConnection::start(const char* name) {
+ JavaVM* vm;
+ JNIEnv* env;
+
+ // start a VM
+ JavaVMInitArgs args;
+ JavaVMOption opt;
+
+ opt.optionString =
+ "-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y";
+
+ args.version = JNI_VERSION_1_4;
+ args.options = &opt;
+ args.nOptions = 1;
+ args.ignoreUnrecognized = JNI_FALSE;
+
+ if (JNI_CreateJavaVM(&vm, &env, &args) == 0) {
+ jclass startClass;
+ jmethodID startMeth;
+
+ // register native code
+ if (Java_com_android_internal_util_WithFramework_registerNatives(env, 0) == 0) {
+ // set our name by calling DdmHandleAppName.setAppName()
+ startClass = env->FindClass("android/ddm/DdmHandleAppName");
+ if (startClass) {
+ startMeth = env->GetStaticMethodID(startClass,
+ "setAppName", "(Ljava/lang/String;)V");
+ if (startMeth) {
+ jstring str = env->NewStringUTF(name);
+ env->CallStaticVoidMethod(startClass, startMeth, str);
+ env->DeleteLocalRef(str);
+ }
+ }
+
+ // initialize DDMS communication by calling
+ // DdmRegister.registerHandlers()
+ startClass = env->FindClass("android/ddm/DdmRegister");
+ if (startClass) {
+ startMeth = env->GetStaticMethodID(startClass,
+ "registerHandlers", "()V");
+ if (startMeth) {
+ env->CallStaticVoidMethod(startClass, startMeth);
+ }
+ }
+ }
+ }
+}
+
+}; // namespace android
diff --git a/services/surfaceflinger/DdmConnection.h b/services/surfaceflinger/DdmConnection.h
new file mode 100644
index 000000000000..91b737c92591
--- /dev/null
+++ b/services/surfaceflinger/DdmConnection.h
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_SF_DDM_CONNECTION
+#define ANDROID_SF_DDM_CONNECTION
+
+namespace android {
+
+class DdmConnection {
+public:
+ static void start(const char* name);
+};
+
+}; // namespace android
+
+#endif /* ANDROID_SF_DDM_CONNECTION */
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 082effe699f7..a68ab3055fe1 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -47,6 +47,7 @@
#include "clz.h"
#include "GLExtensions.h"
+#include "DdmConnection.h"
#include "Layer.h"
#include "LayerDim.h"
#include "SurfaceFlinger.h"
@@ -90,6 +91,7 @@ SurfaceFlinger::SurfaceFlinger()
mFreezeDisplayTime(0),
mDebugRegion(0),
mDebugBackground(0),
+ mDebugDDMS(0),
mDebugDisableHWC(0),
mDebugInSwapBuffers(0),
mLastSwapBufferTime(0),
@@ -108,13 +110,22 @@ void SurfaceFlinger::init()
// debugging stuff...
char value[PROPERTY_VALUE_MAX];
+
property_get("debug.sf.showupdates", value, "0");
mDebugRegion = atoi(value);
+
property_get("debug.sf.showbackground", value, "0");
mDebugBackground = atoi(value);
+ property_get("debug.sf.ddms", value, "0");
+ mDebugDDMS = atoi(value);
+ if (mDebugDDMS) {
+ DdmConnection::start(getServiceName());
+ }
+
LOGI_IF(mDebugRegion, "showupdates enabled");
LOGI_IF(mDebugBackground, "showbackground enabled");
+ LOGI_IF(mDebugDDMS, "DDMS debugging enabled");
}
SurfaceFlinger::~SurfaceFlinger()
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 6f93f5ba0ae5..89df0de55fd9 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -371,6 +371,7 @@ private:
// don't use a lock for these, we don't care
int mDebugRegion;
int mDebugBackground;
+ int mDebugDDMS;
int mDebugDisableHWC;
volatile nsecs_t mDebugInSwapBuffers;
nsecs_t mLastSwapBufferTime;
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/TextureViewActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/TextureViewActivity.java
index 97e21089428c..fcb57d96b3f1 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/TextureViewActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/TextureViewActivity.java
@@ -17,6 +17,7 @@
package com.android.test.hwui;
import android.app.Activity;
+import android.graphics.Matrix;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
@@ -33,6 +34,7 @@ public class TextureViewActivity extends Activity implements TextureView.Surface
private Camera mCamera;
private TextureView mTextureView;
private FrameLayout mContent;
+ private Matrix mMatrix = new Matrix();
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -82,8 +84,6 @@ public class TextureViewActivity extends Activity implements TextureView.Surface
}
mCamera.startPreview();
-
- mTextureView.setCameraDistance(5000);
}
@Override
diff --git a/wifi/java/android/net/wifi/WifiStateTracker.java b/wifi/java/android/net/wifi/WifiStateTracker.java
index 338cb4d0b466..c20c716a8686 100644
--- a/wifi/java/android/net/wifi/WifiStateTracker.java
+++ b/wifi/java/android/net/wifi/WifiStateTracker.java
@@ -27,6 +27,7 @@ import android.net.LinkCapabilities;
import android.net.NetworkInfo;
import android.net.LinkProperties;
import android.net.NetworkStateTracker;
+import android.net.wifi.p2p.WifiP2pManager;
import android.os.Handler;
import android.os.Message;
@@ -58,8 +59,8 @@ public class WifiStateTracker implements NetworkStateTracker {
private BroadcastReceiver mWifiStateReceiver;
private WifiManager mWifiManager;
- public WifiStateTracker() {
- mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, NETWORKTYPE, "");
+ public WifiStateTracker(int netType, String networkName) {
+ mNetworkInfo = new NetworkInfo(netType, 0, networkName, "");
mLinkProperties = new LinkProperties();
mLinkCapabilities = new LinkCapabilities();
@@ -87,6 +88,7 @@ public class WifiStateTracker implements NetworkStateTracker {
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
+ filter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mWifiStateReceiver = new WifiStateReceiver();
mContext.registerReceiver(mWifiStateReceiver, filter);
@@ -104,7 +106,6 @@ public class WifiStateTracker implements NetworkStateTracker {
/**
* Re-enable connectivity to a network after a {@link #teardown()}.
- * TODO: do away with return value after making MobileDataStateTracker async
*/
public boolean reconnect() {
mTeardownRequested.set(false);
@@ -115,7 +116,6 @@ public class WifiStateTracker implements NetworkStateTracker {
/**
* Turn the wireless radio off for a network.
* @param turnOn {@code true} to turn the radio on, {@code false}
- * TODO: do away with return value after making MobileDataStateTracker async
*/
public boolean setRadio(boolean turnOn) {
mWifiManager.setWifiEnabled(turnOn);
@@ -205,7 +205,21 @@ public class WifiStateTracker implements NetworkStateTracker {
private class WifiStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
- if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
+
+ if (intent.getAction().equals(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)) {
+ mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
+ WifiP2pManager.EXTRA_NETWORK_INFO);
+ mLinkProperties = intent.getParcelableExtra(
+ WifiP2pManager.EXTRA_LINK_PROPERTIES);
+ if (mLinkProperties == null) {
+ mLinkProperties = new LinkProperties();
+ }
+ mLinkCapabilities = intent.getParcelableExtra(
+ WifiP2pManager.EXTRA_LINK_CAPABILITIES);
+ if (mLinkCapabilities == null) {
+ mLinkCapabilities = new LinkCapabilities();
+ }
+ } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
WifiManager.EXTRA_NETWORK_INFO);
mLinkProperties = intent.getParcelableExtra(
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pManager.java b/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
index ea212accfd10..cc1f0628fbf5 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
@@ -19,13 +19,17 @@ package android.net.wifi.p2p;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.IConnectivityManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
+import android.os.ServiceManager;
import android.os.WorkSource;
import android.os.Messenger;
+import android.util.Log;
import com.android.internal.util.AsyncChannel;
import com.android.internal.util.Protocol;
@@ -98,6 +102,22 @@ public class WifiP2pManager {
public static final String EXTRA_NETWORK_INFO = "networkInfo";
/**
+ * The lookup key for a {@link android.net.LinkProperties} object associated with the
+ * network. Retrieve with
+ * {@link android.content.Intent#getParcelableExtra(String)}.
+ * @hide
+ */
+ public static final String EXTRA_LINK_PROPERTIES = "linkProperties";
+
+ /**
+ * The lookup key for a {@link android.net.LinkCapabilities} object associated with the
+ * network. Retrieve with
+ * {@link android.content.Intent#getParcelableExtra(String)}.
+ * @hide
+ */
+ public static final String EXTRA_LINK_CAPABILITIES = "linkCapabilities";
+
+ /**
* Broadcast intent action indicating that the available peer list has changed
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
@@ -115,9 +135,6 @@ public class WifiP2pManager {
IWifiP2pManager mService;
- /* For communication with WifiP2pService */
- private AsyncChannel mAsyncChannel = new AsyncChannel();
-
/* AsyncChannel notifications to apps */
public static final int HANDLER_CONNECTION = AsyncChannel.CMD_CHANNEL_HALF_CONNECTED;
public static final int HANDLER_DISCONNECTION = AsyncChannel.CMD_CHANNEL_DISCONNECTED;
@@ -194,18 +211,35 @@ public class WifiP2pManager {
}
/**
- * Registers the application handler with the Wi-Fi framework.
- * This function must be the first to be called before any p2p control
- * or query operations can be performed.
+ * A channel that connects the application handler to the Wifi framework.
+ * All p2p operations are performed on a channel.
+ */
+ public class Channel {
+ Channel(AsyncChannel c) {
+ mAsyncChannel = c;
+ }
+ AsyncChannel mAsyncChannel;
+ }
+
+ /**
+ * Registers the application handler with the Wi-Fi framework. This function
+ * must be the first to be called before any p2p control or query operations can be performed.
* @param srcContext is the context of the source
* @param srcHandler is the handler on which the source receives messages
- * @return {@code true} if the operation succeeded
+ * @return Channel instance that is necessary for performing p2p operations
*/
- public boolean connectHandler(Context srcContext, Handler srcHandler) {
+ public Channel initialize(Context srcContext, Handler srcHandler) {
Messenger messenger = getMessenger();
- if (messenger == null) return false;
- return mAsyncChannel.connectSync(srcContext, srcHandler, messenger)
- == AsyncChannel.STATUS_SUCCESSFUL;
+ if (messenger == null) return null;
+
+ AsyncChannel asyncChannel = new AsyncChannel();
+ Channel c = new Channel(asyncChannel);
+ if (asyncChannel.connectSync(srcContext, srcHandler, messenger)
+ == AsyncChannel.STATUS_SUCCESSFUL) {
+ return c;
+ } else {
+ return null;
+ }
}
public boolean isP2pSupported() {
@@ -220,16 +254,18 @@ public class WifiP2pManager {
* Sends in a request to the system to enable p2p. This will pop up a dialog
* to the user and upon authorization will enable p2p.
*/
- public void enableP2p() {
- mAsyncChannel.sendMessage(ENABLE_P2P);
+ public void enableP2p(Channel c) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(ENABLE_P2P);
}
/**
* Sends in a request to the system to disable p2p. This will pop up a dialog
* to the user and upon authorization will enable p2p.
*/
- public void disableP2p() {
- mAsyncChannel.sendMessage(DISABLE_P2P);
+ public void disableP2p(Channel c) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(DISABLE_P2P);
}
/**
@@ -238,29 +274,33 @@ public class WifiP2pManager {
* A dialog to the user is thrown to request his permission since it can
* have a significant impact on power consumption
*/
- public void setListenState(int timeout) {
- mAsyncChannel.sendMessage(START_LISTEN_MODE, timeout);
+ public void setListenState(Channel c, int timeout) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(START_LISTEN_MODE, timeout);
}
/**
* Initiates peer discovery
*/
- public void discoverPeers() {
- mAsyncChannel.sendMessage(DISCOVER_PEERS);
+ public void discoverPeers(Channel c) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(DISCOVER_PEERS);
}
/**
* Initiates peer discovery with a timeout
*/
- public void discoverPeers(int timeout) {
- mAsyncChannel.sendMessage(DISCOVER_PEERS, timeout);
+ public void discoverPeers(Channel c, int timeout) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(DISCOVER_PEERS, timeout);
}
/**
* Cancel any existing peer discovery operation
*/
- public void cancelPeerDiscovery() {
- mAsyncChannel.sendMessage(CANCEL_DISCOVER_PEERS);
+ public void cancelPeerDiscovery(Channel c) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(CANCEL_DISCOVER_PEERS);
}
/**
@@ -268,47 +308,53 @@ public class WifiP2pManager {
*
* @param peer Configuration described in a {@link WifiP2pConfig} object.
*/
- public void connect(WifiP2pConfig config) {
- mAsyncChannel.sendMessage(CONNECT, config);
+ public void connect(Channel c, WifiP2pConfig config) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(CONNECT, config);
}
/**
* Cancel any ongoing negotiation or disconnect from an existing group
*/
- public void disconnect() {
- mAsyncChannel.sendMessage(CANCEL_CONNECT);
+ public void disconnect(Channel c) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(CANCEL_CONNECT);
}
/**
* Create a p2p group. This is essentially an access point that can accept
* client connections.
*/
- public void createGroup() {
- mAsyncChannel.sendMessage(CREATE_GROUP);
+ public void createGroup(Channel c) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(CREATE_GROUP);
}
/**
* Remove the current group. This also removes the p2p interface created
* during group formation.
*/
- public void removeGroup() {
- mAsyncChannel.sendMessage(REMOVE_GROUP);
+ public void removeGroup(Channel c) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(REMOVE_GROUP);
}
/**
* Request current p2p settings. This returns a RESPONSE_SETTINGS on the source
* handler.
*/
- public void requestP2pSettings() {
- mAsyncChannel.sendMessage(REQUEST_SETTINGS);
+ public void requestP2pSettings(Channel c) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(REQUEST_SETTINGS);
}
/**
* Request the list of peers. This returns a RESPONSE_PEERS on the source
* handler.
*/
- public void requestPeers() {
- mAsyncChannel.sendMessage(REQUEST_PEERS);
+ public void requestPeers(Channel c) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(REQUEST_PEERS);
}
/**
@@ -322,8 +368,9 @@ public class WifiP2pManager {
* Request device connection status. This returns a RESPONSE_CONNECTION_STATUS on
* the source handler.
*/
- public void requestConnectionStatus() {
- mAsyncChannel.sendMessage(REQUEST_CONNECTION_STATUS);
+ public void requestConnectionStatus(Channel c) {
+ if (c == null) return;
+ c.mAsyncChannel.sendMessage(REQUEST_CONNECTION_STATUS);
}
@@ -341,4 +388,38 @@ public class WifiP2pManager {
return null;
}
}
+
+
+ /**
+ * Setup DNS connectivity on the current process to the connected Wi-Fi p2p peers
+ *
+ * @return -1 on failure
+ * @hide
+ */
+ public int startPeerCommunication() {
+ IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
+ IConnectivityManager cm = IConnectivityManager.Stub.asInterface(b);
+ try {
+ return cm.startUsingNetworkFeature(ConnectivityManager.TYPE_WIFI, "p2p", new Binder());
+ } catch (RemoteException e) {
+ return -1;
+ }
+ }
+
+ /**
+ * Tear down connectivity to the connected Wi-Fi p2p peers
+ *
+ * @return -1 on failure
+ * @hide
+ */
+ public int stopPeerCommunication() {
+ IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
+ IConnectivityManager cm = IConnectivityManager.Stub.asInterface(b);
+ try {
+ return cm.stopUsingNetworkFeature(ConnectivityManager.TYPE_WIFI, "p2p");
+ } catch (RemoteException e) {
+ return -1;
+ }
+ }
+
}
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pService.java b/wifi/java/android/net/wifi/p2p/WifiP2pService.java
index 3678cfc12f29..176191e7acc4 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pService.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pService.java
@@ -25,6 +25,15 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
+import android.net.IConnectivityManager;
+import android.net.ConnectivityManager;
+import android.net.DhcpInfoInternal;
+import android.net.DhcpStateMachine;
+import android.net.InterfaceConfiguration;
+import android.net.LinkAddress;
+import android.net.LinkProperties;
+import android.net.NetworkInfo;
+import android.net.NetworkUtils;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiMonitor;
import android.net.wifi.WifiNative;
@@ -47,16 +56,16 @@ import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.util.Collection;
-
import com.android.internal.R;
import com.android.internal.util.AsyncChannel;
import com.android.internal.util.Protocol;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.util.Collection;
+
/**
* WifiP2pService inclues a state machine to perform Wi-Fi p2p operations. Applications
* communicate with this service to issue device discovery and connectivity requests
@@ -70,14 +79,16 @@ import com.android.internal.util.StateMachine;
public class WifiP2pService extends IWifiP2pManager.Stub {
private static final String TAG = "WifiP2pService";
private static final boolean DBG = true;
+ private static final String NETWORKTYPE = "WIFI_P2P";
private Context mContext;
private String mInterface;
INetworkManagementService mNwService;
+ private DhcpStateMachine mDhcpStateMachine;
- // Tracked to notify the user about wifi client/hotspot being shut down
- // during p2p bring up
+ //Tracked to notify the user about wifi client/hotspot being shut down
+ //during p2p bring up
private int mWifiState = WifiManager.WIFI_STATE_DISABLED;
private int mWifiApState = WifiManager.WIFI_AP_STATE_DISABLED;
@@ -85,6 +96,9 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
private AsyncChannel mReplyChannel = new AsyncChannel();;
private AsyncChannel mWifiChannel;
+ private static final int GROUP_NEGOTIATION_WAIT_TIME_MS = 60 * 1000;
+ private static int mGroupNegotiationTimeoutIndex = 0;
+
private static final int BASE = Protocol.BASE_WIFI_P2P_SERVICE;
/* Message sent to WifiStateMachine to indicate p2p enable is pending */
@@ -92,15 +106,24 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
/* Message sent to WifiStateMachine to indicate Wi-Fi client/hotspot operation can proceed */
public static final int WIFI_ENABLE_PROCEED = BASE + 2;
+ /* Delayed message to timeout of group negotiation */
+ public static final int GROUP_NEGOTIATION_TIMED_OUT = BASE + 3;
+
/* User accepted to disable Wi-Fi in order to enable p2p */
private static final int WIFI_DISABLE_USER_ACCEPT = BASE + 11;
private final boolean mP2pSupported;
+ private NetworkInfo mNetworkInfo;
+ private LinkProperties mLinkProperties;
+
public WifiP2pService(Context context) {
mContext = context;
mInterface = SystemProperties.get("wifi.interface", "wlan0");
+ mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI_P2P, 0, NETWORKTYPE, "");
+ mLinkProperties = new LinkProperties();
+
mP2pSupported = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_wifi_p2p_support);
@@ -113,7 +136,7 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
mContext.registerReceiver(new WifiStateReceiver(), filter);
- }
+ }
public void connectivityServiceReady() {
IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
@@ -300,6 +323,7 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
break;
// Ignore
case WIFI_DISABLE_USER_ACCEPT:
+ case GROUP_NEGOTIATION_TIMED_OUT:
break;
default:
Slog.e(TAG, "Unhandled message " + message);
@@ -459,6 +483,10 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
WifiP2pManager.ENABLE_P2P_SUCCEEDED);
transitionTo(mInactiveState);
break;
+ case WifiP2pManager.DISABLE_P2P:
+ //TODO: fix
+ WifiNative.killSupplicant();
+ transitionTo(mP2pDisabledState);
default:
return NOT_HANDLED;
}
@@ -471,6 +499,7 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
public void enter() {
if (DBG) Slog.d(TAG, getName());
sendP2pStateChangedBroadcast(true);
+ mNetworkInfo.setIsAvailable(true);
}
@Override
@@ -526,6 +555,7 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
@Override
public void exit() {
sendP2pStateChangedBroadcast(false);
+ mNetworkInfo.setIsAvailable(false);
}
}
@@ -550,6 +580,8 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
WifiP2pGroup group = (WifiP2pGroup) message.obj;
notifyP2pInvitationReceived(group);
break;
+ case WifiP2pManager.REQUEST_PEERS:
+ return NOT_HANDLED;
default:
return NOT_HANDLED;
}
@@ -558,8 +590,11 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
}
class GroupNegotiationState extends State {
- @Override public void enter() {
+ @Override
+ public void enter() {
if (DBG) Slog.d(TAG, getName());
+ sendMessageDelayed(obtainMessage(GROUP_NEGOTIATION_TIMED_OUT,
+ ++mGroupNegotiationTimeoutIndex, 0), GROUP_NEGOTIATION_WAIT_TIME_MS);
}
@Override
@@ -582,18 +617,29 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
case WifiMonitor.P2P_GROUP_STARTED_EVENT:
mGroup = (WifiP2pGroup) message.obj;
if (DBG) Slog.d(TAG, getName() + " group started");
- // If this device is GO, do nothing since there is a follow up
- // AP_STA_CONNECTED event
- if (!mGroup.isGroupOwner()) {
+ if (mGroup.isGroupOwner()) {
+ startDhcpServer(mGroup.getInterface());
+ } else {
+ mDhcpStateMachine = DhcpStateMachine.makeDhcpStateMachine(mContext,
+ P2pStateMachine.this, mGroup.getInterface());
+ mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_START_DHCP);
WifiP2pDevice groupOwner = mGroup.getOwner();
updateDeviceStatus(groupOwner.deviceAddress, Status.CONNECTED);
sendP2pPeersChangedBroadcast();
}
transitionTo(mGroupCreatedState);
break;
- case WifiP2pManager.CANCEL_CONNECT:
+ case WifiP2pManager.CANCEL_CONNECT:
// TODO: fix
break;
+ case GROUP_NEGOTIATION_TIMED_OUT:
+ if (mGroupNegotiationTimeoutIndex == message.arg1) {
+ if (DBG) Slog.d(TAG, "Group negotiation timed out");
+ updateDeviceStatus(mSavedConnectConfig.deviceAddress, Status.FAILED);
+ mSavedConnectConfig = null;
+ transitionTo(mInactiveState);
+ }
+ break;
default:
return NOT_HANDLED;
}
@@ -605,6 +651,11 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
@Override
public void enter() {
if (DBG) Slog.d(TAG, getName());
+ mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null, null);
+
+ if (mGroup.isGroupOwner()) {
+ sendP2pConnectionChangedBroadcast();
+ }
}
@Override
@@ -638,7 +689,16 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
}
if (DBG) Slog.e(TAG, getName() + " ap sta disconnected");
break;
- // Disconnect & remove group have same effect when connected
+ case DhcpStateMachine.CMD_POST_DHCP_ACTION:
+ DhcpInfoInternal dhcpInfo = (DhcpInfoInternal) message.obj;
+ if (DBG) Slog.d(TAG, "DhcpInfo: " + dhcpInfo);
+ if (dhcpInfo != null) {
+ mLinkProperties = dhcpInfo.makeLinkProperties();
+ mLinkProperties.setInterfaceName(mGroup.getInterface());
+ sendP2pConnectionChangedBroadcast();
+ }
+ break;
+ //disconnect & remove group have same effect when connected
case WifiP2pManager.CANCEL_CONNECT:
case WifiP2pManager.REMOVE_GROUP:
if (DBG) Slog.e(TAG, getName() + " remove group");
@@ -655,6 +715,16 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
changed = true;
}
}
+
+ if (mGroup.isGroupOwner()) {
+ stopDhcpServer();
+ } else {
+ if (DBG) Slog.d(TAG, "stop DHCP client");
+ mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_STOP_DHCP);
+ mDhcpStateMachine.quit();
+ mDhcpStateMachine = null;
+ }
+
mGroup = null;
if (changed) sendP2pPeersChangedBroadcast();
transitionTo(mInactiveState);
@@ -663,10 +733,12 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
WifiP2pDevice device = (WifiP2pDevice) message.obj;
if (device.equals(mGroup.getOwner())) {
Slog.d(TAG, "Lost the group owner, killing p2p connection");
- sendMessage(WifiP2pManager.REMOVE_GROUP);
+ WifiNative.p2pFlush();
+ WifiNative.p2pGroupRemove(mGroup.getInterface());
} else if (mGroup.removeClient(device) && mGroup.isClientListEmpty()) {
Slog.d(TAG, "Client list empty, killing p2p connection");
- sendMessage(WifiP2pManager.REMOVE_GROUP);
+ WifiNative.p2pFlush();
+ WifiNative.p2pGroupRemove(mGroup.getInterface());
}
return NOT_HANDLED; // Do the regular device lost handling
case WifiP2pManager.DISABLE_P2P:
@@ -705,6 +777,10 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
}
return HANDLED;
}
+
+ public void exit() {
+ mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
+ }
}
private void sendP2pStateChangedBroadcast(boolean enabled) {
@@ -726,6 +802,55 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
mContext.sendBroadcast(intent);
}
+ private void sendP2pConnectionChangedBroadcast() {
+ if (DBG) Slog.d(TAG, "sending p2p connection changed broadcast");
+ Intent intent = new Intent(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
+ intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
+ | Intent.FLAG_RECEIVER_REPLACE_PENDING);
+ intent.putExtra(WifiP2pManager.EXTRA_NETWORK_INFO, new NetworkInfo(mNetworkInfo));
+ intent.putExtra(WifiP2pManager.EXTRA_LINK_PROPERTIES,
+ new LinkProperties (mLinkProperties));
+ mContext.sendStickyBroadcast(intent);
+ }
+
+ private void startDhcpServer(String intf) {
+ /* Is chosen as a unique range to avoid conflict with
+ the range defined in Tethering.java */
+ String[] dhcp_range = {"192.168.49.2", "192.168.49.254"};
+ String serverAddress = "192.168.49.1";
+
+ mLinkProperties.clear();
+ mLinkProperties.setInterfaceName(mGroup.getInterface());
+
+ InterfaceConfiguration ifcg = null;
+ try {
+ ifcg = mNwService.getInterfaceConfig(intf);
+ ifcg.addr = new LinkAddress(NetworkUtils.numericToInetAddress(
+ serverAddress), 24);
+ ifcg.interfaceFlags = "[up]";
+ mNwService.setInterfaceConfig(intf, ifcg);
+ /* This starts the dnsmasq server */
+ mNwService.startTethering(dhcp_range);
+ } catch (Exception e) {
+ Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
+ return;
+ }
+
+ mLinkProperties.addDns(NetworkUtils.numericToInetAddress(serverAddress));
+ Slog.d(TAG, "Started Dhcp server on " + intf);
+ }
+
+ private void stopDhcpServer() {
+ try {
+ mNwService.stopTethering();
+ } catch (Exception e) {
+ Slog.e(TAG, "Error stopping Dhcp server" + e);
+ return;
+ }
+
+ Slog.d(TAG, "Stopped Dhcp server");
+ }
+
private void notifyP2pEnableFailure() {
Resources r = Resources.getSystem();
AlertDialog dialog = new AlertDialog.Builder(mContext)
@@ -760,11 +885,16 @@ public class WifiP2pService extends IWifiP2pManager.Stub {
.setView(textEntryView)
.setPositiveButton(r.getString(R.string.ok), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
- if (DBG) Slog.d(TAG, getName() + " connect " + pin.getText());
+ if (DBG) Slog.d(TAG, getName() + " connect " + pin.getText());
+
+ if (pin.getVisibility() == View.GONE) {
+ mSavedGoNegotiationConfig.wpsConfig.setup = Setup.PBC;
+ } else {
mSavedGoNegotiationConfig.wpsConfig.setup = Setup.KEYPAD;
mSavedGoNegotiationConfig.wpsConfig.pin = pin.getText().toString();
- sendMessage(WifiP2pManager.CONNECT, mSavedGoNegotiationConfig);
- mSavedGoNegotiationConfig = null;
+ }
+ sendMessage(WifiP2pManager.CONNECT, mSavedGoNegotiationConfig);
+ mSavedGoNegotiationConfig = null;
}
})
.setNegativeButton(r.getString(R.string.cancel), new OnClickListener() {