code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.ch_linghu.fanfoudroid.task; public interface TaskListener { String getName(); void onPreExecute(GenericTask task); void onPostExecute(GenericTask task, TaskResult result); void onProgressUpdate(GenericTask task, Object param); void onCancelled(GenericTask task); }
Java
package com.ch_linghu.fanfoudroid.task; import java.util.Observable; import java.util.Observer; import android.util.Log; public class TaskManager extends Observable { private static final String TAG = "TaskManager"; public static final Integer CANCEL_ALL = 1; public void cancelAll() { Log.i(TAG, "All task Cancelled."); setChanged(); notifyObservers(CANCEL_ALL); } public void addTask(Observer task) { super.addObserver(task); } }
Java
package com.ch_linghu.fanfoudroid.task; import java.util.Observable; import java.util.Observer; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.ch_linghu.fanfoudroid.TwitterApplication; public abstract class GenericTask extends AsyncTask<TaskParams, Object, TaskResult> implements Observer { private static final String TAG = "TaskManager"; private TaskListener mListener = null; private boolean isCancelable = true; abstract protected TaskResult _doInBackground(TaskParams...params); public void setListener(TaskListener taskListener){ mListener = taskListener; } public TaskListener getListener(){ return mListener; } public void doPublishProgress(Object... values){ super.publishProgress(values); } @Override protected void onCancelled() { super.onCancelled(); if (mListener != null){ mListener.onCancelled(this); } Log.i(TAG, mListener.getName() + " has been Cancelled."); Toast.makeText(TwitterApplication.mContext, mListener.getName() + " has been cancelled", Toast.LENGTH_SHORT); } @Override protected void onPostExecute(TaskResult result) { super.onPostExecute(result); if (mListener != null){ mListener.onPostExecute(this, result); } Toast.makeText(TwitterApplication.mContext, mListener.getName() + " completed", Toast.LENGTH_SHORT); } @Override protected void onPreExecute() { super.onPreExecute(); if (mListener != null){ mListener.onPreExecute(this); } } @Override protected void onProgressUpdate(Object... values) { super.onProgressUpdate(values); if (mListener != null){ if (values != null && values.length > 0){ mListener.onProgressUpdate(this, values[0]); } } } @Override protected TaskResult doInBackground(TaskParams... params){ return _doInBackground(params); } public void update(Observable o, Object arg) { if (TaskManager.CANCEL_ALL == (Integer) arg && isCancelable) { if (getStatus() == GenericTask.Status.RUNNING) { cancel(true); } } } public void setCancelable(boolean flag) { isCancelable = flag; } }
Java
package com.ch_linghu.fanfoudroid.task; public abstract class TaskAdapter implements TaskListener { public abstract String getName(); public void onPreExecute(GenericTask task) {}; public void onPostExecute(GenericTask task, TaskResult result) {}; public void onProgressUpdate(GenericTask task, Object param) {}; public void onCancelled(GenericTask task) {}; }
Java
package com.ch_linghu.fanfoudroid.task; public enum TaskResult { OK, FAILED, CANCELLED, NOT_FOLLOWED_ERROR, IO_ERROR, AUTH_ERROR }
Java
/* Copyright (c) 2007-2009 All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.util.ArrayList; import org.apache.http.message.BasicNameValuePair; /** * A data class represents search query. */ public class Query { private String query = null; private String lang = null; private int rpp = -1; private int page = -1; private long sinceId = -1; private String maxId = null; private String geocode = null; public Query(){ } public Query(String query){ this.query = query; } public String getQuery() { return query; } /** * Sets the query string * @param query - the query string */ public void setQuery(String query) { this.query = query; } public String getLang() { return lang; } /** * restricts tweets to the given language, given by an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a> * @param lang an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a> */ public void setLang(String lang) { this.lang = lang; } public int getRpp() { return rpp; } /** * sets the number of tweets to return per page, up to a max of 100 * @param rpp the number of tweets to return per page */ public void setRpp(int rpp) { this.rpp = rpp; } public int getPage() { return page; } /** * sets the page number (starting at 1) to return, up to a max of roughly 1500 results * @param page - the page number (starting at 1) to return */ public void setPage(int page) { this.page = page; } public long getSinceId() { return sinceId; } /** * returns tweets with status ids greater than the given id. * @param sinceId - returns tweets with status ids greater than the given id */ public void setSinceId(long sinceId) { this.sinceId = sinceId; } public String getMaxId() { return maxId; } /** * returns tweets with status ids less than the given id. * @param maxId - returns tweets with status ids less than the given id */ public void setMaxId(String maxId) { this.maxId = maxId; } public String getGeocode() { return geocode; } public static final String MILES = "mi"; public static final String KILOMETERS = "km"; /** * returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Weibo profile * @param latitude latitude * @param longtitude longtitude * @param radius radius * @param unit Query.MILES or Query.KILOMETERS */ public void setGeoCode(double latitude, double longtitude, double radius , String unit) { this.geocode = latitude + "," + longtitude + "," + radius + unit; } public ArrayList<BasicNameValuePair> asPostParameters(){ ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); appendParameter("q", query, params); appendParameter("lang", lang, params); appendParameter("page", page, params); appendParameter("since_id",sinceId , params); appendParameter("max_id", maxId, params); appendParameter("geocode", geocode, params); return params; } private void appendParameter(String name, String value, ArrayList<BasicNameValuePair> params) { if (null != value) { params.add(new BasicNameValuePair(name, value)); } } private void appendParameter(String name, long value, ArrayList<BasicNameValuePair> params) { if (0 <= value) { params.add(new BasicNameValuePair(name, value + "")); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Query query1 = (Query) o; if (page != query1.page) return false; if (rpp != query1.rpp) return false; if (sinceId != query1.sinceId) return false; if (geocode != null ? !geocode.equals(query1.geocode) : query1.geocode != null) return false; if (lang != null ? !lang.equals(query1.lang) : query1.lang != null) return false; if (query != null ? !query.equals(query1.query) : query1.query != null) return false; return true; } @Override public int hashCode() { int result = query != null ? query.hashCode() : 0; result = 31 * result + (lang != null ? lang.hashCode() : 0); result = 31 * result + rpp; result = 31 * result + page; result = 31 * result + (int) (sinceId ^ (sinceId >>> 32)); result = 31 * result + (geocode != null ? geocode.hashCode() : 0); return result; } @Override public String toString() { return "Query{" + "query='" + query + '\'' + ", lang='" + lang + '\'' + ", rpp=" + rpp + ", page=" + page + ", sinceId=" + sinceId + ", geocode='" + geocode + '\'' + '}'; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import org.json.JSONException; import org.json.JSONObject; import com.ch_linghu.fanfoudroid.http.HttpException; /** * A data class representing Basic user information element */ public class Photo extends WeiboResponse implements java.io.Serializable { private Weibo weibo; private String thumbnail_pic; private String bmiddle_pic; private String original_pic; private boolean verified; private static final long serialVersionUID = -6345893237975349030L; public Photo(JSONObject json) throws HttpException { super(); init(json); } private void init(JSONObject json) throws HttpException { try { //System.out.println(json); thumbnail_pic = json.getString("thumburl"); bmiddle_pic = json.getString("imageurl"); original_pic = json.getString("largeurl"); } catch (JSONException jsone) { throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone); } } public String getThumbnail_pic() { return thumbnail_pic; } public void setThumbnail_pic(String thumbnail_pic) { this.thumbnail_pic = thumbnail_pic; } public String getBmiddle_pic() { return bmiddle_pic; } public void setBmiddle_pic(String bmiddle_pic) { this.bmiddle_pic = bmiddle_pic; } public String getOriginal_pic() { return original_pic; } public void setOriginal_pic(String original_pic) { this.original_pic = original_pic; } @Override public String toString() { return "Photo [thumbnail_pic=" + thumbnail_pic + ", bmiddle_pic=" + bmiddle_pic + ", original_pic=" + original_pic + "]"; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * A data class representing search API response * @author Yusuke Yamamoto - yusuke at mac.com */ public class QueryResult extends WeiboResponse { private long sinceId; private long maxId; private String refreshUrl; private int resultsPerPage; private int total = -1; private String warning; private double completedIn; private int page; private String query; private List<Status> tweets; private static final long serialVersionUID = -9059136565234613286L; /*package*/ QueryResult(Response res, WeiboSupport weiboSupport) throws HttpException { super(res); // 饭否search API直接返回 "[{JSONObejet},{JSONObejet},{JSONObejet}]"的JSONArray //System.out.println("TAG " + res.asString()); JSONArray array = res.asJSONArray(); try { tweets = new ArrayList<Status>(array.length()); for (int i = 0; i < array.length(); i++) { JSONObject tweet = array.getJSONObject(i); tweets.add(new Status(tweet)); } } catch (JSONException jsone) { throw new HttpException(jsone.getMessage() + ":" + array.toString(), jsone); } } /*package*/ QueryResult(Query query) throws HttpException { super(); sinceId = query.getSinceId(); resultsPerPage = query.getRpp(); page = query.getPage(); tweets = new ArrayList<Status>(0); } public long getSinceId() { return sinceId; } public long getMaxId() { return maxId; } public String getRefreshUrl() { return refreshUrl; } public int getResultsPerPage() { return resultsPerPage; } /** * returns the number of hits * @return number of hits * @deprecated The Weibo API doesn't return total anymore * @see <a href="http://yusuke.homeip.net/jira/browse/TFJ-108">TRJ-108 deprecate QueryResult#getTotal()</a> */ @Deprecated public int getTotal() { return total; } public String getWarning() { return warning; } public double getCompletedIn() { return completedIn; } public int getPage() { return page; } public String getQuery() { return query; } public List<Status> getStatus() { return tweets; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QueryResult that = (QueryResult) o; if (Double.compare(that.completedIn, completedIn) != 0) return false; if (maxId != that.maxId) return false; if (page != that.page) return false; if (resultsPerPage != that.resultsPerPage) return false; if (sinceId != that.sinceId) return false; if (total != that.total) return false; if (!query.equals(that.query)) return false; if (refreshUrl != null ? !refreshUrl.equals(that.refreshUrl) : that.refreshUrl != null) return false; if (tweets != null ? !tweets.equals(that.tweets) : that.tweets != null) return false; if (warning != null ? !warning.equals(that.warning) : that.warning != null) return false; return true; } @Override public int hashCode() { int result; long temp; result = (int) (sinceId ^ (sinceId >>> 32)); result = 31 * result + (int) (maxId ^ (maxId >>> 32)); result = 31 * result + (refreshUrl != null ? refreshUrl.hashCode() : 0); result = 31 * result + resultsPerPage; result = 31 * result + total; result = 31 * result + (warning != null ? warning.hashCode() : 0); temp = completedIn != +0.0d ? Double.doubleToLongBits(completedIn) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + page; result = 31 * result + query.hashCode(); result = 31 * result + (tweets != null ? tweets.hashCode() : 0); return result; } @Override public String toString() { return "QueryResult{" + "sinceId=" + sinceId + ", maxId=" + maxId + ", refreshUrl='" + refreshUrl + '\'' + ", resultsPerPage=" + resultsPerPage + ", total=" + total + ", warning='" + warning + '\'' + ", completedIn=" + completedIn + ", page=" + page + ", query='" + query + '\'' + ", tweets=" + tweets + '}'; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.io.IOException; import com.ch_linghu.fanfoudroid.http.HttpClient; /** * @author Yusuke Yamamoto - yusuke at mac.com */ /*protected*/ class WeiboSupport { protected HttpClient http = null; protected String source = Configuration.getSource(); protected final boolean USE_SSL; /*package*/ WeiboSupport(){ USE_SSL = Configuration.useSSL(); http = new HttpClient(); // In case that the user is not logged in } /*package*/ WeiboSupport(String userId, String password){ USE_SSL = Configuration.useSSL(); http = new HttpClient(userId, password); } /** * Returns authenticating userid * * @return userid */ public String getUserId() { return http.getUserId(); } /** * Returns authenticating password * * @return password */ public String getPassword() { return http.getPassword(); } //Low-level interface public HttpClient getHttpClient(){ return http; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import org.json.JSONException; import org.json.JSONObject; /** * A data class representing Treand. * * @author Yusuke Yamamoto - yusuke at mac.com * @since Weibo4J 2.0.2 */ public class Trend implements java.io.Serializable{ private String name; private String url = null; private String query = null; private static final long serialVersionUID = 1925956704460743946L; public Trend(JSONObject json) throws JSONException { this.name = json.getString("name"); if (!json.isNull("url")) { this.url = json.getString("url"); } if (!json.isNull("query")) { this.query = json.getString("query"); } } public String getName() { return name; } public String getUrl() { return url; } public String getQuery() { return query; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Trend)) return false; Trend trend = (Trend) o; if (!name.equals(trend.name)) return false; if (query != null ? !query.equals(trend.query) : trend.query != null) return false; if (url != null ? !url.equals(trend.url) : trend.url != null) return false; return true; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + (url != null ? url.hashCode() : 0); result = 31 * result + (query != null ? query.hashCode() : 0); return result; } @Override public String toString() { return "Trend{" + "name='" + name + '\'' + ", url='" + url + '\'' + ", query='" + query + '\'' + '}'; } }
Java
/* * UserObjectWapper.java created on 2010-7-28 上午08:48:35 by bwl (Liu Daoru) */ package com.ch_linghu.fanfoudroid.weibo; import java.io.Serializable; import java.util.List; /** * 对User对象列表进行的包装,以支持cursor相关信息传递 * @author liudaoru - daoru at sina.com.cn */ public class UserWapper implements Serializable { private static final long serialVersionUID = -3119107701303920284L; /** * 用户对象列表 */ private List<User> users; /** * 向前翻页的cursor */ private long previousCursor; /** * 向后翻页的cursor */ private long nextCursor; public UserWapper(List<User> users, long previousCursor, long nextCursor) { this.users = users; this.previousCursor = previousCursor; this.nextCursor = nextCursor; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public long getPreviousCursor() { return previousCursor; } public void setPreviousCursor(long previousCursor) { this.previousCursor = previousCursor; } public long getNextCursor() { return nextCursor; } public void setNextCursor(long nextCursor) { this.nextCursor = nextCursor; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.ch_linghu.fanfoudroid.http.HTMLEntity; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * Super class of Weibo Response objects. * * @see weibo4j.DirectMessage * @see weibo4j.Status * @see weibo4j.User * @author Yusuke Yamamoto - yusuke at mac.com */ public class WeiboResponse implements java.io.Serializable { private static Map<String,SimpleDateFormat> formatMap = new HashMap<String,SimpleDateFormat>(); private static final long serialVersionUID = 3519962197957449562L; private transient int rateLimitLimit = -1; private transient int rateLimitRemaining = -1; private transient long rateLimitReset = -1; public WeiboResponse() { } public WeiboResponse(Response res) { String limit = res.getResponseHeader("X-RateLimit-Limit"); if(null != limit){ rateLimitLimit = Integer.parseInt(limit); } String remaining = res.getResponseHeader("X-RateLimit-Remaining"); if(null != remaining){ rateLimitRemaining = Integer.parseInt(remaining); } String reset = res.getResponseHeader("X-RateLimit-Reset"); if(null != reset){ rateLimitReset = Long.parseLong(reset); } } protected static void ensureRootNodeNameIs(String rootName, Element elem) throws HttpException { if (!rootName.equals(elem.getNodeName())) { throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/."); } } protected static void ensureRootNodeNameIs(String[] rootNames, Element elem) throws HttpException { String actualRootName = elem.getNodeName(); for (String rootName : rootNames) { if (rootName.equals(actualRootName)) { return; } } String expected = ""; for (int i = 0; i < rootNames.length; i++) { if (i != 0) { expected += " or "; } expected += rootNames[i]; } throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + expected + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/."); } protected static void ensureRootNodeNameIs(String rootName, Document doc) throws HttpException { Element elem = doc.getDocumentElement(); if (!rootName.equals(elem.getNodeName())) { throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/"); } } protected static boolean isRootNodeNilClasses(Document doc) { String root = doc.getDocumentElement().getNodeName(); return "nil-classes".equals(root) || "nilclasses".equals(root); } protected static String getChildText( String str, Element elem ) { return HTMLEntity.unescape(getTextContent(str,elem)); } protected static String getTextContent(String str, Element elem){ NodeList nodelist = elem.getElementsByTagName(str); if (nodelist.getLength() > 0) { Node node = nodelist.item(0).getFirstChild(); if (null != node) { String nodeValue = node.getNodeValue(); return null != nodeValue ? nodeValue : ""; } } return ""; } /*modify by sycheng add "".equals(str) */ protected static int getChildInt(String str, Element elem) { String str2 = getTextContent(str, elem); if (null == str2 || "".equals(str2)||"null".equals(str)) { return -1; } else { return Integer.valueOf(str2); } } /*modify by sycheng add "".equals(str) */ protected static String getChildString(String str, Element elem) { String str2 = getTextContent(str, elem); if (null == str2 || "".equals(str2)||"null".equals(str)) { return ""; } else { return String.valueOf(str2); } } protected static long getChildLong(String str, Element elem) { String str2 = getTextContent(str, elem); if (null == str2 || "".equals(str2)||"null".equals(str)) { return -1; } else { return Long.valueOf(str2); } } protected static String getString(String name, JSONObject json, boolean decode) { String returnValue = null; try { returnValue = json.getString(name); if (decode) { try { returnValue = URLDecoder.decode(returnValue, "UTF-8"); } catch (UnsupportedEncodingException ignore) { } } } catch (JSONException ignore) { // refresh_url could be missing } return returnValue; } protected static boolean getChildBoolean(String str, Element elem) { String value = getTextContent(str, elem); return Boolean.valueOf(value); } protected static Date getChildDate(String str, Element elem) throws HttpException { return getChildDate(str, elem, "EEE MMM d HH:mm:ss z yyyy"); } protected static Date getChildDate(String str, Element elem, String format) throws HttpException { return parseDate(getChildText(str, elem),format); } protected static Date parseDate(String str, String format) throws HttpException{ if(str==null||"".equals(str)){ return null; } SimpleDateFormat sdf = formatMap.get(format); if (null == sdf) { sdf = new SimpleDateFormat(format, Locale.ENGLISH); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); formatMap.put(format, sdf); } try { synchronized(sdf){ // SimpleDateFormat is not thread safe return sdf.parse(str); } } catch (ParseException pe) { throw new HttpException("Unexpected format(" + str + ") returned from sina.com.cn"); } } protected static int getInt(String key, JSONObject json) throws JSONException { String str = json.getString(key); if(null == str || "".equals(str)||"null".equals(str)){ return -1; } return Integer.parseInt(str); } protected static String getString(String key, JSONObject json) throws JSONException { String str = json.getString(key); if(null == str || "".equals(str)||"null".equals(str)){ return ""; } return String.valueOf(str); } protected static long getLong(String key, JSONObject json) throws JSONException { String str = json.getString(key); if(null == str || "".equals(str)||"null".equals(str)){ return -1; } return Long.parseLong(str); } protected static boolean getBoolean(String key, JSONObject json) throws JSONException { String str = json.getString(key); if(null == str || "".equals(str)||"null".equals(str)){ return false; } return Boolean.valueOf(str); } public int getRateLimitLimit() { return rateLimitLimit; } public int getRateLimitRemaining() { return rateLimitRemaining; } public long getRateLimitReset() { return rateLimitReset; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import android.util.Log; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpClient; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; public class Weibo extends WeiboSupport implements java.io.Serializable { public static final String TAG = "Weibo_API"; public static final String CONSUMER_KEY = Configuration.getSource(); public static final String CONSUMER_SECRET = ""; private String baseURL = Configuration.getScheme() + "api.fanfou.com/"; private String searchBaseURL = Configuration.getScheme() + "api.fanfou.com/"; private static final long serialVersionUID = -1486360080128882436L; public Weibo() { super(); // In case that the user is not logged in format.setTimeZone(TimeZone.getTimeZone("GMT")); } public Weibo(String userId, String password) { super(userId, password); format.setTimeZone(TimeZone.getTimeZone("GMT")); } public Weibo(String userId, String password, String baseURL) { this(userId, password); this.baseURL = baseURL; } /** * 设置HttpClient的Auth,为请求做准备 * @param username * @param password */ public void setCredentials(String username, String password) { http.setCredentials(username, password); } /** * 仅判断是否为空 * @param username * @param password * @return */ public static boolean isValidCredentials(String username, String password) { return !Utils.isEmpty(username) && !Utils.isEmpty(password); } /** * 在服务器上验证用户名/密码是否正确,成功则返回该用户信息,失败则抛出异常。 * @param username * @param password * @return Verified User * @throws HttpException 验证失败及其他非200响应均抛出异常 */ public User login(String username, String password) throws HttpException { Log.i(TAG, "Login attempt for " + username); http.setCredentials(username, password); // Verify userName and password on the server. User user = verifyCredentials(); if (null != user && user.getId().length() > 0) { } return user; } /** * Reset HttpClient's Credentials */ public void reset() { http.reset(); } /** * Whether Logged-in * @return */ public boolean isLoggedIn() { // HttpClient的userName&password是由TwitterApplication#onCreate // 从SharedPreferences中取出的,他们为空则表示尚未登录,因为他们只在验证 // 账户成功后才会被储存,且注销时被清空。 return isValidCredentials(http.getUserId(), http.getPassword()); } /** * Sets the base URL * * @param baseURL String the base URL */ public void setBaseURL(String baseURL) { this.baseURL = baseURL; } /** * Returns the base URL * * @return the base URL */ public String getBaseURL() { return this.baseURL; } /** * Sets the search base URL * * @param searchBaseURL the search base URL * @since fanfoudroid 0.5.0 */ public void setSearchBaseURL(String searchBaseURL) { this.searchBaseURL = searchBaseURL; } /** * Returns the search base url * @return search base url * @since fanfoudroid 0.5.0 */ public String getSearchBaseURL(){ return this.searchBaseURL; } /** * Returns authenticating userid * 注意:此userId不一定等同与饭否用户的user_id参数 * 它可能是任意一种当前用户所使用的ID类型(如邮箱,用户名等), * * @return userid */ public String getUserId() { return http.getUserId(); } /** * Returns authenticating password * * @return password */ public String getPassword() { return http.getPassword(); } /** * Issues an HTTP GET request. * * @param url the request url * @param authenticate if true, the request will be sent with BASIC authentication header * @return the response * @throws HttpException */ protected Response get(String url, boolean authenticate) throws HttpException { return get(url, null, authenticate); } /** * Issues an HTTP GET request. * * @param url the request url * @param authenticate if true, the request will be sent with BASIC authentication header * @param name1 the name of the first parameter * @param value1 the value of the first parameter * @return the response * @throws HttpException */ protected Response get(String url, String name1, String value1, boolean authenticate) throws HttpException { ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add( new BasicNameValuePair(name1, HttpClient.encode(value1) ) ); return get(url, params, authenticate); } /** * Issues an HTTP GET request. * * @param url the request url * @param name1 the name of the first parameter * @param value1 the value of the first parameter * @param name2 the name of the second parameter * @param value2 the value of the second parameter * @param authenticate if true, the request will be sent with BASIC authentication header * @return the response * @throws HttpException */ protected Response get(String url, String name1, String value1, String name2, String value2, boolean authenticate) throws HttpException { ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair(name1, HttpClient.encode(value1))); params.add(new BasicNameValuePair(name2, HttpClient.encode(value2))); return get(url, params, authenticate); } /** * Issues an HTTP GET request. * * @param url the request url * @param params the request parameters * @param authenticate if true, the request will be sent with BASIC authentication header * @return the response * @throws HttpException */ protected Response get(String url, ArrayList<BasicNameValuePair> params, boolean authenticated) throws HttpException { if (url.indexOf("?") == -1) { url += "?source=" + CONSUMER_KEY; } else if (url.indexOf("source") == -1) { url += "&source=" + CONSUMER_KEY; } //以HTML格式获得数据,以便进一步处理 url += "&format=html"; if (null != params && params.size() > 0) { url += "&" + HttpClient.encodeParameters(params); } return http.get(url, authenticated); } /** * Issues an HTTP GET request. * * @param url the request url * @param params the request parameters * @param paging controls pagination * @param authenticate if true, the request will be sent with BASIC authentication header * @return the response * @throws HttpException */ protected Response get(String url, ArrayList<BasicNameValuePair> params, Paging paging, boolean authenticate) throws HttpException { if (null == params) { params = new ArrayList<BasicNameValuePair>(); } if (null != paging) { if ("" != paging.getMaxId()) { params.add(new BasicNameValuePair("max_id", String.valueOf(paging.getMaxId()))); } if ("" != paging.getSinceId()) { params.add(new BasicNameValuePair("since_id", String.valueOf(paging.getSinceId()))); } if (-1 != paging.getPage()) { params.add(new BasicNameValuePair("page", String.valueOf(paging.getPage()))); } if (-1 != paging.getCount()) { params.add(new BasicNameValuePair("count", String.valueOf(paging.getCount()))); } return get(url, params, authenticate); } else { return get(url, params, authenticate); } } /** * 生成POST Parameters助手 * @param nameValuePair 参数(一个或多个) * @return post parameters */ public ArrayList<BasicNameValuePair> createParams(BasicNameValuePair... nameValuePair ) { ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); for (BasicNameValuePair param : nameValuePair) { params.add(param); } return params; } /***************** API METHOD START *********************/ /* 搜索相关的方法 */ /** * Returns tweets that match a specified query. * <br>This method calls http://api.fanfou.com/users/search.format * @param query - the search condition * @return the result * @throws HttpException * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public QueryResult search(Query query) throws HttpException { try{ return new QueryResult(get(searchBaseURL + "search/public_timeline.json", query.asPostParameters(), false), this); }catch(HttpException te){ if(404 == te.getStatusCode()){ return new QueryResult(query); }else{ throw te; } } } /** * Returns the top ten topics that are currently trending on Weibo. The response includes the time of the request, the name of each trend. * @return the result * @throws HttpException * @since fanfoudroid 0.5.0 */ public Trends getTrends() throws HttpException { return Trends.constructTrends(get(searchBaseURL + "trends.json", false)); } private String toDateStr(Date date){ if(null == date){ date = new Date(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(date); } /* 消息相关的方法 */ /** * Returns the 20 most recent statuses from non-protected users who have set a custom user icon. * <br>This method calls http://api.fanfou.com/statuses/public_timeline.format * * @return list of statuses of the Public Timeline * @throws HttpException * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<Status> getPublicTimeline() throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/public_timeline.json", true)); } public RateLimitStatus getRateLimitStatus()throws HttpException { return new RateLimitStatus(get(getBaseURL() + "account/rate_limit_status.json", true),this); } /** * Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web. * <br>This method calls http://api.fanfou.com/statuses/home_timeline.format * * @return list of the home Timeline * @throws HttpException * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public List<Status> getHomeTimeline() throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/home_timeline.json", true)); } /** * Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web. * <br>This method calls http://api.fanfou.com/statuses/home_timeline.format * * @param paging controls pagination * @return list of the home Timeline * @throws HttpException * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public List<Status> getHomeTimeline(Paging paging) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/home_timeline.json", null, paging, true)); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating1 user and that user's friends. * It's also possible to request another user's friends_timeline via the id parameter below. * <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format * * @return list of the Friends Timeline * @throws HttpException * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<Status> getFriendsTimeline() throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json", true)); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the specified userid. * <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format * * @param paging controls pagination * @return list of the Friends Timeline * @throws HttpException * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<Status> getFriendsTimeline(Paging paging) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json",null, paging, true)); } /** * Returns friend time line by page and count. * <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format * @param page * @param count * @return * @throws HttpException */ public List<Status> getFriendsTimeline(int page, int count) throws HttpException { Paging paging = new Paging(page, count); return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json",null, paging, true)); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * <br>This method calls http://api.fanfou.com/statuses/user_timeline.format * * @param id specifies the ID or screen name of the user for whom to return the user_timeline * @param paging controls pagenation * @return list of the user Timeline * @throws HttpException * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<Status> getUserTimeline(String id, Paging paging) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline/" + id + ".xml", null, paging, http.isAuthenticationEnabled()), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * <br>This method calls http://api.fanfou.com/statuses/user_timeline.format * * @param id specifies the ID or screen name of the user for whom to return the user_timeline * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws HttpException * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<Status> getUserTimeline(String id) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline/" + id + ".json", http.isAuthenticationEnabled())); } /** * Returns the most recent statuses posted in the last 24 hours from the authenticating user. * <br>This method calls http://api.fanfou.com/statuses/user_timeline.format * * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws HttpException * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<Status> getUserTimeline() throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json" , true)); } /** * Returns the most recent statuses posted in the last 24 hours from the authenticating user. * <br>This method calls http://api.fanfou.com/statuses/user_timeline.format * * @param paging controls pagination * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws HttpException * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public List<Status> getUserTimeline(Paging paging) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json" , null, paging, true)); } public List<Status> getUserTimeline(int page, int count) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json" , null, new Paging(page, count), true)); } /** * Returns the 20 most recent mentions (status containing @username) for the authenticating user. * <br>This method calls http://api.fanfou.com/statuses/mentions.format * * @return the 20 most recent replies * @throws HttpException * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<Status> getMentions() throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json", null, true)); } // by since_id public List<Status> getMentions(String since_id) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json", "since_id", String.valueOf(since_id), true)); } /** * Returns the 20 most recent mentions (status containing @username) for the authenticating user. * <br>This method calls http://api.fanfou.com/statuses/mentions.format * * @param paging controls pagination * @return the 20 most recent replies * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<Status> getMentions(Paging paging) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json", null, paging, true)); } /** * Returns a single status, specified by the id parameter. The status's author will be returned inline. * <br>This method calls http://api.fanfou.com/statuses/show/id.format * * @param id the numerical ID of the status you're trying to retrieve * @return a single status * @throws HttpException when Weibo service or network is unavailable. 可能因为“你没有通过这个用户的验证“,返回403 * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public Status showStatus(String id) throws HttpException { return new Status(get(getBaseURL() + "statuses/show/" + id + ".json", true)); } /** * Updates the user's status. * The text will be trimed if the length of the text is exceeding 160 characters. * <br>This method calls http://api.fanfou.com/statuses/update.format * * @param status the text of your status update * @return the latest status * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public Status updateStatus(String status) throws HttpException{ return new Status(http.post(getBaseURL() + "statuses/update.json", createParams(new BasicNameValuePair("status", status), new BasicNameValuePair("source", source)))); } /** * Updates the user's status. * The text will be trimed if the length of the text is exceeding 160 characters. * <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml] * * @param status the text of your status update * @param latitude The location's latitude that this tweet refers to. * @param longitude The location's longitude that this tweet refers to. * @return the latest status * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public Status updateStatus(String status, double latitude, double longitude) throws HttpException, JSONException { return new Status(http.post(getBaseURL() + "statuses/update.json", createParams(new BasicNameValuePair("status", status), new BasicNameValuePair("source", source), new BasicNameValuePair("location", latitude + "," + longitude)))); } /** * Updates the user's status. * 如果要使用inreplyToStatusId参数, 那么该status就必须得是@别人的. * The text will be trimed if the length of the text is exceeding 160 characters. * <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml] * * @param status the text of your status update * @param inReplyToStatusId The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored. * @return the latest status * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public Status updateStatus(String status, String inReplyToStatusId) throws HttpException { return new Status(http.post(getBaseURL() + "statuses/update.json", createParams(new BasicNameValuePair("status", status), new BasicNameValuePair("source", source), new BasicNameValuePair("in_reply_to_status_id", inReplyToStatusId)))); } /** * Updates the user's status. * The text will be trimed if the length of the text is exceeding 160 characters. * <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml] * * @param status the text of your status update * @param inReplyToStatusId The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored. * @param latitude The location's latitude that this tweet refers to. * @param longitude The location's longitude that this tweet refers to. * @return the latest status * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public Status updateStatus(String status, String inReplyToStatusId , double latitude, double longitude) throws HttpException { return new Status(http.post(getBaseURL() + "statuses/update.json", createParams(new BasicNameValuePair("status", status), new BasicNameValuePair("source", source), new BasicNameValuePair("location", latitude + "," + longitude), new BasicNameValuePair("in_reply_to_status_id", inReplyToStatusId)))); } /** * upload the photo. * The text will be trimed if the length of the text is exceeding 160 characters. * The image suport. * <br>上传照片 http://api.fanfou.com/photos/upload.[json|xml] * * @param status the text of your status update * @return the latest status * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public Status uploadPhoto(String status, File file) throws HttpException { return new Status(http.httpRequest(getBaseURL() + "photos/upload.json", createParams(new BasicNameValuePair("status", status), new BasicNameValuePair("source", source)), file, true, HttpPost.METHOD_NAME)); } public Status updateStatus(String status, File file) throws HttpException { return uploadPhoto(status, file); } /** * Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status. * <br>删除消息 http://api.fanfou.com/statuses/destroy.[json|xml] * * @param statusId The ID of the status to destroy. * @return the deleted status * @throws HttpException when Weibo service or network is unavailable * @since 1.0.5 */ public Status destroyStatus(String statusId) throws HttpException { return new Status(http.post(getBaseURL() + "statuses/destroy/" + statusId + ".json", createParams(), true)); } /** * Returns extended information of a given user, specified by ID or screen name as per the required id parameter below. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences. * <br>This method calls http://api.fanfou.com/users/show.format * * @param id (cann't be screenName the ID of the user for whom to request the detail * @return User * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public User showUser(String id) throws HttpException { return new User(get(getBaseURL() + "users/show.json", createParams(new BasicNameValuePair("id", id)), true)); } /** * Return a status of repost * @param to_user_name repost status's user name * @param repost_status_id repost status id * @param repost_status_text repost status text * @param new_status the new status text * @return a single status * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public Status repost(String to_user_name, String repost_status_id, String repost_status_text, String new_status) throws HttpException { StringBuilder sb = new StringBuilder(); sb.append(new_status); sb.append(" "); sb.append(R.string.pref_rt_prefix_default + ":@"); sb.append(to_user_name); sb.append(" "); sb.append(repost_status_text); sb.append(" "); String message = sb.toString(); return new Status(http.post(getBaseURL() + "statuses/update.json", createParams(new BasicNameValuePair("status", message), new BasicNameValuePair("repost_status_id", repost_status_id)), true)); } /** * Return a status of repost * @param to_user_name repost status's user name * @param repost_status_id repost status id * @param repost_status_text repost status text * @param new_status the new status text * @return a single status * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public Status repost(String new_status, String repost_status_id) throws HttpException { return new Status(http.post(getBaseURL() + "statuses/update.json", createParams(new BasicNameValuePair("status", new_status), new BasicNameValuePair("source", CONSUMER_KEY), new BasicNameValuePair("repost_status_id", repost_status_id)), true)); } /** * Return a status of repost * @param repost_status_id repost status id * @param repost_status_text repost status text * @return a single status * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public Status repost(String repost_status_id, String new_status, boolean tmp) throws HttpException { Status repost_to = showStatus(repost_status_id); String to_user_name = repost_to.getUser().getName(); String repost_status_text = repost_to.getText(); return repost(to_user_name, repost_status_id, repost_status_text, new_status); } /* User Methods */ /** * Returns the specified user's friends, each with current status inline. * <br>This method calls http://api.fanfou.com/statuses/friends.format * * @return the list of friends * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public List<User> getFriendsStatuses() throws HttpException { return User.constructResult(get(getBaseURL() + "users/friends.json", true)); } /** * Returns the specified user's friends, each with current status inline. * <br>This method calls http://api.fanfou.com/statuses/friends.format * <br>分页每页显示100条 * * @param paging controls pagination * @return the list of friends * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * */ public List<User> getFriendsStatuses(Paging paging) throws HttpException { return User.constructUsers(get(getBaseURL() + "users/friends.json", null, paging, true)); } /** * Returns the user's friends, each with current status inline. * <br>This method calls http://api.fanfou.com/statuses/friends.format * * @param id the ID or screen name of the user for whom to request a list of friends * @return the list of friends * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public List<User> getFriendsStatuses(String id) throws HttpException { return User.constructUsers(get(getBaseURL() + "users/friends.json", createParams(new BasicNameValuePair("id", id)), false)); } /** * Returns the user's friends, each with current status inline. * <br>This method calls http://api.fanfou.com/statuses/friends.format * * @param id the ID or screen name of the user for whom to request a list of friends * @param paging controls pagination (饭否API 默认返回 100 条/页) * @return the list of friends * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<User> getFriendsStatuses(String id, Paging paging) throws HttpException { return User.constructUsers(get(getBaseURL() + "users/friends.json", createParams(new BasicNameValuePair("id", id)), paging, false)); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed). * <br>This method calls http://api.fanfou.com/statuses/followers.format * * @return List * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public List<User> getFollowersStatuses() throws HttpException { return User.constructResult(get(getBaseURL() + "statuses/followers.json", true)); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed). * <br>This method calls http://api.fanfou.com/statuses/followers.format * * @param paging controls pagination * @return List * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<User> getFollowersStatuses(Paging paging) throws HttpException { return User.constructUsers(get(getBaseURL() + "statuses/followers.json", null , paging, true)); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed). * <br>This method calls http://api.fanfou.com/statuses/followers.format * * @param id The ID (not screen name) of the user for whom to request a list of followers. * @return List * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<User> getFollowersStatuses(String id) throws HttpException { return User.constructUsers(get(getBaseURL() + "statuses/followers/" + id + ".json", true)); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed). * <br>This method calls http://api.fanfou.com/statuses/followers.format * * @param id The ID or screen name of the user for whom to request a list of followers. * @param paging controls pagination * @return List * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<User> getFollowersStatuses(String id, Paging paging) throws HttpException { return User.constructUsers(get(getBaseURL() + "statuses/followers/" + id + ".json", null, paging, true)); } /* 私信功能 */ /** * Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below. * The text will be trimed if the length of the text is exceeding 140 characters. * <br>This method calls http://api.fanfou.com/direct_messages/new.format * <br>通过客户端只能给互相关注的人发私信 * * @param id the ID of the user to whom send the direct message * @param text String * @return DirectMessage * @throws HttpException when Weibo service or network is unavailable @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public DirectMessage sendDirectMessage(String id, String text) throws HttpException { return new DirectMessage(http.post(getBaseURL() + "direct_messages/new.json", createParams(new BasicNameValuePair("user", id), new BasicNameValuePair("text", text))).asJSONObject()); } //TODO: need be unit tested by in_reply_to_id. /** * Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below. * The text will be trimed if the length of the text is exceeding 140 characters. * <br>通过客户端只能给互相关注的人发私信 * * @param id * @param text * @param in_reply_to_id * @return * @throws HttpException */ public DirectMessage sendDirectMessage(String id, String text, String in_reply_to_id) throws HttpException { return new DirectMessage(http.post(getBaseURL() + "direct_messages/new.json", createParams(new BasicNameValuePair("user", id), new BasicNameValuePair("text", text), new BasicNameValuePair("is_reply_to_id", in_reply_to_id))).asJSONObject()); } /** * Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message. * <br>This method calls http://api.fanfou.com/direct_messages/destroy/id.format * * @param id the ID of the direct message to destroy * @return the deleted direct message * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public DirectMessage destroyDirectMessage(String id) throws HttpException { return new DirectMessage(http.post(getBaseURL() + "direct_messages/destroy/" + id + ".json", true).asJSONObject()); } /** * Returns a list of the direct messages sent to the authenticating user. * <br>This method calls http://api.fanfou.com/direct_messages.format * * @return List * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<DirectMessage> getDirectMessages() throws HttpException { return DirectMessage.constructDirectMessages(get(getBaseURL() + "direct_messages.json", true)); } /** * Returns a list of the direct messages sent to the authenticating user. * <br>This method calls http://api.fanfou.com/direct_messages.format * * @param paging controls pagination * @return List * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<DirectMessage> getDirectMessages(Paging paging) throws HttpException { return DirectMessage.constructDirectMessages(get(getBaseURL() + "direct_messages.json", null, paging, true)); } /** * Returns a list of the direct messages sent by the authenticating user. * <br>This method calls http://api.fanfou.com/direct_messages/sent.format * * @return List * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<DirectMessage> getSentDirectMessages() throws HttpException { return DirectMessage.constructDirectMessages(get(getBaseURL() + "direct_messages/sent.json", null, true)); } /** * Returns a list of the direct messages sent by the authenticating user. * <br>This method calls http://api.fanfou.com/direct_messages/sent.format * * @param paging controls pagination * @return List 默认返回20条, 一次最多返回60条 * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<DirectMessage> getSentDirectMessages(Paging paging) throws HttpException { return DirectMessage.constructDirectMessages(get(getBaseURL() + "direct_messages/sent.json", null, paging, true)); } /* 收藏功能 */ /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * @return List<Status> * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public List<Status> getFavorites() throws HttpException { return Status.constructStatuses(get(getBaseURL() + "favorites.json", createParams(), true)); } public List<Status> getFavorites(Paging paging) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "favorites.json", createParams(), paging, true)); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @param page the number of page * @return List<Status> * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public List<Status> getFavorites(int page) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "favorites.json", "page", String.valueOf(page), true)); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @param id the ID or screen name of the user for whom to request a list of favorite statuses * @return List<Status> * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> * @since fanfoudroid 0.5.0 */ public List<Status> getFavorites(String id) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", createParams(), true)); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @param id the ID or screen name of the user for whom to request a list of favorite statuses * @param page the number of page * @return List<Status> * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public List<Status> getFavorites(String id, int page) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", "page", String.valueOf(page), true)); } public List<Status> getFavorites(String id, Paging paging) throws HttpException { return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", null, paging, true)); } /** * Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful. * * @param id the ID of the status to favorite * @return Status * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public Status createFavorite(String id) throws HttpException { return new Status(http.post(getBaseURL() + "favorites/create/" + id + ".json", true)); } /** * Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. * * @param id the ID of the status to un-favorite * @return Status * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public Status destroyFavorite(String id) throws HttpException { return new Status(http.post(getBaseURL() + "favorites/destroy/" + id + ".json", true)); } /** * Enables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful. * @param id String * @return User * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @deprecated 饭否该功能暂时关闭, 等待该功能开放. */ public User enableNotification(String id) throws HttpException { return new User(http.post(getBaseURL() + "notifications/follow/" + id + ".json", true).asJSONObject()); } /** * Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful. * @param id String * @return User * @throws HttpException when Weibo service or network is unavailable * @deprecated 饭否该功能暂时关闭, 等待该功能开放. * @since fanfoudroid 0.5.0 */ public User disableNotification(String id) throws HttpException { return new User(http.post(getBaseURL() + "notifications/leave/" + id + ".json", true).asJSONObject()); } /* 黑名单 */ /** * Blocks the user specified in the ID parameter as the authenticating user. Returns the blocked user in the requested format when successful. * @param id the ID or screen_name of the user to block * @return the blocked user * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public User createBlock(String id) throws HttpException { return new User(http.post(getBaseURL() + "blocks/create/" + id + ".json", true).asJSONObject()); } /** * Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful. * @param id the ID or screen_name of the user to block * @return the unblocked user * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public User destroyBlock(String id) throws HttpException { return new User(http.post(getBaseURL() + "blocks/destroy/" + id + ".json", true).asJSONObject()); } /** * Tests if a friendship exists between two users. * @param id The ID or screen_name of the potentially blocked user. * @return if the authenticating user is blocking a target user * @throws HttpException when Weibo service or network is unavailable * @deprecated 饭否暂无此功能, 期待此功能 * @since fanfoudroid 0.5.0 */ public boolean existsBlock(String id) throws HttpException { try{ return -1 == get(getBaseURL() + "blocks/exists/" + id + ".json", true). asString().indexOf("<error>You are not blocking this user.</error>"); }catch(HttpException te){ if(te.getStatusCode() == 404){ return false; } throw te; } } /** * Returns a list of user objects that the authenticating user is blocking. * @return a list of user objects that the authenticating user * @throws HttpException when Weibo service or network is unavailable * @deprecated 饭否暂无此功能, 期待此功能 * @since fanfoudroid 0.5.0 */ public List<User> getBlockingUsers() throws HttpException { return User.constructUsers(get(getBaseURL() + "blocks/blocking.json", true)); } /** * Returns a list of user objects that the authenticating user is blocking. * @param page the number of page * @return a list of user objects that the authenticating user * @throws HttpException when Weibo service or network is unavailable * @deprecated 饭否暂无此功能, 期待此功能 * @since fanfoudroid 0.5.0 */ public List<User> getBlockingUsers(int page) throws HttpException { return User.constructUsers(get(getBaseURL() + "blocks/blocking.json?page=" + page, true)); } /** * Returns an array of numeric user ids the authenticating user is blocking. * @return Returns an array of numeric user ids the authenticating user is blocking. * @throws HttpException when Weibo service or network is unavailable * @deprecated 饭否暂无此功能, 期待此功能 * @since fanfoudroid 0.5.0 */ public IDs getBlockingUsersIDs() throws HttpException { return new IDs(get(getBaseURL() + "blocks/blocking/ids.json", true),this); } /* 好友关系方法 */ /** * Tests if a friendship exists between two users. * * @param userA The ID or screen_name of the first user to test friendship for. * @param userB The ID or screen_name of the second user to test friendship for. * @return if a friendship exists between two users. * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public boolean existsFriendship(String userA, String userB) throws HttpException { return -1 != get(getBaseURL() + "friendships/exists.json", "user_a", userA, "user_b", userB, true). asString().indexOf("true"); } /** * Discontinues friendship with the user specified in the ID parameter as the authenticating user. Returns the un-friended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. * * @param id the ID or screen name of the user for whom to request a list of friends * @return User * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public User destroyFriendship(String id) throws HttpException { return new User(http.post(getBaseURL() + "friendships/destroy/" + id + ".json", createParams(), true).asJSONObject()); } /** * Befriends the user specified in the ID parameter as the authenticating user. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. * * @param id the ID or screen name of the user to be befriended * @return the befriended user * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public User createFriendship(String id) throws HttpException { return new User(http.post(getBaseURL() + "friendships/create/" + id + ".json", createParams(), true).asJSONObject()); } /** * Returns an array of numeric IDs for every user the specified user is followed by. * @param userId Specifies the ID of the user for whom to return the followers list. * @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned. * @return The ID or screen_name of the user to retrieve the friends ID list for. * @throws HttpException when Weibo service or network is unavailable * @since Weibo4J 2.0.10 * @see <a href="http://open.t.sina.com.cn/wiki/index.php/Followers/ids">followers/ids </a> */ public IDs getFollowersIDs(String userId) throws HttpException { return new IDs(get(getBaseURL() + "followers/ids.xml?user_id=" + userId, true)); } /** * Returns an array of numeric IDs for every user the specified user is followed by. * @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned. * @return The ID or screen_name of the user to retrieve the friends ID list for. * @throws HttpException when Weibo service or network is unavailable * @since Weibo4J 2.0.10 * @see <a href="http://open.t.sina.com.cn/wiki/index.php/Followers/ids">followers/ids </a> */ public IDs getFollowersIDs() throws HttpException { return new IDs(get(getBaseURL() + "followers/ids.xml", true)); } public List<com.ch_linghu.fanfoudroid.weibo.User> getFollowersList(String userId,Paging paging) throws HttpException{ return User.constructUsers(get(getBaseURL() + "users/followers.json", createParams(new BasicNameValuePair("id", userId)),paging, false)); } public List<com.ch_linghu.fanfoudroid.weibo.User> getFollowersList(String userId) throws HttpException{ return User.constructUsers(get(getBaseURL() + "users/followers.json", createParams(new BasicNameValuePair("id", userId)), false)); } /** * Returns an array of numeric IDs for every user the authenticating user is following. * @return an array of numeric IDs for every user the authenticating user is following * @throws HttpException when Weibo service or network is unavailable * @since androidroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public IDs getFriendsIDs() throws HttpException { return getFriendsIDs(-1l); } /** * Returns an array of numeric IDs for every user the authenticating user is following. * <br/>饭否无cursor参数 * * @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned. * @return an array of numeric IDs for every user the authenticating user is following * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public IDs getFriendsIDs(long cursor) throws HttpException { return new IDs(get(getBaseURL() + "friends/ids.xml?cursor=" + cursor, true)); } /** * 获取关注者id列表 * @param userId * @return * @throws HttpException */ public IDs getFriendsIDs(String userId) throws HttpException{ return new IDs(get(getBaseURL() + "friends/ids.xml?id=" +userId , true)); } /* 账户方法 */ /** * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. Use this method to test if supplied user credentials are valid. * 注意: 如果使用 错误的用户名/密码 多次登录后,饭否会锁IP * 返回提示为“尝试次数过多,请去 http://fandou.com 登录“,且需输入验证码 * * 登录成功返回 200 code * 登录失败返回 401 code * 使用HttpException的getStatusCode取得code * * @return user * @since androidroid 0.5.0 * @throws HttpException when Weibo service or network is unavailable * @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a> */ public User verifyCredentials() throws HttpException { return new User(get(getBaseURL() + "account/verify_credentials.json" , true).asJSONObject()); } /* Saved Searches Methods */ /** * Returns the authenticated user's saved search queries. * @return Returns an array of numeric user ids the authenticating user is blocking. * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public List<SavedSearch> getSavedSearches() throws HttpException { return SavedSearch.constructSavedSearches(get(getBaseURL() + "saved_searches.json", true)); } /** * Retrieve the data for a saved search owned by the authenticating user specified by the given id. * @param id The id of the saved search to be retrieved. * @return the data for a saved search * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public SavedSearch showSavedSearch(int id) throws HttpException { return new SavedSearch(get(getBaseURL() + "saved_searches/show/" + id + ".json", true)); } /** * Retrieve the data for a saved search owned by the authenticating user specified by the given id. * @return the data for a created saved search * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public SavedSearch createSavedSearch(String query) throws HttpException { return new SavedSearch(http.post(getBaseURL() + "saved_searches/create.json", createParams(new BasicNameValuePair("query", query)), true)); } /** * Destroys a saved search for the authenticated user. The search specified by id must be owned by the authenticating user. * @param id The id of the saved search to be deleted. * @return the data for a destroyed saved search * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public SavedSearch destroySavedSearch(int id) throws HttpException { return new SavedSearch(http.post(getBaseURL() + "saved_searches/destroy/" + id + ".json", true)); } /* Help Methods */ /** * Returns the string "ok" in the requested format with a 200 OK HTTP status code. * @return true if the API is working * @throws HttpException when Weibo service or network is unavailable * @since fanfoudroid 0.5.0 */ public boolean test() throws HttpException { return -1 != get(getBaseURL() + "help/test.json", false). asString().indexOf("ok"); } /***************** API METHOD END *********************/ private SimpleDateFormat format = new SimpleDateFormat( "EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Weibo weibo = (Weibo) o; if (!baseURL.equals(weibo.baseURL)) return false; if (!format.equals(weibo.format)) return false; if (!http.equals(weibo.http)) return false; if (!searchBaseURL.equals(weibo.searchBaseURL)) return false; if (!source.equals(weibo.source)) return false; return true; } @Override public int hashCode() { int result = http.hashCode(); result = 31 * result + baseURL.hashCode(); result = 31 * result + searchBaseURL.hashCode(); result = 31 * result + source.hashCode(); result = 31 * result + format.hashCode(); return result; } @Override public String toString() { return "Weibo{" + "http=" + http + ", baseURL='" + baseURL + '\'' + ", searchBaseURL='" + searchBaseURL + '\'' + ", source='" + source + '\'' + ", format=" + format + '}'; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.security.AccessControlException; import java.util.Properties; /** * @author Yusuke Yamamoto - yusuke at mac.com */ public class Configuration { private static Properties defaultProperty; static { init(); } /*package*/ static void init() { defaultProperty = new Properties(); //defaultProperty.setProperty("fanfoudroid.debug", "false"); defaultProperty.setProperty("fanfoudroid.debug", "true"); defaultProperty.setProperty("fanfoudroid.source", "fanfoudroid"); //defaultProperty.setProperty("fanfoudroid.clientVersion",""); defaultProperty.setProperty("fanfoudroid.clientURL", "http://sandin.tk/fanfoudroid.xml"); defaultProperty.setProperty("fanfoudroid.http.userAgent", "fanfoudroid 1.0"); //defaultProperty.setProperty("fanfoudroid.user",""); //defaultProperty.setProperty("fanfoudroid.password",""); defaultProperty.setProperty("fanfoudroid.http.useSSL", "false"); //defaultProperty.setProperty("fanfoudroid.http.proxyHost",""); defaultProperty.setProperty("fanfoudroid.http.proxyHost.fallback", "http.proxyHost"); //defaultProperty.setProperty("fanfoudroid.http.proxyUser",""); //defaultProperty.setProperty("fanfoudroid.http.proxyPassword",""); //defaultProperty.setProperty("fanfoudroid.http.proxyPort",""); defaultProperty.setProperty("fanfoudroid.http.proxyPort.fallback", "http.proxyPort"); defaultProperty.setProperty("fanfoudroid.http.connectionTimeout", "20000"); defaultProperty.setProperty("fanfoudroid.http.readTimeout", "120000"); defaultProperty.setProperty("fanfoudroid.http.retryCount", "3"); defaultProperty.setProperty("fanfoudroid.http.retryIntervalSecs", "10"); //defaultProperty.setProperty("fanfoudroid.oauth.consumerKey",""); //defaultProperty.setProperty("fanfoudroid.oauth.consumerSecret",""); defaultProperty.setProperty("fanfoudroid.async.numThreads", "1"); defaultProperty.setProperty("fanfoudroid.clientVersion", "1.0"); try { // Android platform should have dalvik.system.VMRuntime in the classpath. // @see http://developer.android.com/reference/dalvik/system/VMRuntime.html Class.forName("dalvik.system.VMRuntime"); defaultProperty.setProperty("fanfoudroid.dalvik", "true"); } catch (ClassNotFoundException cnfe) { defaultProperty.setProperty("fanfoudroid.dalvik", "false"); } DALVIK = getBoolean("fanfoudroid.dalvik"); String t4jProps = "fanfoudroid.properties"; boolean loaded = loadProperties(defaultProperty, "." + File.separatorChar + t4jProps) || loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/WEB-INF/" + t4jProps)) || loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/" + t4jProps)); } private static boolean loadProperties(Properties props, String path) { try { File file = new File(path); if(file.exists() && file.isFile()){ props.load(new FileInputStream(file)); return true; } } catch (Exception ignore) { } return false; } private static boolean loadProperties(Properties props, InputStream is) { try { props.load(is); return true; } catch (Exception ignore) { } return false; } private static boolean DALVIK; public static boolean isDalvik() { return DALVIK; } public static boolean useSSL() { return getBoolean("fanfoudroid.http.useSSL"); } public static String getScheme(){ return useSSL() ? "https://" : "http://"; } public static String getCilentVersion() { return getProperty("fanfoudroid.clientVersion"); } public static String getCilentVersion(String clientVersion) { return getProperty("fanfoudroid.clientVersion", clientVersion); } public static String getSource() { return getProperty("fanfoudroid.source"); } public static String getSource(String source) { return getProperty("fanfoudroid.source", source); } public static String getProxyHost() { return getProperty("fanfoudroid.http.proxyHost"); } public static String getProxyHost(String proxyHost) { return getProperty("fanfoudroid.http.proxyHost", proxyHost); } public static String getProxyUser() { return getProperty("fanfoudroid.http.proxyUser"); } public static String getProxyUser(String user) { return getProperty("fanfoudroid.http.proxyUser", user); } public static String getClientURL() { return getProperty("fanfoudroid.clientURL"); } public static String getClientURL(String clientURL) { return getProperty("fanfoudroid.clientURL", clientURL); } public static String getProxyPassword() { return getProperty("fanfoudroid.http.proxyPassword"); } public static String getProxyPassword(String password) { return getProperty("fanfoudroid.http.proxyPassword", password); } public static int getProxyPort() { return getIntProperty("fanfoudroid.http.proxyPort"); } public static int getProxyPort(int port) { return getIntProperty("fanfoudroid.http.proxyPort", port); } public static int getConnectionTimeout() { return getIntProperty("fanfoudroid.http.connectionTimeout"); } public static int getConnectionTimeout(int connectionTimeout) { return getIntProperty("fanfoudroid.http.connectionTimeout", connectionTimeout); } public static int getReadTimeout() { return getIntProperty("fanfoudroid.http.readTimeout"); } public static int getReadTimeout(int readTimeout) { return getIntProperty("fanfoudroid.http.readTimeout", readTimeout); } public static int getRetryCount() { return getIntProperty("fanfoudroid.http.retryCount"); } public static int getRetryCount(int retryCount) { return getIntProperty("fanfoudroid.http.retryCount", retryCount); } public static int getRetryIntervalSecs() { return getIntProperty("fanfoudroid.http.retryIntervalSecs"); } public static int getRetryIntervalSecs(int retryIntervalSecs) { return getIntProperty("fanfoudroid.http.retryIntervalSecs", retryIntervalSecs); } public static String getUser() { return getProperty("fanfoudroid.user"); } public static String getUser(String userId) { return getProperty("fanfoudroid.user", userId); } public static String getPassword() { return getProperty("fanfoudroid.password"); } public static String getPassword(String password) { return getProperty("fanfoudroid.password", password); } public static String getUserAgent() { return getProperty("fanfoudroid.http.userAgent"); } public static String getUserAgent(String userAgent) { return getProperty("fanfoudroid.http.userAgent", userAgent); } public static String getOAuthConsumerKey() { return getProperty("fanfoudroid.oauth.consumerKey"); } public static String getOAuthConsumerKey(String consumerKey) { return getProperty("fanfoudroid.oauth.consumerKey", consumerKey); } public static String getOAuthConsumerSecret() { return getProperty("fanfoudroid.oauth.consumerSecret"); } public static String getOAuthConsumerSecret(String consumerSecret) { return getProperty("fanfoudroid.oauth.consumerSecret", consumerSecret); } public static boolean getBoolean(String name) { String value = getProperty(name); return Boolean.valueOf(value); } public static int getIntProperty(String name) { String value = getProperty(name); try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { return -1; } } public static int getIntProperty(String name, int fallbackValue) { String value = getProperty(name, String.valueOf(fallbackValue)); try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { return -1; } } public static long getLongProperty(String name) { String value = getProperty(name); try { return Long.parseLong(value); } catch (NumberFormatException nfe) { return -1; } } public static String getProperty(String name) { return getProperty(name, null); } public static String getProperty(String name, String fallbackValue) { String value; try { value = System.getProperty(name, fallbackValue); if (null == value) { value = defaultProperty.getProperty(name); } if (null == value) { String fallback = defaultProperty.getProperty(name + ".fallback"); if (null != fallback) { value = System.getProperty(fallback); } } } catch (AccessControlException ace) { // Unsigned applet cannot access System properties value = fallbackValue; } return replace(value); } private static String replace(String value) { if (null == value) { return value; } String newValue = value; int openBrace = 0; if (-1 != (openBrace = value.indexOf("{", openBrace))) { int closeBrace = value.indexOf("}", openBrace); if (closeBrace > (openBrace + 1)) { String name = value.substring(openBrace + 1, closeBrace); if (name.length() > 0) { newValue = value.substring(0, openBrace) + getProperty(name) + value.substring(closeBrace + 1); } } } if (newValue.equals(value)) { return value; } else { return replace(newValue); } } public static int getNumberOfAsyncThreads() { return getIntProperty("fanfoudroid.async.numThreads"); } public static boolean getDebug() { return getBoolean("fanfoudroid.debug"); } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import android.database.Cursor; import android.util.Log; import com.ch_linghu.fanfoudroid.data.db.MessageTable; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.data.db.UserInfoTable; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * A data class representing Basic user information element */ public class User extends WeiboResponse implements java.io.Serializable { static final String[] POSSIBLE_ROOT_NAMES = new String[]{"user", "sender", "recipient", "retweeting_user"}; private Weibo weibo; private String id; private String name; private String screenName; private String location; private String description; private String birthday; private String gender; private String profileImageUrl; private String url; private boolean isProtected; private int followersCount; private Date statusCreatedAt; private String statusId = ""; private String statusText = null; private String statusSource = null; private boolean statusTruncated = false; private String statusInReplyToStatusId = ""; private String statusInReplyToUserId = ""; private boolean statusFavorited = false; private String statusInReplyToScreenName = null; private String profileBackgroundColor; private String profileTextColor; private String profileLinkColor; private String profileSidebarFillColor; private String profileSidebarBorderColor; private int friendsCount; private Date createdAt; private int favouritesCount; private int utcOffset; private String timeZone; private String profileBackgroundImageUrl; private String profileBackgroundTile; private boolean following; private boolean notificationEnabled; private int statusesCount; private boolean geoEnabled; private boolean verified; private static final long serialVersionUID = -6345893237975349030L; /*package*/User(Response res, Weibo weibo) throws HttpException { super(res); Element elem = res.asDocument().getDocumentElement(); init(elem, weibo); } /*package*/public User(Response res, Element elem, Weibo weibo) throws HttpException { super(res); init(elem, weibo); } /*package*/public User(JSONObject json) throws HttpException { super(); init(json); } /*package*/User(Response res) throws HttpException { super(); init(res.asJSONObject()); } User(){ } private void init(JSONObject json) throws HttpException { try { id = json.getString("id"); name = json.getString("name"); screenName = json.getString("screen_name"); location = json.getString("location"); gender = json.getString("gender"); birthday = json.getString("birthday"); description = json.getString("description"); profileImageUrl = json.getString("profile_image_url"); url = json.getString("url"); isProtected = json.getBoolean("protected"); followersCount = json.getInt("followers_count"); profileBackgroundColor = json.getString("profile_background_color"); profileTextColor = json.getString("profile_text_color"); profileLinkColor = json.getString("profile_link_color"); profileSidebarFillColor = json.getString("profile_sidebar_fill_color"); profileSidebarBorderColor = json.getString("profile_sidebar_border_color"); friendsCount = json.getInt("friends_count"); createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); favouritesCount = json.getInt("favourites_count"); utcOffset = getInt("utc_offset", json); // timeZone = json.getString("time_zone"); profileBackgroundImageUrl = json.getString("profile_background_image_url"); profileBackgroundTile = json.getString("profile_background_tile"); following = getBoolean("following", json); notificationEnabled = getBoolean("notifications", json); statusesCount = json.getInt("statuses_count"); if (!json.isNull("status")) { JSONObject status = json.getJSONObject("status"); statusCreatedAt = parseDate(status.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); statusId = status.getString("id"); statusText = status.getString("text"); statusSource = status.getString("source"); statusTruncated = status.getBoolean("truncated"); // statusInReplyToStatusId = status.getString("in_reply_to_status_id"); statusInReplyToStatusId = status.getString("in_reply_to_lastmsg_id"); // 饭否不知为什么把这个参数的名称改了 statusInReplyToUserId = status.getString("in_reply_to_user_id"); statusFavorited = status.getBoolean("favorited"); statusInReplyToScreenName = status.getString("in_reply_to_screen_name"); } } catch (JSONException jsone) { throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone); } } private void init(Element elem, Weibo weibo) throws HttpException { this.weibo = weibo; ensureRootNodeNameIs(POSSIBLE_ROOT_NAMES, elem); id = getChildString("id", elem); name = getChildText("name", elem); screenName = getChildText("screen_name", elem); location = getChildText("location", elem); description = getChildText("description", elem); profileImageUrl = getChildText("profile_image_url", elem); url = getChildText("url", elem); isProtected = getChildBoolean("protected", elem); followersCount = getChildInt("followers_count", elem); profileBackgroundColor = getChildText("profile_background_color", elem); profileTextColor = getChildText("profile_text_color", elem); profileLinkColor = getChildText("profile_link_color", elem); profileSidebarFillColor = getChildText("profile_sidebar_fill_color", elem); profileSidebarBorderColor = getChildText("profile_sidebar_border_color", elem); friendsCount = getChildInt("friends_count", elem); createdAt = getChildDate("created_at", elem); favouritesCount = getChildInt("favourites_count", elem); utcOffset = getChildInt("utc_offset", elem); // timeZone = getChildText("time_zone", elem); profileBackgroundImageUrl = getChildText("profile_background_image_url", elem); profileBackgroundTile = getChildText("profile_background_tile", elem); following = getChildBoolean("following", elem); notificationEnabled = getChildBoolean("notifications", elem); statusesCount = getChildInt("statuses_count", elem); geoEnabled = getChildBoolean("geo_enabled", elem); verified = getChildBoolean("verified", elem); NodeList statuses = elem.getElementsByTagName("status"); if (statuses.getLength() != 0) { Element status = (Element) statuses.item(0); statusCreatedAt = getChildDate("created_at", status); statusId = getChildString("id", status); statusText = getChildText("text", status); statusSource = getChildText("source", status); statusTruncated = getChildBoolean("truncated", status); statusInReplyToStatusId = getChildString("in_reply_to_status_id", status); statusInReplyToUserId = getChildString("in_reply_to_user_id", status); statusFavorited = getChildBoolean("favorited", status); statusInReplyToScreenName = getChildText("in_reply_to_screen_name", status); } } /** * Returns the id of the user * * @return the id of the user */ public String getId() { return id; } /** * Returns the name of the user * * @return the name of the user */ public String getName() { return name; } public String getGender() { return gender; } public String getBirthday() { return birthday; } /** * Returns the screen name of the user * * @return the screen name of the user */ public String getScreenName() { return screenName; } /** * Returns the location of the user * * @return the location of the user */ public String getLocation() { return location; } /** * Returns the description of the user * * @return the description of the user */ public String getDescription() { return description; } /** * Returns the profile image url of the user * * @return the profile image url of the user */ public URL getProfileImageURL() { try { return new URL(profileImageUrl); } catch (MalformedURLException ex) { return null; } } /** * Returns the url of the user * * @return the url of the user */ public URL getURL() { try { return new URL(url); } catch (MalformedURLException ex) { return null; } } /** * Test if the user status is protected * * @return true if the user status is protected */ public boolean isProtected() { return isProtected; } /** * Returns the number of followers * * @return the number of followers * @since Weibo4J 1.0.4 */ public int getFollowersCount() { return followersCount; } //TODO: uncomment // public DirectMessage sendDirectMessage(String text) throws WeiboException { // return weibo.sendDirectMessage(this.getName(), text); // } public static List<User> constructUsers(Response res, Weibo weibo) throws HttpException { Document doc = res.asDocument(); if (isRootNodeNilClasses(doc)) { return new ArrayList<User>(0); } else { try { ensureRootNodeNameIs("users", doc); // NodeList list = doc.getDocumentElement().getElementsByTagName( // "user"); // int size = list.getLength(); // List<User> users = new ArrayList<User>(size); // for (int i = 0; i < size; i++) { // users.add(new User(res, (Element) list.item(i), weibo)); // } //去除掉嵌套的bug NodeList list=doc.getDocumentElement().getChildNodes(); List<User> users = new ArrayList<User>(list.getLength()); Node node; for(int i=0;i<list.getLength();i++){ node=list.item(i); if(node.getNodeName().equals("user")){ users.add(new User(res, (Element) node, weibo)); } } return users; } catch (HttpException te) { if (isRootNodeNilClasses(doc)) { return new ArrayList<User>(0); } else { throw te; } } } } public static UserWapper constructWapperUsers(Response res, Weibo weibo) throws HttpException { Document doc = res.asDocument(); if (isRootNodeNilClasses(doc)) { return new UserWapper(new ArrayList<User>(0), 0, 0); } else { try { ensureRootNodeNameIs("users_list", doc); Element root = doc.getDocumentElement(); NodeList user = root.getElementsByTagName("users"); int length = user.getLength(); if (length == 0) { return new UserWapper(new ArrayList<User>(0), 0, 0); } // Element listsRoot = (Element) user.item(0); NodeList list=listsRoot.getChildNodes(); List<User> users = new ArrayList<User>(list.getLength()); Node node; for(int i=0;i<list.getLength();i++){ node=list.item(i); if(node.getNodeName().equals("user")){ users.add(new User(res, (Element) node, weibo)); } } // long previousCursor = getChildLong("previous_curosr", root); long nextCursor = getChildLong("next_curosr", root); if (nextCursor == -1) { // 兼容不同标签名称 nextCursor = getChildLong("nextCurosr", root); } return new UserWapper(users, previousCursor, nextCursor); } catch (HttpException te) { if (isRootNodeNilClasses(doc)) { return new UserWapper(new ArrayList<User>(0), 0, 0); } else { throw te; } } } } public static List<User> constructUsers(Response res) throws HttpException { try { JSONArray list = res.asJSONArray(); int size = list.length(); List<User> users = new ArrayList<User>(size); for (int i = 0; i < size; i++) { users.add(new User(list.getJSONObject(i))); } return users; } catch (JSONException jsone) { throw new HttpException(jsone); } catch (HttpException te) { throw te; } } /** * * @param res * @return * @throws HttpException */ public static UserWapper constructWapperUsers(Response res) throws HttpException { JSONObject jsonUsers = res.asJSONObject(); //asJSONArray(); try { JSONArray user = jsonUsers.getJSONArray("users"); int size = user.length(); List<User> users = new ArrayList<User>(size); for (int i = 0; i < size; i++) { users.add(new User(user.getJSONObject(i))); } long previousCursor = jsonUsers.getLong("previous_curosr"); long nextCursor = jsonUsers.getLong("next_cursor"); if (nextCursor == -1) { // 兼容不同标签名称 nextCursor = jsonUsers.getLong("nextCursor"); } return new UserWapper(users, previousCursor, nextCursor); } catch (JSONException jsone) { throw new HttpException(jsone); } } /** * @param res * @return * @throws HttpException */ static List<User> constructResult(Response res) throws HttpException { JSONArray list = res.asJSONArray(); try { int size = list.length(); List<User> users = new ArrayList<User>(size); for (int i = 0; i < size; i++) { users.add(new User(list.getJSONObject(i))); } return users; } catch (JSONException e) { } return null; } /** * @return created_at or null if the user is protected * @since Weibo4J 1.1.0 */ public Date getStatusCreatedAt() { return statusCreatedAt; } /** * * @return status id or -1 if the user is protected */ public String getStatusId() { return statusId; } /** * * @return status text or null if the user is protected */ public String getStatusText() { return statusText; } /** * * @return source or null if the user is protected * @since 1.1.4 */ public String getStatusSource() { return statusSource; } /** * * @return truncated or false if the user is protected * @since 1.1.4 */ public boolean isStatusTruncated() { return statusTruncated; } /** * * @return in_reply_to_status_id or -1 if the user is protected * @since 1.1.4 */ public String getStatusInReplyToStatusId() { return statusInReplyToStatusId; } /** * * @return in_reply_to_user_id or -1 if the user is protected * @since 1.1.4 */ public String getStatusInReplyToUserId() { return statusInReplyToUserId; } /** * * @return favorited or false if the user is protected * @since 1.1.4 */ public boolean isStatusFavorited() { return statusFavorited; } /** * * @return in_reply_to_screen_name or null if the user is protected * @since 1.1.4 */ public String getStatusInReplyToScreenName() { return "" != statusInReplyToUserId ? statusInReplyToScreenName : null; } public String getProfileBackgroundColor() { return profileBackgroundColor; } public String getProfileTextColor() { return profileTextColor; } public String getProfileLinkColor() { return profileLinkColor; } public String getProfileSidebarFillColor() { return profileSidebarFillColor; } public String getProfileSidebarBorderColor() { return profileSidebarBorderColor; } public int getFriendsCount() { return friendsCount; } public Date getCreatedAt() { return createdAt; } public int getFavouritesCount() { return favouritesCount; } public int getUtcOffset() { return utcOffset; } public String getTimeZone() { return timeZone; } public String getProfileBackgroundImageUrl() { return profileBackgroundImageUrl; } public String getProfileBackgroundTile() { return profileBackgroundTile; } /** * */ public boolean isFollowing() { return following; } /** * @deprecated use isNotificationsEnabled() instead */ public boolean isNotifications() { return notificationEnabled; } /** * * @since Weibo4J 2.0.1 */ public boolean isNotificationEnabled() { return notificationEnabled; } public int getStatusesCount() { return statusesCount; } /** * @return the user is enabling geo location * @since Weibo4J 2.0.10 */ public boolean isGeoEnabled() { return geoEnabled; } /** * @return returns true if the user is a verified celebrity * @since Weibo4J 2.0.10 */ public boolean isVerified() { return verified; } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(Object obj) { if (null == obj) { return false; } if (this == obj) { return true; } return obj instanceof User && ((User) obj).id.equals(this.id); } @Override public String toString() { return "User{" + "weibo=" + weibo + ", id=" + id + ", name='" + name + '\'' + ", screenName='" + screenName + '\'' + ", location='" + location + '\'' + ", description='" + description + '\'' + ", profileImageUrl='" + profileImageUrl + '\'' + ", url='" + url + '\'' + ", isProtected=" + isProtected + ", followersCount=" + followersCount + ", statusCreatedAt=" + statusCreatedAt + ", statusId=" + statusId + ", statusText='" + statusText + '\'' + ", statusSource='" + statusSource + '\'' + ", statusTruncated=" + statusTruncated + ", statusInReplyToStatusId=" + statusInReplyToStatusId + ", statusInReplyToUserId=" + statusInReplyToUserId + ", statusFavorited=" + statusFavorited + ", statusInReplyToScreenName='" + statusInReplyToScreenName + '\'' + ", profileBackgroundColor='" + profileBackgroundColor + '\'' + ", profileTextColor='" + profileTextColor + '\'' + ", profileLinkColor='" + profileLinkColor + '\'' + ", profileSidebarFillColor='" + profileSidebarFillColor + '\'' + ", profileSidebarBorderColor='" + profileSidebarBorderColor + '\'' + ", friendsCount=" + friendsCount + ", createdAt=" + createdAt + ", favouritesCount=" + favouritesCount + ", utcOffset=" + utcOffset + // ", timeZone='" + timeZone + '\'' + ", profileBackgroundImageUrl='" + profileBackgroundImageUrl + '\'' + ", profileBackgroundTile='" + profileBackgroundTile + '\'' + ", following=" + following + ", notificationEnabled=" + notificationEnabled + ", statusesCount=" + statusesCount + ", geoEnabled=" + geoEnabled + ", verified=" + verified + '}'; } //TODO:增加从游标解析User的方法,用于和data里User转换一条数据 public static User parseUser(Cursor cursor){ if (null == cursor || 0 == cursor.getCount()||cursor.getCount()>1) { Log.w("User.ParseUser", "Cann't parse Cursor, bacause cursor is null or empty."); } cursor.moveToFirst(); User u=new User(); u.id = cursor.getString(cursor.getColumnIndex(UserInfoTable._ID)); u.name = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_USER_NAME)); u.screenName = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_USER_SCREEN_NAME)); u.location = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_LOCALTION)); u.description = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_DESCRIPTION)); u.profileImageUrl = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_PROFILE_IMAGE_URL)); u.url = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_URL)); u.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_PROTECTED))) ? false : true; u.followersCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FOLLOWERS_COUNT)); u.friendsCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FRIENDS_COUNT)); u.favouritesCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FAVORITES_COUNT)); u.statusesCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_STATUSES_COUNT)); u.following = (0 == cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FOLLOWING))) ? false : true; try { String createAtStr=cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)); if(createAtStr!=null){ u.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(createAtStr); } } catch (ParseException e) { Log.w("User", "Invalid created at data."); } return u; } public com.ch_linghu.fanfoudroid.data.User parseUser(){ com.ch_linghu.fanfoudroid.data.User user=new com.ch_linghu.fanfoudroid.data.User(); user.id=this.id; user.name=this.name; user.screenName=this.screenName; user.location=this.location; user.description=this.description; user.profileImageUrl=this.profileImageUrl; user.url=this.url; user.isProtected=this.isProtected; user.followersCount=this.followersCount; user.friendsCount=this.friendsCount; user.favoritesCount=this.favouritesCount; user.statusesCount=this.statusesCount; user.isFollowing=this.following; user.createdAt = this.createdAt; return user; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * A data class representing Treands. * * @author Yusuke Yamamoto - yusuke at mac.com * @since Weibo4J 2.0.2 */ public class Trends extends WeiboResponse implements Comparable<Trends> { private Date asOf; private Date trendAt; private Trend[] trends; private static final long serialVersionUID = -7151479143843312309L; public int compareTo(Trends that) { return this.trendAt.compareTo(that.trendAt); } /*package*/ Trends(Response res, Date asOf, Date trendAt, Trend[] trends) throws HttpException { super(res); this.asOf = asOf; this.trendAt = trendAt; this.trends = trends; } /*package*/ static List<Trends> constructTrendsList(Response res) throws HttpException { JSONObject json = res.asJSONObject(); List<Trends> trends; try { Date asOf = parseDate(json.getString("as_of")); JSONObject trendsJson = json.getJSONObject("trends"); trends = new ArrayList<Trends>(trendsJson.length()); Iterator ite = trendsJson.keys(); while (ite.hasNext()) { String key = (String) ite.next(); JSONArray array = trendsJson.getJSONArray(key); Trend[] trendsArray = jsonArrayToTrendArray(array); if (key.length() == 19) { // current trends trends.add(new Trends(res, asOf, parseDate(key , "yyyy-MM-dd HH:mm:ss"), trendsArray)); } else if (key.length() == 16) { // daily trends trends.add(new Trends(res, asOf, parseDate(key , "yyyy-MM-dd HH:mm"), trendsArray)); } else if (key.length() == 10) { // weekly trends trends.add(new Trends(res, asOf, parseDate(key , "yyyy-MM-dd"), trendsArray)); } } Collections.sort(trends); return trends; } catch (JSONException jsone) { throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone); } } /*package*/ static Trends constructTrends(Response res) throws HttpException { JSONObject json = res.asJSONObject(); try { Date asOf = parseDate(json.getString("as_of")); JSONArray array = json.getJSONArray("trends"); Trend[] trendsArray = jsonArrayToTrendArray(array); return new Trends(res, asOf, asOf, trendsArray); } catch (JSONException jsone) { throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone); } } private static Date parseDate(String asOfStr) throws HttpException { Date parsed; if (asOfStr.length() == 10) { parsed = new Date(Long.parseLong(asOfStr) * 1000); } else { // parsed = WeiboResponse.parseDate(asOfStr, "EEE, d MMM yyyy HH:mm:ss z"); parsed = WeiboResponse.parseDate(asOfStr, "EEE MMM WW HH:mm:ss z yyyy"); } return parsed; } private static Trend[] jsonArrayToTrendArray(JSONArray array) throws JSONException { Trend[] trends = new Trend[array.length()]; for (int i = 0; i < array.length(); i++) { JSONObject trend = array.getJSONObject(i); trends[i] = new Trend(trend); } return trends; } public Trend[] getTrends() { return this.trends; } public Date getAsOf() { return asOf; } public Date getTrendAt() { return trendAt; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Trends)) return false; Trends trends1 = (Trends) o; if (asOf != null ? !asOf.equals(trends1.asOf) : trends1.asOf != null) return false; if (trendAt != null ? !trendAt.equals(trends1.trendAt) : trends1.trendAt != null) return false; if (!Arrays.equals(trends, trends1.trends)) return false; return true; } @Override public int hashCode() { int result = asOf != null ? asOf.hashCode() : 0; result = 31 * result + (trendAt != null ? trendAt.hashCode() : 0); result = 31 * result + (trends != null ? Arrays.hashCode(trends) : 0); return result; } @Override public String toString() { return "Trends{" + "asOf=" + asOf + ", trendAt=" + trendAt + ", trends=" + (trends == null ? null : Arrays.asList(trends)) + '}'; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * A data class representing one single status of a user. * @author Yusuke Yamamoto - yusuke at mac.com */ public class Status extends WeiboResponse implements java.io.Serializable { private static final long serialVersionUID = 1608000492860584608L; private Date createdAt; private String id; private String text; private String source; private boolean isTruncated; private String inReplyToStatusId; private String inReplyToUserId; private boolean isFavorited; private String inReplyToScreenName; private double latitude = -1; private double longitude = -1; private String thumbnail_pic; private String bmiddle_pic; private String original_pic; private String photo_url; private RetweetDetails retweetDetails; private User user = null; /*package*/Status(Response res, Weibo weibo) throws HttpException { super(res); Element elem = res.asDocument().getDocumentElement(); init(res, elem, weibo); } /*package*/Status(Response res, Element elem, Weibo weibo) throws HttpException { super(res); init(res, elem, weibo); } Status(Response res)throws HttpException{ super(res); JSONObject json=res.asJSONObject(); try { id = json.getString("id"); text = json.getString("text"); source = json.getString("source"); createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); inReplyToStatusId = getString("in_reply_to_status_id", json); inReplyToUserId = getString("in_reply_to_user_id", json); isFavorited = getBoolean("favorited", json); // System.out.println("json photo" + json.getJSONObject("photo")); if(!json.isNull("photo")) { // System.out.println("not null" + json.getJSONObject("photo")); Photo photo = new Photo(json.getJSONObject("photo")); thumbnail_pic = photo.getThumbnail_pic(); bmiddle_pic = photo.getBmiddle_pic(); original_pic = photo.getOriginal_pic(); } else { // System.out.println("Null"); thumbnail_pic = ""; bmiddle_pic = ""; original_pic = ""; } if(!json.isNull("user")) user = new User(json.getJSONObject("user")); inReplyToScreenName=json.getString("in_reply_to_screen_name"); if(!json.isNull("retweetDetails")){ retweetDetails = new RetweetDetails(json.getJSONObject("retweetDetails")); } } catch (JSONException je) { throw new HttpException(je.getMessage() + ":" + json.toString(), je); } } /* modify by sycheng add some field*/ public Status(JSONObject json)throws HttpException, JSONException{ id = json.getString("id"); text = json.getString("text"); source = json.getString("source"); createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); isFavorited = getBoolean("favorited", json); isTruncated=getBoolean("truncated", json); inReplyToStatusId = getString("in_reply_to_status_id", json); inReplyToUserId = getString("in_reply_to_user_id", json); inReplyToScreenName=json.getString("in_reply_to_screen_name"); if(!json.isNull("photo")) { Photo photo = new Photo(json.getJSONObject("photo")); thumbnail_pic = photo.getThumbnail_pic(); bmiddle_pic = photo.getBmiddle_pic(); original_pic = photo.getOriginal_pic(); } else { thumbnail_pic = ""; bmiddle_pic = ""; original_pic = ""; } user = new User(json.getJSONObject("user")); } public Status(String str) throws HttpException, JSONException { // StatusStream uses this constructor super(); JSONObject json = new JSONObject(str); id = json.getString("id"); text = json.getString("text"); source = json.getString("source"); createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); inReplyToStatusId = getString("in_reply_to_status_id", json); inReplyToUserId = getString("in_reply_to_user_id", json); isFavorited = getBoolean("favorited", json); if(!json.isNull("photo")) { Photo photo = new Photo(json.getJSONObject("photo")); thumbnail_pic = photo.getThumbnail_pic(); bmiddle_pic = photo.getBmiddle_pic(); original_pic = photo.getOriginal_pic(); } else { thumbnail_pic = ""; bmiddle_pic = ""; original_pic = ""; } user = new User(json.getJSONObject("user")); } private void init(Response res, Element elem, Weibo weibo) throws HttpException { ensureRootNodeNameIs("status", elem); user = new User(res, (Element) elem.getElementsByTagName("user").item(0) , weibo); id = getChildString("id", elem); text = getChildText("text", elem); source = getChildText("source", elem); createdAt = getChildDate("created_at", elem); isTruncated = getChildBoolean("truncated", elem); inReplyToStatusId = getChildString("in_reply_to_status_id", elem); inReplyToUserId = getChildString("in_reply_to_user_id", elem); isFavorited = getChildBoolean("favorited", elem); inReplyToScreenName = getChildText("in_reply_to_screen_name", elem); NodeList georssPoint = elem.getElementsByTagName("georss:point"); if(1 == georssPoint.getLength()){ String[] point = georssPoint.item(0).getFirstChild().getNodeValue().split(" "); if(!"null".equals(point[0])) latitude = Double.parseDouble(point[0]); if(!"null".equals(point[1])) longitude = Double.parseDouble(point[1]); } NodeList retweetDetailsNode = elem.getElementsByTagName("retweet_details"); if(1 == retweetDetailsNode.getLength()){ retweetDetails = new RetweetDetails(res,(Element)retweetDetailsNode.item(0),weibo); } } /** * Return the created_at * * @return created_at * @since Weibo4J 1.1.0 */ public Date getCreatedAt() { return this.createdAt; } /** * Returns the id of the status * * @return the id */ public String getId() { return this.id; } /** * Returns the text of the status * * @return the text */ public String getText() { return this.text; } /** * Returns the source * * @return the source * @since Weibo4J 1.0.4 */ public String getSource() { return this.source; } /** * Test if the status is truncated * * @return true if truncated * @since Weibo4J 1.0.4 */ public boolean isTruncated() { return isTruncated; } /** * Returns the in_reply_tostatus_id * * @return the in_reply_tostatus_id * @since Weibo4J 1.0.4 */ public String getInReplyToStatusId() { return inReplyToStatusId; } /** * Returns the in_reply_user_id * * @return the in_reply_tostatus_id * @since Weibo4J 1.0.4 */ public String getInReplyToUserId() { return inReplyToUserId; } /** * Returns the in_reply_to_screen_name * * @return the in_in_reply_to_screen_name * @since Weibo4J 2.0.4 */ public String getInReplyToScreenName() { return inReplyToScreenName; } /** * returns The location's latitude that this tweet refers to. * * @since Weibo4J 2.0.10 */ public double getLatitude() { return latitude; } /** * returns The location's longitude that this tweet refers to. * * @since Weibo4J 2.0.10 */ public double getLongitude() { return longitude; } /** * Test if the status is favorited * * @return true if favorited * @since Weibo4J 1.0.4 */ public boolean isFavorited() { return isFavorited; } public String getThumbnail_pic() { return thumbnail_pic; } public String getBmiddle_pic() { return bmiddle_pic; } public String getOriginal_pic() { return original_pic; } /** * Return the user * * @return the user */ public User getUser() { return user; } // TODO: 等合并Tweet, Status public int getType() { return -1111111; } /** * * @since Weibo4J 2.0.10 */ public boolean isRetweet(){ return null != retweetDetails; } /** * * @since Weibo4J 2.0.10 */ public RetweetDetails getRetweetDetails() { return retweetDetails; } /*package*/ static List<Status> constructStatuses(Response res, Weibo weibo) throws HttpException { Document doc = res.asDocument(); if (isRootNodeNilClasses(doc)) { return new ArrayList<Status>(0); } else { try { ensureRootNodeNameIs("statuses", doc); NodeList list = doc.getDocumentElement().getElementsByTagName( "status"); int size = list.getLength(); List<Status> statuses = new ArrayList<Status>(size); for (int i = 0; i < size; i++) { Element status = (Element) list.item(i); statuses.add(new Status(res, status, weibo)); } return statuses; } catch (HttpException te) { ensureRootNodeNameIs("nil-classes", doc); return new ArrayList<Status>(0); } } } /*modify by sycheng add json call method*/ /*package*/ static List<Status> constructStatuses(Response res) throws HttpException { try { JSONArray list = res.asJSONArray(); int size = list.length(); List<Status> statuses = new ArrayList<Status>(size); for (int i = 0; i < size; i++) { statuses.add(new Status(list.getJSONObject(i))); } return statuses; } catch (JSONException jsone) { throw new HttpException(jsone); } catch (HttpException te) { throw te; } } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(Object obj) { if (null == obj) { return false; } if (this == obj) { return true; } // return obj instanceof Status && ((Status) obj).id == this.id; return obj instanceof Status && this.id.equals(((Status) obj).id); } @Override public String toString() { return "Status{" + "createdAt=" + createdAt + ", id=" + id + ", text='" + text + '\'' + ", source='" + source + '\'' + ", isTruncated=" + isTruncated + ", inReplyToStatusId=" + inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId + ", isFavorited=" + isFavorited + ", thumbnail_pic=" + thumbnail_pic + ", bmiddle_pic=" + bmiddle_pic + ", original_pic=" + original_pic + ", inReplyToScreenName='" + inReplyToScreenName + '\'' + ", latitude=" + latitude + ", longitude=" + longitude + ", retweetDetails=" + retweetDetails + ", user=" + user + '}'; } public boolean isEmpty() { return (null == id); } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.util.Arrays; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * A data class representing array of numeric IDs. * * @author Yusuke Yamamoto - yusuke at mac.com */ public class IDs extends WeiboResponse { private String[] ids; private long previousCursor; private long nextCursor; private static final long serialVersionUID = -6585026560164704953L; private static String[] ROOT_NODE_NAMES = {"id_list", "ids"}; /*package*/ IDs(Response res) throws HttpException { super(res); Element elem = res.asDocument().getDocumentElement(); ensureRootNodeNameIs(ROOT_NODE_NAMES, elem); NodeList idlist = elem.getElementsByTagName("id"); ids = new String[idlist.getLength()]; for (int i = 0; i < idlist.getLength(); i++) { try { ids[i] = idlist.item(i).getFirstChild().getNodeValue(); } catch (NumberFormatException nfe) { throw new HttpException("Weibo API returned malformed response(Invalid Number): " + elem, nfe); } catch (NullPointerException npe) { throw new HttpException("Weibo API returned malformed response(NULL): " + elem, npe); } } previousCursor = getChildLong("previous_cursor", elem); nextCursor = getChildLong("next_cursor", elem); } /*package*/ IDs(Response res,Weibo w) throws HttpException { super(res); // TODO: 饭否返回的为 JSONArray 类型, 例如["ifan","fanfouapi","\u62cd\u62cd","daoru"] JSONObject json= res.asJSONObject(); try { previousCursor = json.getLong("previous_cursor"); nextCursor = json.getLong("next_cursor"); if(!json.isNull("ids")){ JSONArray jsona= json.getJSONArray("ids"); int size=jsona.length(); ids = new String[size]; for (int i = 0; i < size; i++) { ids[i] =jsona.getString(i); } } } catch (JSONException jsone) { throw new HttpException(jsone); } } public String[] getIDs() { return ids; } /** * * @since Weibo4J 2.0.10 */ public boolean hasPrevious(){ return 0 != previousCursor; } /** * * @since Weibo4J 2.0.10 */ public long getPreviousCursor() { return previousCursor; } /** * * @since Weibo4J 2.0.10 */ public boolean hasNext(){ return 0 != nextCursor; } /** * * @since Weibo4J 2.0.10 */ public long getNextCursor() { return nextCursor; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof IDs)) return false; IDs iDs = (IDs) o; if (!Arrays.equals(ids, iDs.ids)) return false; return true; } @Override public int hashCode() { return ids != null ? Arrays.hashCode(ids) : 0; } public int getCount(){ return ids.length; } @Override public String toString() { return "IDs{" + "ids=" + ids + ", previousCursor=" + previousCursor + ", nextCursor=" + nextCursor + '}'; } }
Java
package com.ch_linghu.fanfoudroid.weibo; /** * An exception class that will be thrown when WeiboAPI calls are failed.<br> * In case the Fanfou server returned HTTP error code, you can get the HTTP status code using getStatusCode() method. */ public class WeiboException extends Exception { private int statusCode = -1; private static final long serialVersionUID = -2623309261327598087L; public WeiboException(String msg) { super(msg); } public WeiboException(Exception cause) { super(cause); } public WeiboException(String msg, int statusCode) { super(msg); this.statusCode = statusCode; } public WeiboException(String msg, Exception cause) { super(msg, cause); } public WeiboException(String msg, Exception cause, int statusCode) { super(msg, cause); this.statusCode = statusCode; } public int getStatusCode() { return this.statusCode; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * A data class representing one single retweet details. * * @author Yusuke Yamamoto - yusuke at mac.com * @since Weibo4J 2.0.10 */ public class RetweetDetails extends WeiboResponse implements java.io.Serializable { private long retweetId; private Date retweetedAt; private User retweetingUser; static final long serialVersionUID = 1957982268696560598L; public RetweetDetails(Response res, Weibo weibo) throws HttpException { super(res); Element elem = res.asDocument().getDocumentElement(); init(res, elem, weibo); } public RetweetDetails(JSONObject json) throws HttpException { super(); init(json); } private void init(JSONObject json) throws HttpException{ try { retweetId = json.getInt("retweetId"); retweetedAt = parseDate(json.getString("retweetedAt"), "EEE MMM dd HH:mm:ss z yyyy"); retweetingUser=new User(json.getJSONObject("retweetingUser")); } catch (JSONException jsone) { throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone); } } /*package*/public RetweetDetails(Response res, Element elem, Weibo weibo) throws HttpException { super(res); init(res, elem, weibo); } private void init(Response res, Element elem, Weibo weibo) throws HttpException { ensureRootNodeNameIs("retweet_details", elem); retweetId = getChildLong("retweet_id", elem); retweetedAt = getChildDate("retweeted_at", elem); retweetingUser = new User(res, (Element) elem.getElementsByTagName("retweeting_user").item(0) , weibo); } public long getRetweetId() { return retweetId; } public Date getRetweetedAt() { return retweetedAt; } public User getRetweetingUser() { return retweetingUser; } /*modify by sycheng add json*/ /*package*/ static List<RetweetDetails> createRetweetDetails(Response res) throws HttpException { try { JSONArray list = res.asJSONArray(); int size = list.length(); List<RetweetDetails> retweets = new ArrayList<RetweetDetails>(size); for (int i = 0; i < size; i++) { retweets.add(new RetweetDetails(list.getJSONObject(i))); } return retweets; } catch (JSONException jsone) { throw new HttpException(jsone); } catch (HttpException te) { throw te; } } /*package*/ static List<RetweetDetails> createRetweetDetails(Response res, Weibo weibo) throws HttpException { Document doc = res.asDocument(); if (isRootNodeNilClasses(doc)) { return new ArrayList<RetweetDetails>(0); } else { try { ensureRootNodeNameIs("retweets", doc); NodeList list = doc.getDocumentElement().getElementsByTagName( "retweet_details"); int size = list.getLength(); List<RetweetDetails> statuses = new ArrayList<RetweetDetails>(size); for (int i = 0; i < size; i++) { Element status = (Element) list.item(i); statuses.add(new RetweetDetails(res, status, weibo)); } return statuses; } catch (HttpException te) { ensureRootNodeNameIs("nil-classes", doc); return new ArrayList<RetweetDetails>(0); } } } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RetweetDetails)) return false; RetweetDetails that = (RetweetDetails) o; return retweetId == that.retweetId; } @Override public int hashCode() { int result = (int) (retweetId ^ (retweetId >>> 32)); result = 31 * result + retweetedAt.hashCode(); result = 31 * result + retweetingUser.hashCode(); return result; } @Override public String toString() { return "RetweetDetails{" + "retweetId=" + retweetId + ", retweetedAt=" + retweetedAt + ", retweetingUser=" + retweetingUser + '}'; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONException; import org.json.JSONObject; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * 模仿JSONObject的XML实现 * @author jmx * */ class XmlObject{ private String str; public XmlObject(String s){ this.str = s; } //FIXME: 这里用的是一个专有的ugly实现 public String getString(String name) throws Exception { Pattern p = Pattern.compile(String.format("<%s>(.*?)</%s>", name, name)); Matcher m = p.matcher(this.str); if (m.find()){ return m.group(1); }else{ throw new Exception(String.format("<%s> value not found", name)); } } @Override public String toString(){ return this.str; } } /** * 服务器响应的错误信息 */ public class RefuseError extends WeiboResponse implements java.io.Serializable { // TODO: get error type public static final int ERROR_A = 1; public static final int ERROR_B = 1; public static final int ERROR_C = 1; private int mErrorCode = -1; private String mRequestUrl = ""; private String mResponseError = ""; private static final long serialVersionUID = -2105422180879273058L; public RefuseError(Response res) throws HttpException { String error = res.asString(); try{ //先尝试作为json object进行处理 JSONObject json = new JSONObject(error); init(json); }catch(Exception e1){ //如果失败,则作为XML再进行处理 try{ XmlObject xml = new XmlObject(error); init(xml); }catch(Exception e2){ //再失败就作为普通字符串进行处理,这个处理保证不会出错 init(error); } } } public void init(JSONObject json) throws HttpException { try { mRequestUrl = json.getString("request"); mResponseError = json.getString("error"); parseError(mResponseError); } catch (JSONException je) { throw new HttpException(je.getMessage() + ":" + json.toString(), je); } } public void init(XmlObject xml) throws HttpException { try { mRequestUrl = xml.getString("request"); mResponseError = xml.getString("error"); parseError(mResponseError); } catch (Exception e) { throw new HttpException(e.getMessage() + ":" + xml.toString(), e); } } public void init(String error){ mRequestUrl = ""; mResponseError = error; parseError(mResponseError); } private void parseError(String error) { if (error.equals("")) { mErrorCode = ERROR_A; } } public int getErrorCode() { return mErrorCode; } public String getRequestUrl() { return mRequestUrl; } public String getMessage() { return mResponseError; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Element; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * A data class representing Weibo rate limit status * @author Yusuke Yamamoto - yusuke at mac.com */ public class RateLimitStatus extends WeiboResponse { private int remainingHits; private int hourlyLimit; private int resetTimeInSeconds; private Date resetTime; private static final long serialVersionUID = 933996804168952707L; /* package */ RateLimitStatus(Response res) throws HttpException { super(res); Element elem = res.asDocument().getDocumentElement(); remainingHits = getChildInt("remaining-hits", elem); hourlyLimit = getChildInt("hourly-limit", elem); resetTimeInSeconds = getChildInt("reset-time-in-seconds", elem); resetTime = getChildDate("reset-time", elem, "EEE MMM d HH:mm:ss z yyyy"); } /*modify by sycheng add json call*/ /* package */ RateLimitStatus(Response res,Weibo w) throws HttpException { super(res); JSONObject json= res.asJSONObject(); try { remainingHits = json.getInt("remaining_hits"); hourlyLimit = json.getInt("hourly_limit"); resetTimeInSeconds = json.getInt("reset_time_in_seconds"); resetTime = parseDate(json.getString("reset_time"), "EEE MMM dd HH:mm:ss z yyyy"); } catch (JSONException jsone) { throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone); } } public int getRemainingHits() { return remainingHits; } public int getHourlyLimit() { return hourlyLimit; } public int getResetTimeInSeconds() { return resetTimeInSeconds; } /** * * @deprecated use getResetTime() instead */ @Deprecated public Date getDateTime() { return resetTime; } /** * @since Weibo4J 2.0.9 */ public Date getResetTime() { return resetTime; } @Override public String toString() { StringBuilder sb=new StringBuilder(); sb.append("RateLimitStatus{remainingHits:"); sb.append(remainingHits); sb.append(";hourlyLimit:"); sb.append(hourlyLimit); sb.append(";resetTimeInSeconds:"); sb.append(resetTimeInSeconds); sb.append(";resetTime:"); sb.append(resetTime); sb.append("}"); return sb.toString(); } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * A data class representing sent/received direct message. * @author Yusuke Yamamoto - yusuke at mac.com */ public class DirectMessage extends WeiboResponse implements java.io.Serializable { private String id; private String text; private String sender_id; private String recipient_id; private Date created_at; private String sender_screen_name; private String recipient_screen_name; private static final long serialVersionUID = -3253021825891789737L; /*package*/DirectMessage(Response res, Weibo weibo) throws HttpException { super(res); init(res, res.asDocument().getDocumentElement(), weibo); } /*package*/DirectMessage(Response res, Element elem, Weibo weibo) throws HttpException { super(res); init(res, elem, weibo); } /*modify by sycheng add json call*/ /*package*/DirectMessage(JSONObject json) throws HttpException { try { id = json.getString("id"); text = json.getString("text"); sender_id = json.getString("sender_id"); recipient_id = json.getString("recipient_id"); created_at = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); sender_screen_name = json.getString("sender_screen_name"); recipient_screen_name = json.getString("recipient_screen_name"); if(!json.isNull("sender")) sender = new User(json.getJSONObject("sender")); if(!json.isNull("recipient")) recipient = new User(json.getJSONObject("recipient")); } catch (JSONException jsone) { throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone); } } private void init(Response res, Element elem, Weibo weibo) throws HttpException{ ensureRootNodeNameIs("direct_message", elem); sender = new User(res, (Element) elem.getElementsByTagName("sender").item(0), weibo); recipient = new User(res, (Element) elem.getElementsByTagName("recipient").item(0), weibo); id = getChildString("id", elem); text = getChildText("text", elem); sender_id = getChildString("sender_id", elem); recipient_id = getChildString("recipient_id", elem); created_at = getChildDate("created_at", elem); sender_screen_name = getChildText("sender_screen_name", elem); recipient_screen_name = getChildText("recipient_screen_name", elem); } public String getId() { return id; } public String getText() { return text; } public String getSenderId() { return sender_id; } public String getRecipientId() { return recipient_id; } /** * @return created_at * @since Weibo4J 1.1.0 */ public Date getCreatedAt() { return created_at; } public String getSenderScreenName() { return sender_screen_name; } public String getRecipientScreenName() { return recipient_screen_name; } private User sender; public User getSender() { return sender; } private User recipient; public User getRecipient() { return recipient; } /*package*/ static List<DirectMessage> constructDirectMessages(Response res, Weibo weibo) throws HttpException { Document doc = res.asDocument(); if (isRootNodeNilClasses(doc)) { return new ArrayList<DirectMessage>(0); } else { try { ensureRootNodeNameIs("direct-messages", doc); NodeList list = doc.getDocumentElement().getElementsByTagName( "direct_message"); int size = list.getLength(); List<DirectMessage> messages = new ArrayList<DirectMessage>(size); for (int i = 0; i < size; i++) { Element status = (Element) list.item(i); messages.add(new DirectMessage(res, status, weibo)); } return messages; } catch (HttpException te) { if (isRootNodeNilClasses(doc)) { return new ArrayList<DirectMessage>(0); } else { throw te; } } } } /*package*/ static List<DirectMessage> constructDirectMessages(Response res ) throws HttpException { JSONArray list= res.asJSONArray(); try { int size = list.length(); List<DirectMessage> messages = new ArrayList<DirectMessage>(size); for (int i = 0; i < size; i++) { messages.add(new DirectMessage(list.getJSONObject(i))); } return messages; } catch (JSONException jsone) { throw new HttpException(jsone); } } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(Object obj) { if (null == obj) { return false; } if (this == obj) { return true; } return obj instanceof DirectMessage && ((DirectMessage) obj).id.equals(this.id); } @Override public String toString() { return "DirectMessage{" + "id=" + id + ", text='" + text + '\'' + ", sender_id=" + sender_id + ", recipient_id=" + recipient_id + ", created_at=" + created_at + ", sender_screen_name='" + sender_screen_name + '\'' + ", recipient_screen_name='" + recipient_screen_name + '\'' + ", sender=" + sender + ", recipient=" + recipient + '}'; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; /** * Controlls pagination * * @author Yusuke Yamamoto - yusuke at mac.com */ public class Paging implements java.io.Serializable { private int page = -1; private int count = -1; private String sinceId = ""; private String maxId = ""; private static final long serialVersionUID = -3285857427993796670L; public Paging() { } public Paging(int page) { setPage(page); } public Paging(String sinceId) { setSinceId(sinceId); } public Paging(int page, int count) { this(page); setCount(count); } public Paging(int page, String sinceId) { this(page); setSinceId(sinceId); } public Paging(int page, int count, String sinceId) { this(page, count); setSinceId(sinceId); } public Paging(int page, int count, String sinceId, String maxId) { this(page, count, sinceId); setMaxId(maxId); } public int getPage() { return page; } public void setPage(int page) { if (page < 1) { throw new IllegalArgumentException("page should be positive integer. passed:" + page); } this.page = page; } public int getCount() { return count; } public void setCount(int count) { if (count < 1) { throw new IllegalArgumentException("count should be positive integer. passed:" + count); } this.count = count; } public Paging count(int count) { setCount(count); return this; } public String getSinceId() { return sinceId; } public void setSinceId(String sinceId) { if (sinceId.length() > 0) { this.sinceId = sinceId; } else { throw new IllegalArgumentException("since_id is null. passed:" + sinceId); } } public Paging sinceId(String sinceId) { setSinceId(sinceId); return this; } public String getMaxId() { return maxId; } public void setMaxId(String maxId) { if (maxId.length() == 0) { throw new IllegalArgumentException("max_id is null. passed:" + maxId); } this.maxId = maxId; } public Paging maxId(String maxId) { setMaxId(maxId); return this; } }
Java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ch_linghu.fanfoudroid.weibo; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * A data class representing a Saved Search * * @author Yusuke Yamamoto - yusuke at mac.com * @since Weibo4J 2.0.8 */ public class SavedSearch extends WeiboResponse { private Date createdAt; private String query; private int position; private String name; private int id; private static final long serialVersionUID = 3083819860391598212L; /*package*/ SavedSearch(Response res) throws HttpException { super(res); init(res.asJSONObject()); } /*package*/ SavedSearch(Response res, JSONObject json) throws HttpException { super(res); init(json); } /*package*/ SavedSearch(JSONObject savedSearch) throws HttpException { init(savedSearch); } /*package*/ static List<SavedSearch> constructSavedSearches(Response res) throws HttpException { JSONArray json = res.asJSONArray(); List<SavedSearch> savedSearches; try { savedSearches = new ArrayList<SavedSearch>(json.length()); for(int i=0;i<json.length();i++){ savedSearches.add(new SavedSearch(res,json.getJSONObject(i))); } return savedSearches; } catch (JSONException jsone) { throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone); } } private void init(JSONObject savedSearch) throws HttpException { try { createdAt = parseDate(savedSearch.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); query = getString("query", savedSearch, true); name = getString("name", savedSearch, true); id = getInt("id", savedSearch); } catch (JSONException jsone) { throw new HttpException(jsone.getMessage() + ":" + savedSearch.toString(), jsone); } } public Date getCreatedAt() { return createdAt; } public String getQuery() { return query; } public int getPosition() { return position; } public String getName() { return name; } public int getId() { return id; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof SavedSearch)) return false; SavedSearch that = (SavedSearch) o; if (id != that.id) return false; if (position != that.position) return false; if (!createdAt.equals(that.createdAt)) return false; if (!name.equals(that.name)) return false; if (!query.equals(that.query)) return false; return true; } @Override public int hashCode() { int result = createdAt.hashCode(); result = 31 * result + query.hashCode(); result = 31 * result + position; result = 31 * result + name.hashCode(); result = 31 * result + id; return result; } @Override public String toString() { return "SavedSearch{" + "createdAt=" + createdAt + ", query='" + query + '\'' + ", position=" + position + ", name='" + name + '\'' + ", id=" + id + '}'; } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.util.Log; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.http.HttpClient; public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: is this a hack? setResult(RESULT_OK); addPreferencesFromResource(R.xml.preferences); } @Override protected void onResume() { super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { return super.onPreferenceTreeClick(preferenceScreen, preference); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if ( key.equalsIgnoreCase(Preferences.NETWORK_TYPE) ) { HttpClient httpClient = TwitterApplication.mApi.getHttpClient(); String type = sharedPreferences.getString(Preferences.NETWORK_TYPE, ""); if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) { Log.i("LDS", "Set proxy for cmwap mode."); httpClient.setProxy("10.0.0.172", 80, "http"); } else { Log.i("LDS", "No proxy."); httpClient.removeProxy(); } } } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import com.ch_linghu.fanfoudroid.R; import android.app.Activity; import android.app.AlertDialog; import android.content.ComponentName; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.view.LayoutInflater; import android.view.View; public class AboutDialog { public static void show(Activity activity) { View view = LayoutInflater.from(activity).inflate(R.layout.about, null); ComponentName comp = new ComponentName(activity, activity.getClass()); PackageInfo pinfo = null; try { pinfo = activity.getPackageManager().getPackageInfo(comp.getPackageName(), 0); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String title = String.format("%s ver.%s", activity.getString(R.string.app_name), pinfo.versionName); AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setView(view); builder.setCancelable(true); builder.setTitle(title); builder.setPositiveButton(R.string.about_label_ok, null); builder.create().show(); } }
Java
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity; import com.ch_linghu.fanfoudroid.weibo.SavedSearch; import com.ch_linghu.fanfoudroid.weibo.Trend; import com.commonsware.cwac.merge.MergeAdapter; public class SearchActivity extends WithHeaderActivity { private static final String TAG = SearchActivity.class.getSimpleName(); private static final int LOADING = 1; private static final int NETWORKERROR = 2; private static final int SUCCESS = 3; private EditText mSearchEdit; private ListView mSearchSectionList; private TextView trendsTitle; private TextView savedSearchTitle; private MergeAdapter mSearchSectionAdapter; private SearchAdapter trendsAdapter; private SearchAdapter savedSearchesAdapter; private ArrayList<SearchItem> trends; private ArrayList<SearchItem> savedSearch; private String initialQuery; private GenericTask trendsAndSavedSearchesTask; private TaskListener trendsAndSavedSearchesTaskListener = new TaskAdapter() { @Override public String getName() { return "trendsAndSavedSearchesTask"; } @Override public void onPreExecute(GenericTask task) { } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { refreshSearchSectionList(SearchActivity.SUCCESS); } else if (result == TaskResult.IO_ERROR) { refreshSearchSectionList(SearchActivity.NETWORKERROR); Toast.makeText( SearchActivity.this, getResources() .getString( R.string.login_status_network_or_connection_error), Toast.LENGTH_SHORT).show(); } } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate()..."); if (super._onCreate(savedInstanceState)) { setContentView(R.layout.search); initHeader(HEADER_STYLE_SEARCH); mSearchEdit = (EditText) findViewById(R.id.search_edit); mSearchEdit.setOnKeyListener(enterKeyHandler); trendsTitle = (TextView) getLayoutInflater().inflate( R.layout.search_section_header, null); trendsTitle .setText(getResources().getString(R.string.trends_title)); savedSearchTitle = (TextView) getLayoutInflater().inflate( R.layout.search_section_header, null); savedSearchTitle.setText(getResources().getString( R.string.saved_search_title)); mSearchSectionAdapter = new MergeAdapter(); mSearchSectionList = (ListView) findViewById(R.id.search_section_list); initSearchSectionList(); refreshSearchSectionList(SearchActivity.LOADING); doGetSavedSearches(); return true; } else { return false; } } @Override protected void onResume() { Log.i(TAG, "onResume()..."); super.onResume(); } private void doGetSavedSearches(){ if (trendsAndSavedSearchesTask != null && trendsAndSavedSearchesTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ trendsAndSavedSearchesTask = new TrendsAndSavedSearchesTask(); trendsAndSavedSearchesTask .setListener(trendsAndSavedSearchesTaskListener); trendsAndSavedSearchesTask.execute(); } } private void initSearchSectionList() { trends = new ArrayList<SearchItem>(); savedSearch = new ArrayList<SearchItem>(); trendsAdapter = new SearchAdapter(this); savedSearchesAdapter = new SearchAdapter(this); mSearchSectionAdapter.addView(savedSearchTitle); mSearchSectionAdapter.addAdapter(savedSearchesAdapter); mSearchSectionAdapter.addView(trendsTitle); mSearchSectionAdapter.addAdapter(trendsAdapter); mSearchSectionList.setAdapter(mSearchSectionAdapter); } /** * 辅助计算位置的类 * @author jmx * */ class PositionHelper{ /** * 返回指定位置属于哪一个小节 * @param position 绝对位置 * @return 小节的序号,0是第一小节,1是第二小节, -1为无效位置 */ public int getSectionIndex(int position){ int[] contentLength = new int[2]; contentLength[0] = savedSearchesAdapter.getCount(); contentLength[1] = trendsAdapter.getCount(); if (position > 0 && position < contentLength[0]+1){ return 0; } else if (position > contentLength[0]+1 && position < (contentLength[0]+contentLength[1]+1)+1){ return 1; } else { return -1; } } /** * 返回指定位置在自己所在小节的相对位置 * @param position 绝对位置 * @return 所在小节的相对位置,-1为无效位置 */ public int getRelativePostion(int position){ int[] contentLength = new int[2]; contentLength[0] = savedSearchesAdapter.getCount(); contentLength[1] = trendsAdapter.getCount(); int sectionIndex = getSectionIndex(position); int offset = 0; for (int i = 0; i < sectionIndex; ++i) { offset += contentLength[i] + 1; } return position - offset - 1; } } /** * flag: loading;network error;success */ PositionHelper pos_helper = new PositionHelper(); private void refreshSearchSectionList(int flag) { AdapterView.OnItemClickListener searchSectionListListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { MergeAdapter adapter = (MergeAdapter)(adapterView.getAdapter()); SearchAdapter subAdapter = (SearchAdapter)adapter.getAdapter(position); //计算针对subAdapter中的相对位置 int relativePos = pos_helper.getRelativePostion(position); SearchItem item = (SearchItem)(subAdapter.getItem(relativePos)); initialQuery = item.query; startSearch(); } }; if (flag == SearchActivity.LOADING) { mSearchSectionList.setOnItemClickListener(null); savedSearch.clear(); trends.clear(); savedSearchesAdapter.refresh(getString(R.string.search_loading)); trendsAdapter.refresh(getString(R.string.search_loading)); } else if (flag == SearchActivity.NETWORKERROR) { mSearchSectionList.setOnItemClickListener(null); savedSearch.clear(); trends.clear(); savedSearchesAdapter.refresh(getString(R.string.login_status_network_or_connection_error)); trendsAdapter.refresh(getString(R.string.login_status_network_or_connection_error)); } else { savedSearchesAdapter.refresh(savedSearch); trendsAdapter.refresh(trends); } if (flag == SearchActivity.SUCCESS) { mSearchSectionList .setOnItemClickListener(searchSectionListListener); } } @Override protected boolean startSearch() { if (!Utils.isEmpty(initialQuery)) { // 以下这个方法在7可用,在8就报空指针 // triggerSearch(initialQuery, null); Intent i = new Intent(this, SearchResultActivity.class); i.putExtra(SearchManager.QUERY, initialQuery); startActivity(i); } else if (Utils.isEmpty(initialQuery)) { Toast.makeText(this, getResources().getString(R.string.search_box_null), Toast.LENGTH_SHORT).show(); return false; } return false; } @Override protected void addSearchButton() { searchButton = (ImageButton) findViewById(R.id.search); searchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { initialQuery = mSearchEdit.getText().toString(); startSearch(); } }); } // 搜索框回车键判断 private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { initialQuery = mSearchEdit.getText().toString(); startSearch(); } return true; } return false; } }; private class TrendsAndSavedSearchesTask extends GenericTask { Trend[] trendsList; List<SavedSearch> savedSearchsList; @Override protected TaskResult _doInBackground(TaskParams... params) { try { trendsList = getApi().getTrends().getTrends(); savedSearchsList = getApi().getSavedSearches(); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } trends.clear(); savedSearch.clear(); for (int i = 0; i < trendsList.length; i++) { SearchItem item = new SearchItem(); item.name = trendsList[i].getName(); item.query = trendsList[i].getQuery(); trends.add(item); } for (int i = 0; i < savedSearchsList.size(); i++) { SearchItem item = new SearchItem(); item.name = savedSearchsList.get(i).getName(); item.query = savedSearchsList.get(i).getQuery(); savedSearch.add(item); } return TaskResult.OK; } } } class SearchItem { public String name; public String query; } class SearchAdapter extends BaseAdapter{ protected ArrayList<SearchItem> mSearchList; private Context mContext; protected LayoutInflater mInflater; protected StringBuilder mMetaBuilder; public SearchAdapter(Context context) { mSearchList = new ArrayList<SearchItem>(); mContext = context; mInflater = LayoutInflater.from(mContext); mMetaBuilder = new StringBuilder(); } public SearchAdapter(Context context, String prompt) { this(context); refresh(prompt); } public void refresh(ArrayList<SearchItem> searchList){ mSearchList = searchList; notifyDataSetChanged(); } public void refresh(String prompt){ SearchItem item = new SearchItem(); item.name = prompt; item.query = null; mSearchList.clear(); mSearchList.add(item); notifyDataSetChanged(); } @Override public int getCount() { return mSearchList.size(); } @Override public Object getItem(int position) { return mSearchList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.search_section_view, parent, false); TextView text = (TextView)view.findViewById(R.id.search_section_text); view.setTag(text); } else { view = convertView; } TextView text = (TextView)view.getTag(); SearchItem item = mSearchList.get(position); text.setText(item.name); return view; } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.EditText; import android.widget.TextView; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity; import com.ch_linghu.fanfoudroid.ui.module.TweetEdit; import com.ch_linghu.fanfoudroid.weibo.DirectMessage; //FIXME: 将WriteDmActivity和WriteActivity进行整合。 /** * 撰写私信界面 * @author lds * */ public class WriteDmActivity extends WithHeaderActivity { public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW"; public static final String EXTRA_TEXT = "text"; public static final String REPLY_ID = "reply_id"; private static final String TAG = "WriteActivity"; private static final String SIS_RUNNING_KEY = "running"; private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid"; // View private TweetEdit mTweetEdit; private EditText mTweetEditText; private TextView mProgressText; private Button mSendButton; //private AutoCompleteTextView mToEdit; private TextView mToEdit; // Task private GenericTask mSendTask; private TaskListener mSendTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { disableEntry(); updateProgress(getString(R.string.page_status_updating)); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mToEdit.setText(""); mTweetEdit.setText(""); updateProgress(""); enableEntry(); // 发送成功就直接关闭界面 finish(); } else if (result == TaskResult.NOT_FOLLOWED_ERROR) { updateProgress(getString(R.string.direct_meesage_status_the_person_not_following_you)); enableEntry(); } else if (result == TaskResult.IO_ERROR) { // TODO: 什么情况下会抛出IO_ERROR?需要给用户更为具体的失败原因 updateProgress(getString(R.string.page_status_unable_to_update)); enableEntry(); } } @Override public String getName() { return "DMSend"; } }; private FriendsAdapter mFriendsAdapter; // Adapter for To: recipient // autocomplete. private static final String EXTRA_USER = "user"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMSW"; public static Intent createIntent(String user) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!Utils.isEmpty(user)) { intent.putExtra(EXTRA_USER, user); } return intent; } // sub menu // protected void createInsertPhotoDialog() { // // final CharSequence[] items = { // getString(R.string.write_label_take_a_picture), // getString(R.string.write_label_choose_a_picture) }; // // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle(getString(R.string.write_label_insert_picture)); // builder.setItems(items, new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int item) { // // Toast.makeText(getApplicationContext(), items[item], // // Toast.LENGTH_SHORT).show(); // switch (item) { // case 0: // openImageCaptureMenu(); // break; // case 1: // openPhotoLibraryMenu(); // } // } // }); // AlertDialog alert = builder.create(); // alert.show(); // } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate."); if (super._onCreate(savedInstanceState)){ // init View setContentView(R.layout.write_dm); initHeader(HEADER_STYLE_WRITE); // Intent & Action & Extras Intent intent = getIntent(); Bundle extras = intent.getExtras(); // View mProgressText = (TextView) findViewById(R.id.progress_text); mTweetEditText = (EditText) findViewById(R.id.tweet_edit); TwitterDatabase db = getDb(); //FIXME: 暂时取消收件人自动完成功能 //mToEdit = (AutoCompleteTextView) findViewById(R.id.to_edit); //Cursor cursor = db.getFollowerUsernames(""); //// startManagingCursor(cursor); //mFriendsAdapter = new FriendsAdapter(this, cursor); //mToEdit.setAdapter(mFriendsAdapter); mToEdit = (TextView) findViewById(R.id.to_edit); // Update status mTweetEdit = new TweetEdit(mTweetEditText, (TextView) findViewById(R.id.chars_text)); mTweetEdit.setOnKeyListener(editEnterHandler); mTweetEdit .addTextChangedListener(new MyTextWatcher(WriteDmActivity.this)); // With extras if (extras != null) { String to = extras.getString(EXTRA_USER); if (!Utils.isEmpty(to)) { mToEdit.setText(to); mTweetEdit.requestFocus(); } } mSendButton = (Button) findViewById(R.id.send_button); mSendButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doSend(); } }); return true; }else{ return false; } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); mTweetEdit.updateCharsRemain(); } @Override protected void onPause() { super.onPause(); Log.i(TAG, "onPause."); } @Override protected void onRestart() { super.onRestart(); Log.i(TAG, "onRestart."); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.i(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.i(TAG, "onStop."); } @Override protected void onDestroy() { Log.i(TAG, "onDestroy."); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { // Doesn't really cancel execution (we let it continue running). // See the SendTask code for more details. mSendTask.cancel(true); } // Don't need to cancel FollowersTask (assuming it ends properly). super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } public static Intent createNewTweetIntent(String text) { Intent intent = new Intent(NEW_TWEET_ACTION); intent.putExtra(EXTRA_TEXT, text); return intent; } private class MyTextWatcher implements TextWatcher { private WriteDmActivity _activity; public MyTextWatcher(WriteDmActivity activity) { _activity = activity; } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub if (s.length() == 0) { } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } } private void doSend() { if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { String to = mToEdit.getText().toString(); String status = mTweetEdit.getText().toString(); if (!Utils.isEmpty(status) && !Utils.isEmpty(to)) { mSendTask = new DmSendTask(); mSendTask.setListener(mSendTaskListener); mSendTask.execute(); } else if (Utils.isEmpty(status)) { updateProgress(getString(R.string.direct_meesage_status_texting_is_null)); } else if (Utils.isEmpty(to)) { updateProgress(getString(R.string.direct_meesage_status_user_is_null)); } } } private class DmSendTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String user = mToEdit.getText().toString(); String text = mTweetEdit.getText().toString(); DirectMessage directMessage = getApi().sendDirectMessage(user, text); Dm dm = Dm.create(directMessage, true); // if (!Utils.isEmpty(dm.profileImageUrl)) { // // Fetch image to cache. // try { // getImageManager().put(dm.profileImageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } getDb().createDm(dm, false); } catch (HttpException e) { Log.i(TAG, e.getMessage()); // TODO: check is this is actually the case. return TaskResult.NOT_FOLLOWED_ERROR; } return TaskResult.OK; } } private static class FriendsAdapter extends CursorAdapter { public FriendsAdapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); mUserTextColumn = cursor .getColumnIndexOrThrow(StatusTable.FIELD_USER_SCREEN_NAME); } private LayoutInflater mInflater; private int mUserTextColumn; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater .inflate(R.layout.dropdown_item, parent, false); ViewHolder holder = new ViewHolder(); holder.userText = (TextView) view.findViewById(android.R.id.text1); view.setTag(holder); return view; } class ViewHolder { public TextView userText; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); holder.userText.setText(cursor.getString(mUserTextColumn)); } @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String filter = constraint == null ? "" : constraint.toString(); return TwitterApplication.mDb.getFollowerUsernames(filter); } @Override public String convertToString(Cursor cursor) { return cursor.getString(mUserTextColumn); } } private void enableEntry() { mTweetEdit.setEnabled(true); mSendButton.setEnabled(true); } private void disableEntry() { mTweetEdit.setEnabled(false); mSendButton.setEnabled(false); } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } private View.OnKeyListener editEnterHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { doSend(); } return true; } return false; } }; }
Java
package com.ch_linghu.fanfoudroid; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.data.db.MessageTable; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.ProfileImageCacheCallback; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity; import com.ch_linghu.fanfoudroid.weibo.DirectMessage; import com.ch_linghu.fanfoudroid.weibo.Paging; public class DmActivity extends WithHeaderActivity { private static final String TAG = "DmActivity"; // Views. private ListView mTweetList; private Adapter mAdapter; private Adapter mInboxAdapter; private Adapter mSendboxAdapter; Button inbox; Button sendbox; Button newMsg; private int mDMType; private static final int DM_TYPE_ALL = 0; private static final int DM_TYPE_INBOX = 1; private static final int DM_TYPE_SENDBOX = 2; private TextView mProgressText; // Tasks. private GenericTask mRetrieveTask; private GenericTask mDeleteTask; private TaskListener mDeleteTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_deleting)); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mAdapter.refresh(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmDeleteTask"; } }; private TaskListener mRetrieveTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_refreshing)); } @Override public void onProgressUpdate(GenericTask task, Object params) { draw(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = mPreferences.edit(); editor.putLong(Preferences.LAST_DM_REFRESH_KEY, Utils .getNowTime()); editor.commit(); draw(); goTop(); } else { // Do nothing. } // 刷新按钮停止旋转 refreshButton.clearAnimation(); updateProgress(""); } @Override public String getName() { return "DmRetrieve"; } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; private static final String EXTRA_USER = "user"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS"; public static Intent createIntent() { return createIntent(""); } public static Intent createIntent(String user) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!Utils.isEmpty(user)) { intent.putExtra(EXTRA_USER, user); } return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(R.layout.dm); initHeader(HEADER_STYLE_HOME); setHeaderTitle("我的私信"); // 绑定底部栏按钮onClick监听器 bindFooterButtonEvent(); mTweetList = (ListView) findViewById(R.id.tweet_list); mProgressText = (TextView) findViewById(R.id.progress_text); TwitterDatabase db = getDb(); // Mark all as read. db.markAllDmsRead(); setupAdapter(); // Make sure call bindFooterButtonEvent first boolean shouldRetrieve = false; long lastRefreshTime = mPreferences.getLong( Preferences.LAST_DM_REFRESH_KEY, 0); long nowTime = Utils.getNowTime(); long diff = nowTime - lastRefreshTime; Log.i(TAG, "Last refresh was " + diff + " ms ago."); if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.i(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } if (shouldRetrieve) { doRetrieve(); } // Want to be able to focus on the items with the trackball. // That way, we can navigate up and down by changing item focus. mTweetList.setItemsCanFocus(true); return true; }else{ return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } private static final String SIS_RUNNING_KEY = "running"; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onDestroy() { Log.i(TAG, "onDestroy."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { mRetrieveTask.cancel(true); } if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { mDeleteTask.cancel(true); } super.onDestroy(); } // UI helpers. private void bindFooterButtonEvent() { inbox = (Button) findViewById(R.id.inbox); sendbox = (Button) findViewById(R.id.sendbox); newMsg = (Button) findViewById(R.id.new_message); inbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_INBOX) { mDMType = DM_TYPE_INBOX; inbox.setEnabled(false); sendbox.setEnabled(true); mTweetList.setAdapter(mInboxAdapter); mInboxAdapter.refresh(); } } }); sendbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_SENDBOX) { mDMType = DM_TYPE_SENDBOX; inbox.setEnabled(true); sendbox.setEnabled(false); mTweetList.setAdapter(mSendboxAdapter); mSendboxAdapter.refresh(); } } }); newMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(DmActivity.this, WriteDmActivity.class); intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id startActivity(intent); } }); } private void setupAdapter() { Cursor cursor = getDb().fetchAllDms(-1); startManagingCursor(cursor); mAdapter = new Adapter(this, cursor); Cursor inboxCursor = getDb().fetchInboxDms(); startManagingCursor(inboxCursor); mInboxAdapter = new Adapter(this, inboxCursor); Cursor sendboxCursor = getDb().fetchSendboxDms(); startManagingCursor(sendboxCursor); mSendboxAdapter = new Adapter(this, sendboxCursor); mTweetList.setAdapter(mInboxAdapter); registerForContextMenu(mTweetList); inbox.setEnabled(false); } private class DmRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams...params) { List<DirectMessage> dmList; ArrayList<Dm> dms = new ArrayList<Dm>(); TwitterDatabase db = getDb(); //ImageManager imageManager = getImageManager(); String maxId = db.fetchMaxDmId(false); HashSet<String> imageUrls = new HashSet<String>(); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getDirectMessages(paging); } else { dmList = getApi().getDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, false); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } maxId = db.fetchMaxDmId(true); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getSentDirectMessages(paging); } else { dmList = getApi().getSentDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, true); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } db.addDms(dms, false); // if (isCancelled()) { // return TaskResult.CANCELLED; // } // // publishProgress(null); // // for (String imageUrl : imageUrls) { // if (!Utils.isEmpty(imageUrl)) { // // Fetch image to cache. // try { // imageManager.put(imageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } // // if (isCancelled()) { // return TaskResult.CANCELLED; // } // } return TaskResult.OK; } } private static class Adapter extends CursorAdapter { public Adapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); // TODO: 可使用: //DM dm = MessageTable.parseCursor(cursor); mUserTextColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME); mTextColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_TEXT); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL); mCreatedAtColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT); mIsSentColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT); } private LayoutInflater mInflater; private int mUserTextColumn; private int mTextColumn; private int mProfileImageUrlColumn; private int mIsSentColumn; private int mCreatedAtColumn; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.direct_message, parent, false); ViewHolder holder = new ViewHolder(); holder.userText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.metaText = (TextView) view .findViewById(R.id.tweet_meta_text); view.setTag(holder); return view; } class ViewHolder { public TextView userText; public TextView tweetText; public ImageView profileImage; public TextView metaText; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); int isSent = cursor.getInt(mIsSentColumn); String user = cursor.getString(mUserTextColumn); if (0 == isSent) { holder.userText.setText(context .getString(R.string.direct_message_label_from_prefix) + user); } else { holder.userText.setText(context .getString(R.string.direct_message_label_to_prefix) + user); } Utils.setTweetText(holder.tweetText, cursor.getString(mTextColumn)); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (!Utils.isEmpty(profileImageUrl)) { holder.profileImage .setImageBitmap(TwitterApplication.mProfileImageCacheManager .get(profileImageUrl, new ProfileImageCacheCallback(){ @Override public void refresh(String url, Bitmap bitmap) { Adapter.this.refresh(); } })); } try { holder.metaText.setText(Utils .getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER .parse(cursor.getString(mCreatedAtColumn)))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } } public void refresh() { getCursor().requery(); } } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除 // case OPTIONS_MENU_ID_REFRESH: // doRetrieve(); // return true; case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; } return super.onOptionsItemSelected(item); } private static final int CONTEXT_REPLY_ID = 0; private static final int CONTEXT_DELETE_ID = 1; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Cursor cursor = (Cursor) mAdapter.getItem(info.position); if (cursor == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTEXT_REPLY_ID: String user_id = cursor.getString(cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_ID)); Intent intent = WriteDmActivity.createIntent(user_id); startActivity(intent); return true; case CONTEXT_DELETE_ID: int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID); String id = cursor.getString(idIndex); doDestroy(id); return true; default: return super.onContextItemSelected(item); } } private void doDestroy(String id) { Log.i(TAG, "Attempting delete."); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mDeleteTask = new DmDeleteTask(); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } private class DmDeleteTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams...params) { TaskParams param = params[0]; try { String id = param.getString("id"); DirectMessage directMessage = getApi().destroyDirectMessage(id); Dm.create(directMessage, false); getDb().deleteDm(id); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } if (isCancelled()) { return TaskResult.CANCELLED; } return TaskResult.OK; } } public void doRetrieve() { Log.i(TAG, "Attempting retrieve."); // 旋转刷新按钮 animRotate(refreshButton); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mRetrieveTask = new DmRetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); } } public void goTop() { mTweetList.setSelection(0); } public void draw() { mAdapter.refresh(); mInboxAdapter.refresh(); mSendboxAdapter.refresh(); } private void updateProgress(String msg) { mProgressText.setText(msg); } }
Java
package com.ch_linghu.fanfoudroid.helper; import android.text.Spannable; import android.text.method.LinkMovementMethod; import android.text.method.MovementMethod; import android.view.MotionEvent; import android.widget.TextView; public class TestMovementMethod extends LinkMovementMethod { private double mY; private boolean mIsMoving = false; @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { /* int action = event.getAction(); if (action == MotionEvent.ACTION_MOVE) { double deltaY = mY - event.getY(); mY = event.getY(); Log.i("foo", deltaY + ""); if (Math.abs(deltaY) > 1) { mIsMoving = true; } } else if (action == MotionEvent.ACTION_DOWN) { mIsMoving = false; mY = event.getY(); } else if (action == MotionEvent.ACTION_UP) { boolean wasMoving = mIsMoving; mIsMoving = false; if (wasMoving) { return true; } } */ return super.onTouchEvent(widget, buffer, event); } public static MovementMethod getInstance() { if (sInstance == null) sInstance = new TestMovementMethod(); return sInstance; } private static TestMovementMethod sInstance; }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.helper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Html; import android.text.util.Linkify; import android.util.Log; import android.widget.TextView; import android.widget.TextView.BufferType; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; public class Utils { private static final String TAG = "Utils"; public static boolean isEmpty(String s) { return s == null || s.length() == 0; } private static HashMap<String, String> _userLinkMapping = new HashMap<String, String>(); public static String stringifyStream(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } return sb.toString(); } //Wed Dec 15 02:53:36 +0000 2010 public static final DateFormat TWITTER_DATE_FORMATTER = new SimpleDateFormat( "E MMM d HH:mm:ss Z yyyy", Locale.US); public static final DateFormat TWITTER_SEARCH_API_DATE_FORMATTER = new SimpleDateFormat( //TODO: Z -> z ? "E, d MMM yyyy HH:mm:ss Z", Locale.US); public static final Date parseDateTime(String dateString) { try { Log.d(TAG, String.format("in parseDateTime, dateString=%s", dateString)); return TWITTER_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter date string: " + dateString); return null; } } // Handle "yyyy-MM-dd'T'HH:mm:ss.SSS" from sqlite public static final Date parseDateTimeFromSqlite(String dateString) { try { Log.d(TAG, String.format("in parseDateTime, dateString=%s", dateString)); return TwitterDatabase.DB_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter date string: " + dateString); return null; } } public static final Date parseSearchApiDateTime(String dateString) { try { return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter search date string: " + dateString); return null; } } public static final DateFormat AGO_FULL_DATE_FORMATTER = new SimpleDateFormat( "yyyy-MM-dd HH:mm"); public static String getRelativeDate(Date date) { Date now = new Date(); String prefix = TwitterApplication.mContext.getString(R.string.tweet_created_at_beautify_prefix); String sec = TwitterApplication.mContext.getString(R.string.tweet_created_at_beautify_sec); String min = TwitterApplication.mContext.getString(R.string.tweet_created_at_beautify_min); String hour = TwitterApplication.mContext.getString(R.string.tweet_created_at_beautify_hour); String day = TwitterApplication.mContext.getString(R.string.tweet_created_at_beautify_day); String suffix = TwitterApplication.mContext.getString(R.string.tweet_created_at_beautify_suffix); // Seconds. long diff = (now.getTime() - date.getTime()) / 1000; if (diff < 0) { diff = 0; } if (diff < 60) { return diff + sec + suffix; } // Minutes. diff /= 60; if (diff < 60) { return prefix + diff + min + suffix; } // Hours. diff /= 60; if (diff < 24) { return prefix + diff + hour + suffix; } return AGO_FULL_DATE_FORMATTER.format(date); } public static long getNowTime() { return Calendar.getInstance().getTime().getTime(); } private static final Pattern NAME_MATCHER = Pattern.compile("@.+?\\s"); private static final Linkify.MatchFilter NAME_MATCHER_MATCH_FILTER = new Linkify.MatchFilter() { @Override public final boolean acceptMatch(final CharSequence s, final int start, final int end) { String name = s.subSequence(start+1, end).toString().trim(); boolean result = _userLinkMapping.containsKey(name); return result; } }; private static final Linkify.TransformFilter NAME_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() { @Override public String transformUrl(Matcher match, String url) { // TODO Auto-generated method stub String name = url.subSequence(1, url.length()).toString().trim(); return _userLinkMapping.get(name); } }; private static final String TWITTA_USER_URL = "twitta://users/"; public static void linkifyUsers(TextView view) { Linkify.addLinks(view, NAME_MATCHER, TWITTA_USER_URL, NAME_MATCHER_MATCH_FILTER, NAME_MATCHER_TRANSFORM_FILTER); } private static final Pattern TAG_MATCHER = Pattern.compile("#\\w+#"); private static final Linkify.TransformFilter TAG_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() { @Override public final String transformUrl(Matcher match, String url) { String result = url.substring(1, url.length()-1); return "%23" + result + "%23"; } }; private static final String TWITTA_SEARCH_URL = "twitta://search/"; public static void linkifyTags(TextView view) { Linkify.addLinks(view, TAG_MATCHER, TWITTA_SEARCH_URL, null, TAG_MATCHER_TRANSFORM_FILTER); } public static boolean isTrue(Bundle bundle, String key) { return bundle != null && bundle.containsKey(key) && bundle.getBoolean(key); } private static Pattern USER_LINK = Pattern.compile("@<a href=\"http:\\/\\/fanfou\\.com\\/(.*?)\" class=\"former\">(.*?)<\\/a>"); public static String preprocessText(String text){ //处理HTML格式返回的用户链接 Matcher m = USER_LINK.matcher(text); while(m.find()){ _userLinkMapping.put(m.group(2), m.group(1)); Log.d(TAG, String.format("Found mapping! %s=%s", m.group(2), m.group(1))); } //将User Link的连接去掉 StringBuffer sb = new StringBuffer(); m = USER_LINK.matcher(text); while(m.find()){ m.appendReplacement(sb, "@$2"); } m.appendTail(sb); return sb.toString(); } public static String getSimpleTweetText(String text){ return text.replaceAll("<.*?>", "") .replace("&lt;", "<") .replace("&gt;", ">") .replace("&nbsp;", " ") .replace("&amp;", "&") .replace("&quot;", "\""); } public static void setSimpleTweetText(TextView textView, String text){ String processedText = getSimpleTweetText(text); textView.setText(processedText); } public static void setTweetText(TextView textView, String text) { String processedText = preprocessText(text); textView.setText(Html.fromHtml(processedText), BufferType.SPANNABLE); Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES); Utils.linkifyUsers(textView); Utils.linkifyTags(textView); _userLinkMapping.clear(); } public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } private static Pattern PHOTO_PAGE_LINK = Pattern.compile("http://fanfou.com(/photo/[-a-zA-Z0-9+&@#%?=~_|!:,.;]*[-a-zA-Z0-9+&@#%=~_|])"); private static Pattern PHOTO_SRC_LINK = Pattern.compile("src=\"(http:\\/\\/photo\\.fanfou\\.com\\/.*?)\""); /** * 获得消息中的照片页面链接 * @param text 消息文本 * @param size 照片尺寸 * @return 照片页面的链接,若不存在,则返回null */ public static String getPhotoPageLink(String text, String size){ Matcher m = PHOTO_PAGE_LINK.matcher(text); if(m.find()){ String THUMBNAIL=TwitterApplication.mContext .getString(R.string.pref_photo_preview_type_thumbnail); String MIDDLE=TwitterApplication.mContext .getString(R.string.pref_photo_preview_type_middle); String ORIGINAL=TwitterApplication.mContext .getString(R.string.pref_photo_preview_type_original); if (size.equals(THUMBNAIL) || size.equals(MIDDLE)){ return "http://m.fanfou.com" + m.group(1); }else if (size.endsWith(ORIGINAL)){ return m.group(0); }else{ return null; } }else{ return null; } } /** * 获得照片页面中的照片链接 * @param pageHtml 照片页面文本 * @return 照片链接,若不存在,则返回null */ public static String getPhotoURL(String pageHtml){ Matcher m = PHOTO_SRC_LINK.matcher(pageHtml); if(m.find()){ return m.group(1); }else{ return null; } } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.helper; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.SoftReference; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; /** * Manages retrieval and storage of icon images. Use the put method to download * and store images. Use the get method to retrieve images from the manager. */ public class ImageManager implements ImageCache { private static final String TAG = "ImageManager"; // 饭否目前最大宽度支持496px, 超过则同比缩小 // 最大宽度为992px, 超过从中截取 public static final int DEFAULT_COMPRESS_QUALITY = 90; public static final int MAX_WIDTH = 496; public static final int MAX_HEIGHT = 992; private Context mContext; // In memory cache. private Map<String, SoftReference<Bitmap>> mCache; private HttpClient mClient; // MD5 hasher. private MessageDigest mDigest; // We want the requests to timeout quickly. // Tweets are processed in a batch and we don't want to stay on one too // long. private static final int CONNECTION_TIMEOUT_MS = 10 * 1000; private static final int SOCKET_TIMEOUT_MS = 10 * 1000; public ImageManager(Context context) { mContext = context; mCache = new HashMap<String, SoftReference<Bitmap>>(); mClient = new DefaultHttpClient(); try { mDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // This shouldn't happen. throw new RuntimeException("No MD5 algorithm."); } } public void setContext(Context context) { mContext = context; } private String getHashString(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for (byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } // MD5 hases are used to generate filenames based off a URL. private String getMd5(String url) { mDigest.update(url.getBytes()); return getHashString(mDigest); } // Looks to see if an image is in the file system. private Bitmap lookupFile(String url) { String hashedUrl = getMd5(url); FileInputStream fis = null; try { fis = mContext.openFileInput(hashedUrl); return BitmapFactory.decodeStream(fis); } catch (FileNotFoundException e) { // Not there. return null; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // Ignore. } } } } /** * Downloads a file * @param url * @return * @throws IOException */ public Bitmap fetchImage(String url) throws IOException { Log.i(TAG, "Fetching image: " + url); HttpGet get = new HttpGet(url); HttpConnectionParams.setConnectionTimeout(get.getParams(), CONNECTION_TIMEOUT_MS); HttpConnectionParams.setSoTimeout(get.getParams(), SOCKET_TIMEOUT_MS); HttpResponse response; try { response = mClient.execute(get); } catch (ClientProtocolException e) { Log.e(TAG, e.getMessage(), e); throw new IOException("Invalid client protocol."); } if (response.getStatusLine().getStatusCode() != 200) { throw new IOException("Non OK response: " + response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); BufferedInputStream bis = new BufferedInputStream(entity.getContent(), 8 * 1024); Bitmap bitmap = BitmapFactory.decodeStream(bis); bis.close(); return bitmap; } /** * 下载远程图片 -> 转换为Bitmap -> 写入缓存器. * @param url * @param quality image quality 1~100 * @throws IOException */ public void put(String url, int quality, boolean forceOverride) throws IOException { if (!forceOverride && contains(url)) { // Image already exists. return; // TODO: write to file if not present. } Bitmap bitmap = fetchImage(url); if (bitmap == null) { Log.w(TAG, "Retrieved bitmap is null."); } else { put(url, bitmap, quality); } } /** * 重载 put(String url, int quality) * @param url * @throws IOException */ public void put(String url) throws IOException { put(url, DEFAULT_COMPRESS_QUALITY, false); } /** * 将本地File -> 转换为Bitmap -> 写入缓存器. * 如果图片大小超过MAX_WIDTH/MAX_HEIGHT, 则将会对图片缩放. * * @param file * @param quality 图片质量(0~100) * @param forceOverride * @throws IOException */ public void put(File file, int quality, boolean forceOverride) throws IOException { if (!file.exists()) { Log.w(TAG, file.getName() + " is not exists."); return; } if (!forceOverride && contains(file.getPath())) { // Image already exists. Log.i(TAG, file.getName() + " is exists"); return; // TODO: write to file if not present. } Bitmap bitmap = BitmapFactory.decodeFile(file.getPath()); bitmap = resizeBitmap(bitmap, MAX_WIDTH, MAX_HEIGHT); if (bitmap == null) { Log.w(TAG, "Retrieved bitmap is null."); } else { put(file.getPath(), bitmap, quality); } } /** * 将Bitmap写入缓存器. * @param filePath file path * @param bitmap * @param quality 1~100 */ public void put(String file, Bitmap bitmap, int quality) { synchronized (this) { mCache.put(file, new SoftReference<Bitmap>(bitmap)); } writeFile(file, bitmap, quality); } /** * 重载 put(String file, Bitmap bitmap, int quality) * @param filePath file path * @param bitmap * @param quality 1~100 */ @Override public void put(String file, Bitmap bitmap) { put(file, bitmap, DEFAULT_COMPRESS_QUALITY); } /** * 将Bitmap写入本地缓存文件. * @param file URL/PATH * @param bitmap * @param quality */ private void writeFile(String file, Bitmap bitmap, int quality) { if (bitmap == null) { Log.w(TAG, "Can't write file. Bitmap is null."); return; } String hashedUrl = getMd5(file); FileOutputStream fos; try { fos = mContext.openFileOutput(hashedUrl, Context.MODE_PRIVATE); } catch (FileNotFoundException e) { Log.w(TAG, "Error creating file."); return; } // image is too small if (bitmap.getWidth() < 100 && bitmap.getHeight() < 100) { quality = 100; } Log.i(TAG, "Writing file: " + hashedUrl); bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos); try { fos.close(); } catch (IOException e) { Log.w(TAG, "Could not close file."); } } public Bitmap get(File file) { return get(file.getPath()); } /** * 从缓存器中读取文件 * @param file file URL/file PATH * @param bitmap * @param quality */ public Bitmap get(String file) { SoftReference<Bitmap> ref; Bitmap bitmap; // Look in memory first. synchronized (this) { ref = mCache.get(file); } if (ref != null) { bitmap = ref.get(); if (bitmap != null) { return bitmap; } } // Now try file. bitmap = lookupFile(file); if (bitmap != null) { synchronized (this) { mCache.put(file, new SoftReference<Bitmap>(bitmap)); } return bitmap; } //TODO: why? //upload: see profileImageCacheManager line 96 Log.i(TAG, "Image is missing: " + file); // return the default photo return mDefaultBitmap; } public boolean contains(String url) { return get(url) != mDefaultBitmap; } public void clear() { String[] files = mContext.fileList(); for (String file : files) { mContext.deleteFile(file); } synchronized (this) { mCache.clear(); } } public void cleanup(HashSet<String> keepers) { String[] files = mContext.fileList(); HashSet<String> hashedUrls = new HashSet<String>(); for (String imageUrl : keepers) { hashedUrls.add(getMd5(imageUrl)); } for (String file : files) { if (!hashedUrls.contains(file)) { Log.i(TAG, "Deleting unused file: " + file); mContext.deleteFile(file); } } } /** * Compress and resize the Image * @param targetFile * @param quality * @return * @throws IOException */ public File compressImage(File targetFile, int quality) throws IOException { put(targetFile, quality, true); // compress, resize, store String filePath = getMd5(targetFile.getPath()); File compressedImage = mContext.getFileStreamPath(filePath); return compressedImage; } /** * 保持长宽比缩小Bitmap * * @param bitmap * @param maxWidth * @param maxHeight * @param quality 1~100 * @return */ public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) { int originWidth = bitmap.getWidth(); int originHeight = bitmap.getHeight(); // no need to resize if (originWidth < maxWidth && originHeight < maxHeight) { return bitmap; } int width = originWidth; int height = originHeight; // 若图片过宽, 则保持长宽比缩放图片 if (originWidth > maxWidth) { width = maxWidth; double i = originWidth * 1.0 / maxWidth; height = (int) Math.floor(originHeight / i); bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false); } // 若图片过长, 则从上端截取 if (height > maxHeight) { height = maxHeight; bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height); } // Log.i(TAG, width + " width"); // Log.i(TAG, height + " height"); return bitmap; } }
Java
package com.ch_linghu.fanfoudroid.helper; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; public interface ImageCache { public static Bitmap mDefaultBitmap = Utils.drawableToBitmap(TwitterApplication.mContext.getResources().getDrawable(R.drawable.user_default_photo)); public Bitmap get(String url); public void put(String url, Bitmap bitmap); }
Java
package com.ch_linghu.fanfoudroid.helper; import android.graphics.Bitmap; public interface ProfileImageCacheCallback { void refresh(String url, Bitmap bitmap); }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.helper; public class Preferences { public static final String USERNAME_KEY = "username"; public static final String PASSWORD_KEY = "password"; public static final String CHECK_UPDATES_KEY = "check_updates"; public static final String CHECK_UPDATE_INTERVAL_KEY = "check_update_interval"; public static final String VIBRATE_KEY = "vibrate"; public static final String TIMELINE_ONLY_KEY = "timeline_only"; public static final String REPLIES_ONLY_KEY = "replies_only"; public static final String DM_ONLY_KEY = "dm_only"; public static String RINGTONE_KEY = "ringtone"; public static final String RINGTONE_DEFAULT_KEY = "content://settings/system/notification_sound"; public static final String LAST_TWEET_REFRESH_KEY = "last_tweet_refresh"; public static final String LAST_DM_REFRESH_KEY = "last_dm_refresh"; public static final String LAST_FOLLOWERS_REFRESH_KEY = "last_followers_refresh"; public static final String TWITTER_ACTIVITY_STATE_KEY = "twitter_activity_state"; public static final String USE_PROFILE_IMAGE = "use_profile_image"; public static final String PHOTO_PREVIEW = "photo_preview"; public static final String FORCE_SHOW_ALL_IMAGE = "force_show_all_image"; public static final String RT_PREFIX_KEY = "rt_prefix"; public static final String RT_INSERT_APPEND = "rt_insert_append"; //转发时光标放置在开始还是结尾 public static final String NETWORK_TYPE = "network_type"; //DEBUG标记 public static final String DEBUG="debug"; //当前用户相关信息 public static final String CURRENT_USER_ID="current_user_id"; public static final String CURRENT_USER_SCREEN_NAME="current_user_screenname"; }
Java
package com.ch_linghu.fanfoudroid.helper; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import android.graphics.Bitmap; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; public class ProfileImageCacheManager { private static final String TAG="ProfileImageCacheManager"; private ImageManager mImageManager = new ImageManager(TwitterApplication.mContext); private ArrayList<String> mUrlList = new ArrayList<String>(); private HashMap<String, ProfileImageCacheCallback> mCallbackMap = new HashMap<String, ProfileImageCacheCallback>(); private GenericTask mTask; private TaskListener mTaskListener = new TaskAdapter(){ @Override public String getName() { return "GetProfileImage"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); if (result == TaskResult.OK){ //如果还有没处理完的,再次启动Task继续处理 if (mUrlList.size() != 0){ doGetImage(null); } } } @Override public void onProgressUpdate(GenericTask task, Object param) { super.onProgressUpdate(task, param); TaskParams p = (TaskParams)param; String url = (String)p.get("url"); Bitmap bitmap = (Bitmap)p.get("bitmap"); ProfileImageCacheCallback callback = mCallbackMap.get(url); if (callback != null){ callback.refresh(url, bitmap); } mCallbackMap.remove(url); } }; public Bitmap get(String url, ProfileImageCacheCallback callback){ Bitmap bitmap = mImageManager.get(url); if(bitmap == ImageCache.mDefaultBitmap){ //bitmap不存在,启动Task进行下载 mCallbackMap.put(url, callback); doGetImage(url); } return bitmap; } //Low-level interface to get ImageManager public ImageManager getImageManager(){ return mImageManager; } private void putUrl(String url){ synchronized(mUrlList){ mUrlList.add(url); } } private void doGetImage(String url){ if (url != null){ putUrl(url); } if (mTask != null && mTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mTask = new GetImageTask(); mTask.setListener(mTaskListener); mTask.execute(); } } private class GetImageTask extends GenericTask{ @Override protected TaskResult _doInBackground(TaskParams... params) { String url = null; if (mUrlList.size() > 0){ synchronized(mUrlList){ url = mUrlList.get(0); mUrlList.remove(0); } try { mImageManager.put(url); } catch (IOException e) { Log.e(TAG, url + " get failed!"); } TaskParams p = new TaskParams(); p.put("url", url); p.put("bitmap", mImageManager.get(url)); publishProgress(p); } return TaskResult.OK; } } }
Java
package com.ch_linghu.fanfoudroid.helper; import java.util.HashMap; import android.graphics.Bitmap; public class MemoryImageCache implements ImageCache { private HashMap<String, Bitmap> mCache; public MemoryImageCache() { mCache = new HashMap<String, Bitmap>(); } @Override public Bitmap get(String url) { synchronized(this) { Bitmap bitmap = mCache.get(url); if (bitmap == null){ return mDefaultBitmap; }else{ return bitmap; } } } @Override public void put(String url, Bitmap bitmap) { synchronized(this) { mCache.put(url, bitmap); } } public void putAll(MemoryImageCache imageCache) { synchronized(this) { // TODO: is this thread safe? mCache.putAll(imageCache.mCache); } } }
Java
package com.ch_linghu.fanfoudroid.helper; import android.app.Activity; import android.content.Intent; import android.widget.Toast; import com.ch_linghu.fanfoudroid.LoginActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.http.HttpAuthException; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.http.HttpServerException; import com.ch_linghu.fanfoudroid.weibo.RefuseError; public class ExceptionHandler { private Activity mActivity; public ExceptionHandler(Activity activity) { mActivity = activity; } public void handle(HttpException e) { Throwable cause = e.getCause(); if (null == cause) return; // Handle Different Exception if (cause instanceof HttpAuthException) { // 用户名/密码错误 Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show(); Intent intent = new Intent(mActivity, LoginActivity.class); mActivity.startActivity(intent); // redirect to the login activity } else if (cause instanceof HttpServerException) { // 服务器暂时无法响应 Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show(); } else if (cause instanceof HttpAuthException) { //FIXME: 集中处理用户名/密码验证错误,返回到登录界面 } else if (cause instanceof HttpRefusedException) { // 服务器拒绝请求,如没有权限查看某用户信息 RefuseError error = ((HttpRefusedException) cause).getError(); switch (error.getErrorCode()) { // TODO: finish it case -1: default: Toast.makeText(mActivity, error.getMessage(), Toast.LENGTH_LONG).show(); break; } } } private void handleCause() { } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.text.ClipboardManager; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.helper.ImageCache; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.ProfileImageCacheCallback; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpAuthException; import com.ch_linghu.fanfoudroid.http.HttpClient; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.http.Response; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity; public class StatusActivity extends WithHeaderActivity { private static final String TAG = "StatusActivity"; private static final String SIS_RUNNING_KEY = "running"; private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid"; private static final String EXTRA_TWEET = "tweet"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.STATUS"; static final private int CONTEXT_REFRESH_ID = 0x0001; static final private int CONTEXT_CLIPBOARD_ID = 0x0002; static final private int CONTEXT_DELETE_ID = 0x0003; // Task TODO: tasks private GenericTask mStatusTask; private GenericTask mPhotoTask; // TODO: 压缩图片,提供获取图片的过程中可取消获取 private GenericTask mFavTask; private GenericTask mDeleteTask; private TaskListener mStatusTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { showReplyStatus(replyTweet); StatusActivity.this.refreshButton.clearAnimation(); } @Override public String getName() { // TODO Auto-generated method stub return "GetStatus"; } }; private TaskListener mPhotoTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { status_photo.setImageBitmap(mPhotoBitmap); } else { status_photo.setVisibility(View.GONE); } StatusActivity.this.refreshButton.clearAnimation(); } @Override public String getName() { // TODO Auto-generated method stub return "GetPhoto"; } }; private TaskListener mFavTaskListener = new TaskAdapter() { @Override public String getName() { return "FavoriteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onFavSuccess(); } else if (result == TaskResult.IO_ERROR) { onFavFailure(); } } }; private TaskListener mDeleteTaskListener = new TaskAdapter() { @Override public String getName() { return "DeleteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onDeleteSuccess(); } else if (result == TaskResult.IO_ERROR) { onDeleteFailure(); } } }; // View private TextView tweet_screen_name; private TextView tweet_text; private TextView tweet_user_info; private ImageView profile_image; private TextView tweet_source; private TextView tweet_created_at; private ImageButton btn_person_more; private ImageView status_photo = null; // if exists private ViewGroup reply_wrap; private TextView reply_status_text = null; // if exists private TextView reply_status_date = null; // if exists private ImageButton tweet_fav; private Tweet tweet = null; private Tweet replyTweet = null; // if exists private HttpClient mClient; private Bitmap mPhotoBitmap = ImageCache.mDefaultBitmap; // if exists public static Intent createIntent(Tweet tweet) { Intent intent = new Intent(LAUNCH_ACTION); intent.putExtra(EXTRA_TWEET, tweet); return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { mClient = getApi().getHttpClient(); // Intent & Action & Extras Intent intent = getIntent(); String action = intent.getAction(); Bundle extras = intent.getExtras(); // Must has extras if (null == extras) { Log.e(TAG, this.getClass().getName() + " must has extras."); finish(); return false; } // init View setContentView(R.layout.status); initHeader(HEADER_STYLE_BACK); // View tweet_screen_name = (TextView) findViewById(R.id.tweet_screen_name); tweet_user_info = (TextView) findViewById(R.id.tweet_user_info); tweet_text = (TextView) findViewById(R.id.tweet_text); tweet_source = (TextView) findViewById(R.id.tweet_source); profile_image = (ImageView) findViewById(R.id.profile_image); tweet_created_at = (TextView) findViewById(R.id.tweet_created_at); btn_person_more = (ImageButton) findViewById(R.id.person_more); tweet_fav = (ImageButton) findViewById(R.id.tweet_fav); reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap); reply_status_text = (TextView) findViewById(R.id.reply_status_text); reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at); status_photo = (ImageView) findViewById(R.id.status_photo); // Set view with intent data this.tweet = extras.getParcelable(EXTRA_TWEET); draw(); // 绑定监听器 refreshButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doGetStatus(tweet.id, false); } }); bindFooterBarListener(); bindReplyViewListener(); return true; } else { return false; } } private void bindFooterBarListener() { // person_more btn_person_more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = ProfileActivity.createIntent(tweet.userId); startActivity(intent); } }); // Footer bar TextView footer_btn_share = (TextView) findViewById(R.id.footer_btn_share); TextView footer_btn_reply = (TextView) findViewById(R.id.footer_btn_reply); TextView footer_btn_retweet = (TextView) findViewById(R.id.footer_btn_retweet); TextView footer_btn_fav = (TextView) findViewById(R.id.footer_btn_fav); TextView footer_btn_more = (TextView) findViewById(R.id.footer_btn_more); // 分享 footer_btn_share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra( Intent.EXTRA_TEXT, String.format("@%s %s", tweet.screenName, Utils.getSimpleTweetText(tweet.text))); startActivity(Intent.createChooser(intent, getString(R.string.cmenu_share))); } }); // 回复 footer_btn_reply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewReplyIntent( tweet.screenName, tweet.id); startActivity(intent); } }); // 转发 footer_btn_retweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewRepostIntent( StatusActivity.this, tweet.text, tweet.screenName, tweet.id); startActivity(intent); } }); // 收藏/取消收藏 footer_btn_fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (tweet.favorited.equals("true")) { doFavorite("del", tweet.id); } else { doFavorite("add", tweet.id); } } }); // TODO: 更多操作 registerForContextMenu(footer_btn_more); footer_btn_more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openContextMenu(v); } }); } private void bindReplyViewListener() { // 点击回复消息打开新的Status界面 OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { if (!Utils.isEmpty(tweet.inReplyToStatusId)) { if (replyTweet == null) { Log.w(TAG, "Selected item not available."); } else { launchActivity(StatusActivity.createIntent(replyTweet)); } } } }; reply_wrap.setOnClickListener(listener); } @Override protected void onPause() { super.onPause(); Log.i(TAG, "onPause."); } @Override protected void onRestart() { super.onRestart(); Log.i(TAG, "onRestart."); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.i(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.i(TAG, "onStop."); } @Override protected void onDestroy() { Log.i(TAG, "onDestroy."); if (mStatusTask != null && mStatusTask.getStatus() == GenericTask.Status.RUNNING) { mStatusTask.cancel(true); } if (mPhotoTask != null && mPhotoTask.getStatus() == GenericTask.Status.RUNNING) { mPhotoTask.cancel(true); } if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } super.onDestroy(); } private ProfileImageCacheCallback callback = new ProfileImageCacheCallback() { @Override public void refresh(String url, Bitmap bitmap) { profile_image.setImageBitmap(bitmap); } }; private void draw() { Log.i(TAG, "draw"); String PHOTO_PREVIEW_TYPE_NONE = getString(R.string.pref_photo_preview_type_none); String PHOTO_PREVIEW_TYPE_THUMBNAIL = getString(R.string.pref_photo_preview_type_thumbnail); String PHOTO_PREVIEW_TYPE_MIDDLE = getString(R.string.pref_photo_preview_type_middle); String PHOTO_PREVIEW_TYPE_ORIGINAL = getString(R.string.pref_photo_preview_type_original); SharedPreferences pref = getPreferences(); String photoPreviewSize = pref.getString(Preferences.PHOTO_PREVIEW, PHOTO_PREVIEW_TYPE_ORIGINAL); boolean forceShowAllImage = pref.getBoolean( Preferences.FORCE_SHOW_ALL_IMAGE, false); tweet_screen_name.setText(tweet.screenName); Utils.setTweetText(tweet_text, tweet.text); tweet_created_at.setText(Utils.getRelativeDate(tweet.createdAt)); tweet_source.setText(getString(R.string.tweet_source_prefix) + tweet.source); tweet_user_info.setText(tweet.userId); boolean isFav = (tweet.favorited.equals("true")) ? true : false; tweet_fav.setEnabled(isFav); // Bitmap mProfileBitmap = // TwitterApplication.mImageManager.get(tweet.profileImageUrl); profile_image .setImageBitmap(TwitterApplication.mProfileImageCacheManager .get(tweet.profileImageUrl, callback)); // has photo if (!photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_NONE)) { String photoLink; boolean isPageLink = false; if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_THUMBNAIL)) { photoLink = tweet.thumbnail_pic; } else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_MIDDLE)) { photoLink = tweet.bmiddle_pic; } else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_ORIGINAL)) { photoLink = tweet.original_pic; } else { Log.e(TAG, "Invalid Photo Preview Size Type"); photoLink = ""; } // 如果选用了强制显示则再尝试分析图片链接 if (forceShowAllImage) { photoLink = Utils .getPhotoPageLink(tweet.text, photoPreviewSize); isPageLink = true; } if (!Utils.isEmpty(photoLink)) { status_photo.setVisibility(View.VISIBLE); status_photo.setImageBitmap(mPhotoBitmap); doGetPhoto(photoLink, isPageLink); } } else { status_photo.setVisibility(View.GONE); } // has reply if (!Utils.isEmpty(tweet.inReplyToStatusId)) { ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap); reply_wrap.setVisibility(View.VISIBLE); reply_status_text = (TextView) findViewById(R.id.reply_status_text); reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at); doGetStatus(tweet.inReplyToStatusId, true); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mStatusTask != null && mStatusTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } private String fetchWebPage(String url) throws HttpException { Log.i(TAG, "Fetching WebPage: " + url); Response res = mClient.get(url); return res.asString(); } private Bitmap fetchPhotoBitmap(String url) throws HttpException, IOException { Log.i(TAG, "Fetching Photo: " + url); Response res = mClient.get(url); InputStream is = res.asStream(); Bitmap bitmap = BitmapFactory.decodeStream(is); is.close(); return bitmap; } private void doGetStatus(String status_id, boolean isReply) { Log.i(TAG, "Attempting get status task."); // 旋转刷新按钮 animRotate(refreshButton); if (mStatusTask != null && mStatusTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mStatusTask = new GetStatusTask(); mStatusTask.setListener(mStatusTaskListener); TaskParams params = new TaskParams(); if (isReply) { params.put("reply_id", status_id); } mStatusTask.execute(params); } } private class GetStatusTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; com.ch_linghu.fanfoudroid.weibo.Status status; try { String reply_id = param.getString("reply_id"); if (!Utils.isEmpty(reply_id)) { // 首先查看是否在数据库中,如不在再去获取 replyTweet = getDb().queryTweet(reply_id, -1); if (replyTweet == null) { status = getApi().showStatus(reply_id); replyTweet = Tweet.create(status); } } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } private void doGetPhoto(String photoPageURL, boolean isPageLink) { // 旋转刷新按钮 animRotate(refreshButton); if (mPhotoTask != null && mPhotoTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mPhotoTask = new GetPhotoTask(); mPhotoTask.setListener(mPhotoTaskListener); TaskParams params = new TaskParams(); params.put("photo_url", photoPageURL); params.put("is_page_link", isPageLink); mPhotoTask.execute(params); } } private class GetPhotoTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; try { String photoURL = param.getString("photo_url"); boolean isPageLink = param.getBoolean("is_page_link"); if (!Utils.isEmpty(photoURL)) { if (isPageLink) { String pageHtml = fetchWebPage(photoURL); String photoSrcURL = Utils.getPhotoURL(pageHtml); if (photoSrcURL != null) { mPhotoBitmap = fetchPhotoBitmap(photoSrcURL); } } else { mPhotoBitmap = fetchPhotoBitmap(photoURL); } } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } catch (IOException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } private void showReplyStatus(Tweet tweet) { if (tweet != null) { String text = tweet.screenName + " : " + tweet.text; Utils.setSimpleTweetText(reply_status_text, text); reply_status_date.setText(Utils.getRelativeDate(tweet.createdAt)); } else { String msg = MessageFormat.format( getString(R.string.status_status_reply_cannot_display), this.tweet.inReplyToScreenName); reply_status_text.setText(msg); } } public void onDeleteFailure() { Log.e(TAG, "Delete failed"); } public void onDeleteSuccess() { finish(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { if (!Utils.isEmpty(id)) { Log.i(TAG, "doFavorite."); mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setListener(mFavTaskListener); TaskParams param = new TaskParams(); param.put("action", action); param.put("id", id); mFavTask.execute(param); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); if (((TweetCommonTask.FavoriteTask) mFavTask).getType().equals( TweetCommonTask.FavoriteTask.TYPE_ADD)) { tweet.favorited = "true"; tweet_fav.setEnabled(true); } else { tweet.favorited = "false"; tweet_fav.setEnabled(false); } } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } private void doDelete(String id) { if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mDeleteTask = new TweetCommonTask.DeleteTask(this); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case CONTEXT_REFRESH_ID: doGetStatus(tweet.id, false); return true; case CONTEXT_CLIPBOARD_ID: ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(Utils.getSimpleTweetText(tweet.text)); return true; case CONTEXT_DELETE_ID: doDelete(tweet.id); return true; } return super.onContextItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderIcon(android.R.drawable.ic_menu_more); menu.setHeaderTitle(getString(R.string.cmenu_more)); menu.add(0, CONTEXT_REFRESH_ID, 0, R.string.omenu_refresh); menu.add(0, CONTEXT_CLIPBOARD_ID, 0, R.string.cmenu_clipboard); if (tweet.userId.equals(TwitterApplication.getMyselfId())) { menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } } }
Java
package com.ch_linghu.fanfoudroid; import java.util.List; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; import com.ch_linghu.fanfoudroid.weibo.Paging; public class FollowingActivity extends UserArrayBaseActivity { private ListView mUserList; private UserArrayAdapter mAdapter; private String userId; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING"; private static final String USER_ID = "userId"; private int currentPage=1; String myself=""; @Override protected boolean _onCreate(Bundle savedInstanceState) { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { this.userId = extras.getString(USER_ID); } else { // 获取登录用户id // SharedPreferences preferences = PreferenceManager // .getDefaultSharedPreferences(this); // userId = preferences.getString(Preferences.CURRENT_USER_ID, // TwitterApplication.mApi.getUserId()); userId=TwitterApplication.getMyselfId(); } Uri data = intent.getData(); if (data != null) { userId = data.getLastPathSegment(); } if(super._onCreate(savedInstanceState)){ myself = TwitterApplication.getMyselfId(); if(getUserId()==myself){ setHeaderTitle("我关注的人"); } return true; }else{ return false; } } /* * 添加取消关注按钮 * @see com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo) */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if(getUserId()==myself){ AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); menu.add(0,CONTENT_DEL_FRIEND,0,getResources().getString(R.string.cmenu_user_addfriend_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_friend_suffix)); } } public static Intent createIntent(String userId) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); return intent; } @Override public Paging getNextPage() { currentPage+=1; return new Paging(currentPage); } @Override protected String getUserId() { return this.userId; } @Override public Paging getCurrentPage() { return new Paging(this.currentPage); } @Override protected List<com.ch_linghu.fanfoudroid.weibo.User> getUsers( String userId, Paging page) throws HttpException { return getApi().getFriendsStatuses(userId, page); } }
Java
package com.ch_linghu.fanfoudroid; import java.util.HashSet; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.preference.PreferenceManager; import android.widget.Toast; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.ProfileImageCacheManager; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.weibo.Configuration; import com.ch_linghu.fanfoudroid.weibo.User; import com.ch_linghu.fanfoudroid.weibo.Weibo; import org.acra.*; import org.acra.annotation.*; @ReportsCrashes(formKey="dHowMk5LMXQweVJkWGthb1E1T1NUUHc6MQ", mode = ReportingInteractionMode.NOTIFICATION, resNotifTickerText = R.string.crash_notif_ticker_text, resNotifTitle = R.string.crash_notif_title, resNotifText = R.string.crash_notif_text, resNotifIcon = android.R.drawable.stat_notify_error, // optional. default is a warning sign resDialogText = R.string.crash_dialog_text, resDialogIcon = android.R.drawable.ic_dialog_info, //optional. default is a warning sign resDialogTitle = R.string.crash_dialog_title, // optional. default is your application name resDialogCommentPrompt = R.string.crash_dialog_comment_prompt, // optional. when defined, adds a user text field input with this text resource as a label resDialogOkToast = R.string.crash_dialog_ok_toast // optional. displays a Toast message when the user accepts to send a report. ) public class TwitterApplication extends Application { public static final String TAG = "TwitterApplication"; // public static ImageManager mImageManager; public static ProfileImageCacheManager mProfileImageCacheManager; public static TwitterDatabase mDb; public static Weibo mApi; // new API public static Context mContext; public static SharedPreferences mPref; public static int networkType = 0; private final static boolean DEBUG = Configuration.getDebug(); // FIXME:获取登录用户id, 据肉眼观察,刚注册的用户系统分配id都是~开头的,因为不知道 // 用户何时去修改这个ID,目前只有把所有以~开头的ID在每次需要UserId时都去服务器 // 取一次数据,看看新的ID是否已经设定,判断依据是是否以~开头。这么判断会把有些用户 // 就是把自己ID设置的以~开头的造成,每次都需要去服务器取数。 // 只是简单处理了mPref没有CURRENT_USER_ID的情况,因为用户在登陆时,肯定会记一个CURRENT_USER_ID // 到mPref. private static void fetchMyselfInfo() { User myself; try { myself = TwitterApplication.mApi.showUser(TwitterApplication.mApi.getUserId()); TwitterApplication.mPref.edit().putString( Preferences.CURRENT_USER_ID, myself.getId()); TwitterApplication.mPref.edit().putString( Preferences.CURRENT_USER_SCREEN_NAME, myself.getScreenName()); TwitterApplication.mPref.edit().commit(); } catch (HttpException e) { e.printStackTrace(); } } public static String getMyselfId() { if (!mPref.contains(Preferences.CURRENT_USER_ID) || mPref.getString(Preferences.CURRENT_USER_ID, "~") .startsWith("~")) { fetchMyselfInfo(); } return mPref.getString(Preferences.CURRENT_USER_ID, "~"); } public static String getMyselfName() { if (!mPref.contains(Preferences.CURRENT_USER_ID) || !mPref.contains(Preferences.CURRENT_USER_SCREEN_NAME) || mPref.getString(Preferences.CURRENT_USER_ID, "~") .startsWith("~")) { fetchMyselfInfo(); } return mPref.getString(Preferences.CURRENT_USER_SCREEN_NAME, ""); } @Override public void onCreate() { // FIXME: StrictMode类在1.6以下的版本中没有,会导致类加载失败。 // 因此将这些代码设成关闭状态,仅在做性能调试时才打开。 // //NOTE: StrictMode模式需要2.3+ API支持。 // if (DEBUG){ // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() // .detectAll() // .penaltyLog() // .build()); // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() // .detectAll() // .penaltyLog() // .build()); // } super.onCreate(); mContext = this.getApplicationContext(); // mImageManager = new ImageManager(this); mProfileImageCacheManager = new ProfileImageCacheManager(); mApi = new Weibo(); mDb = TwitterDatabase.getInstance(this); mPref = PreferenceManager.getDefaultSharedPreferences(this); String username = mPref.getString(Preferences.USERNAME_KEY, ""); String password = mPref.getString(Preferences.PASSWORD_KEY, ""); if (Weibo.isValidCredentials(username, password)) { mApi.setCredentials(username, password); // Setup API and HttpClient } // 为cmwap用户设置代理上网 String type = getNetworkType(); if (null != type && type.equalsIgnoreCase("cmwap")) { Toast.makeText(this, "您当前正在使用cmwap网络上网.", Toast.LENGTH_SHORT); mApi.getHttpClient().setProxy("10.0.0.172", 80, "http"); } } public String getNetworkType() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); NetworkInfo mobNetInfo = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); return mobNetInfo.getExtraInfo(); // 接入点名称: 此名称可被用户任意更改 如: cmwap, cmnet, // internet ... } @Override public void onTerminate() { //FIXME: 根据android文档,onTerminate不会在真实机器上被执行到 //因此这些清理动作需要再找合适的地方放置,以确保执行。 cleanupImages(); mDb.close(); Toast.makeText(this, "exit app", Toast.LENGTH_LONG); super.onTerminate(); } private void cleanupImages() { HashSet<String> keepers = new HashSet<String>(); Cursor cursor = mDb.fetchAllTweets(StatusTable.TYPE_HOME); if (cursor.moveToFirst()) { int imageIndex = cursor .getColumnIndexOrThrow(StatusTable.FIELD_PROFILE_IMAGE_URL); do { keepers.add(cursor.getString(imageIndex)); } while (cursor.moveToNext()); } cursor.close(); cursor = mDb.fetchAllDms(-1); if (cursor.moveToFirst()) { int imageIndex = cursor .getColumnIndexOrThrow(StatusTable.FIELD_PROFILE_IMAGE_URL); do { keepers.add(cursor.getString(imageIndex)); } while (cursor.moveToNext()); } cursor.close(); mProfileImageCacheManager.getImageManager().cleanup(keepers); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.graphics.Bitmap; import android.graphics.Canvas; /** * The Canvas version of a sprite. This class keeps a pointer to a bitmap * and draws it at the Sprite's current location. */ public class CanvasSprite extends Renderable { private Bitmap mBitmap; public CanvasSprite(Bitmap bitmap) { mBitmap = bitmap; } public void draw(Canvas canvas) { // The Canvas system uses a screen-space coordinate system, that is, // 0,0 is the top-left point of the canvas. But in order to align // with OpenGL's coordinate space (which places 0,0 and the lower-left), // for this test I flip the y coordinate. canvas.drawBitmap(mBitmap, x, canvas.getHeight() - (y + height), null); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.os.SystemClock; /** * Implements a simple runtime profiler. The profiler records start and stop * times for several different types of profiles and can then return min, max * and average execution times per type. Profile types are independent and may * be nested in calling code. This object is a singleton for convenience. */ public class ProfileRecorder { // A type for recording actual draw command time. public static final int PROFILE_DRAW = 0; // A type for recording the time it takes to display the scene. public static final int PROFILE_PAGE_FLIP = 1; // A type for recording the time it takes to run a single simulation step. public static final int PROFILE_SIM = 2; // A type for recording the total amount of time spent rendering a frame. public static final int PROFILE_FRAME = 3; private static final int PROFILE_COUNT = PROFILE_FRAME + 1; private ProfileRecord[] mProfiles; private int mFrameCount; public static ProfileRecorder sSingleton = new ProfileRecorder(); public ProfileRecorder() { mProfiles = new ProfileRecord[PROFILE_COUNT]; for (int x = 0; x < PROFILE_COUNT; x++) { mProfiles[x] = new ProfileRecord(); } } /** Starts recording execution time for a specific profile type.*/ public void start(int profileType) { if (profileType < PROFILE_COUNT) { mProfiles[profileType].start(SystemClock.uptimeMillis()); } } /** Stops recording time for this profile type. */ public void stop(int profileType) { if (profileType < PROFILE_COUNT) { mProfiles[profileType].stop(SystemClock.uptimeMillis()); } } /** Indicates the end of the frame.*/ public void endFrame() { mFrameCount++; } /* Flushes all recorded timings from the profiler. */ public void resetAll() { for (int x = 0; x < PROFILE_COUNT; x++) { mProfiles[x].reset(); } mFrameCount = 0; } /* Returns the average execution time, in milliseconds, for a given type. */ public long getAverageTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getAverageTime(mFrameCount); } return time; } /* Returns the minimum execution time in milliseconds for a given type. */ public long getMinTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getMinTime(); } return time; } /* Returns the maximum execution time in milliseconds for a given type. */ public long getMaxTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getMaxTime(); } return time; } /** * A simple class for storing timing information about a single profile * type. */ protected class ProfileRecord { private long mStartTime; private long mTotalTime; private long mMinTime; private long mMaxTime; public void start(long time) { mStartTime = time; } public void stop(long time) { final long timeDelta = time - mStartTime; mTotalTime += timeDelta; if (mMinTime == 0 || timeDelta < mMinTime) { mMinTime = timeDelta; } if (mMaxTime == 0 || timeDelta > mMaxTime) { mMaxTime = timeDelta; } } public long getAverageTime(int frameCount) { long time = frameCount > 0 ? mTotalTime / frameCount : 0; return time; } public long getMinTime() { return mMinTime; } public long getMaxTime() { return mMaxTime; } public void startNewProfilePeriod() { mTotalTime = 0; } public void reset() { mTotalTime = 0; mStartTime = 0; mMinTime = 0; mMaxTime = 0; } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * Implements a surface view which writes updates to the surface's canvas using * a separate rendering thread. This class is based heavily on GLSurfaceView. */ public class CanvasSurfaceView extends SurfaceView implements SurfaceHolder.Callback { private boolean mSizeChanged = true; private SurfaceHolder mHolder; private CanvasThread mCanvasThread; public CanvasSurfaceView(Context context) { super(context); init(); } public CanvasSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL); } public SurfaceHolder getSurfaceHolder() { return mHolder; } /** Sets the user's renderer and kicks off the rendering thread. */ public void setRenderer(Renderer renderer) { mCanvasThread = new CanvasThread(mHolder, renderer); mCanvasThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mCanvasThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mCanvasThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mCanvasThread.onWindowResize(w, h); } /** Inform the view that the activity is paused.*/ public void onPause() { mCanvasThread.onPause(); } /** Inform the view that the activity is resumed. */ public void onResume() { mCanvasThread.onResume(); } /** Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mCanvasThread.onWindowFocusChanged(hasFocus); } /** * Set an "event" to be run on the rendering thread. * @param r the runnable to be run on the rendering thread. */ public void setEvent(Runnable r) { mCanvasThread.setEvent(r); } /** Clears the runnable event, if any, from the rendering thread. */ public void clearEvent() { mCanvasThread.clearEvent(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mCanvasThread.requestExitAndWait(); } protected void stopDrawing() { mCanvasThread.requestExitAndWait(); } // ---------------------------------------------------------------------- /** A generic renderer interface. */ public interface Renderer { /** * Surface changed size. * Called after the surface is created and whenever * the surface size changes. Set your viewport here. * @param width * @param height */ void sizeChanged(int width, int height); /** * Draw the current frame. * @param canvas The target canvas to draw into. */ void drawFrame(Canvas canvas); } /** * A generic Canvas rendering Thread. Delegates to a Renderer instance to do * the actual drawing. */ class CanvasThread extends Thread { private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private Runnable mEvent; private SurfaceHolder mSurfaceHolder; CanvasThread(SurfaceHolder holder, Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; mSurfaceHolder = holder; setName("CanvasThread"); } @Override public void run() { boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ final ProfileRecorder profiler = ProfileRecorder.sSingleton; while (!mDone) { profiler.start(ProfileRecorder.PROFILE_FRAME); /* * Update the asynchronous state (window size) */ int w; int h; synchronized (this) { // If the user has set a runnable to run in this thread, // execute it and record the amount of time it takes to // run. if (mEvent != null) { profiler.start(ProfileRecorder.PROFILE_SIM); mEvent.run(); profiler.stop(ProfileRecorder.PROFILE_SIM); } if(needToWait()) { while (needToWait()) { try { wait(); } catch (InterruptedException e) { } } } if (mDone) { break; } tellRendererSurfaceChanged = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { // Get ready to draw. // We record both lockCanvas() and unlockCanvasAndPost() // as part of "page flip" time because either may block // until the previous frame is complete. profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP); Canvas canvas = mSurfaceHolder.lockCanvas(); profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP); if (canvas != null) { // Draw a frame! profiler.start(ProfileRecorder.PROFILE_DRAW); mRenderer.drawFrame(canvas); profiler.stop(ProfileRecorder.PROFILE_DRAW); profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP); mSurfaceHolder.unlockCanvasAndPost(canvas); profiler.stop(ProfileRecorder.PROFILE_PAGE_FLIP); } } profiler.stop(ProfileRecorder.PROFILE_FRAME); profiler.endFrame(); } } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from CanvasThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the rendering thread. * @param r the runnable to be run on the rendering thread. */ public void setEvent(Runnable r) { synchronized(this) { mEvent = r; } } public void clearEvent() { synchronized(this) { mEvent = null; } } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; /** * Base class defining the core set of information necessary to render (and move * an object on the screen. This is an abstract type and must be derived to * add methods to actually draw (see CanvasSprite and GLSprite). */ public abstract class Renderable { // Position. public float x; public float y; public float z; // Velocity. public float velocityX; public float velocityY; public float velocityZ; // Size. public float width; public float height; }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.util.DisplayMetrics; /** * Activity for testing OpenGL ES drawing speed. This activity sets up sprites * and passes them off to an OpenGLSurfaceView for rendering and movement. */ public class OpenGLTestActivity extends Activity { private final static int SPRITE_WIDTH = 64; private final static int SPRITE_HEIGHT = 64; private GLSurfaceView mGLSurfaceView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGLSurfaceView = new GLSurfaceView(this); SimpleGLRenderer spriteRenderer = new SimpleGLRenderer(this); // Clear out any old profile results. ProfileRecorder.sSingleton.resetAll(); final Intent callingIntent = getIntent(); // Allocate our sprites and add them to an array. final int robotCount = callingIntent.getIntExtra("spriteCount", 10); final boolean animate = callingIntent.getBooleanExtra("animate", true); final boolean useVerts = callingIntent.getBooleanExtra("useVerts", false); final boolean useHardwareBuffers = callingIntent.getBooleanExtra("useHardwareBuffers", false); // Allocate space for the robot sprites + one background sprite. GLSprite[] spriteArray = new GLSprite[robotCount + 1]; // We need to know the width and height of the display pretty soon, // so grab the information now. DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); GLSprite background = new GLSprite(R.drawable.background); BitmapDrawable backgroundImage = (BitmapDrawable)getResources().getDrawable(R.drawable.background); Bitmap backgoundBitmap = backgroundImage.getBitmap(); background.width = backgoundBitmap.getWidth(); background.height = backgoundBitmap.getHeight(); if (useVerts) { // Setup the background grid. This is just a quad. Grid backgroundGrid = new Grid(2, 2, false); backgroundGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, null); backgroundGrid.set(1, 0, background.width, 0.0f, 0.0f, 1.0f, 1.0f, null); backgroundGrid.set(0, 1, 0.0f, background.height, 0.0f, 0.0f, 0.0f, null); backgroundGrid.set(1, 1, background.width, background.height, 0.0f, 1.0f, 0.0f, null ); background.setGrid(backgroundGrid); } spriteArray[0] = background; Grid spriteGrid = null; if (useVerts) { // Setup a quad for the sprites to use. All sprites will use the // same sprite grid intance. spriteGrid = new Grid(2, 2, false); spriteGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f , 1.0f, null); spriteGrid.set(1, 0, SPRITE_WIDTH, 0.0f, 0.0f, 1.0f, 1.0f, null); spriteGrid.set(0, 1, 0.0f, SPRITE_HEIGHT, 0.0f, 0.0f, 0.0f, null); spriteGrid.set(1, 1, SPRITE_WIDTH, SPRITE_HEIGHT, 0.0f, 1.0f, 0.0f, null); } // This list of things to move. It points to the same content as the // sprite list except for the background. Renderable[] renderableArray = new Renderable[robotCount]; final int robotBucketSize = robotCount / 3; for (int x = 0; x < robotCount; x++) { GLSprite robot; // Our robots come in three flavors. Split them up accordingly. if (x < robotBucketSize) { robot = new GLSprite(R.drawable.skate1); } else if (x < robotBucketSize * 2) { robot = new GLSprite(R.drawable.skate2); } else { robot = new GLSprite(R.drawable.skate3); } robot.width = SPRITE_WIDTH; robot.height = SPRITE_HEIGHT; // Pick a random location for this sprite. robot.x = (float)(Math.random() * dm.widthPixels); robot.y = (float)(Math.random() * dm.heightPixels); // All sprites can reuse the same grid. If we're running the // DrawTexture extension test, this is null. robot.setGrid(spriteGrid); // Add this robot to the spriteArray so it gets drawn and to the // renderableArray so that it gets moved. spriteArray[x + 1] = robot; renderableArray[x] = robot; } // Now's a good time to run the GC. Since we won't do any explicit // allocation during the test, the GC should stay dormant and not // influence our results. Runtime r = Runtime.getRuntime(); r.gc(); spriteRenderer.setSprites(spriteArray); spriteRenderer.setVertMode(useVerts, useHardwareBuffers); mGLSurfaceView.setRenderer(spriteRenderer); if (animate) { Mover simulationRuntime = new Mover(); simulationRuntime.setRenderables(renderableArray); simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels); mGLSurfaceView.setEvent(simulationRuntime); } setContentView(mGLSurfaceView); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.graphics.Canvas; import com.android.spritemethodtest.CanvasSurfaceView.Renderer; /** * An extremely simple renderer based on the CanvasSurfaceView drawing * framework. Simply draws a list of sprites to a canvas every frame. */ public class SimpleCanvasRenderer implements Renderer { private CanvasSprite[] mSprites; public void setSprites(CanvasSprite[] sprites) { mSprites = sprites; } public void drawFrame(Canvas canvas) { if (mSprites != null) { for (int x = 0; x < mSprites.length; x++) { mSprites[x].draw(canvas); } } } public void sizeChanged(int width, int height) { } }
Java
/* * Copyright (C) 2009 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. */ // This file was lifted from the APIDemos sample. See: // http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/index.html package com.android.spritemethodtest; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback { public GLSurfaceView(Context context) { super(context); init(); } public GLSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public SurfaceHolder getSurfaceHolder() { return mHolder; } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Set an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void setEvent(Runnable r) { mGLThread.setEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Called when the rendering thread is about to shut down. This is a * good place to release OpenGL ES resources (textures, buffers, etc). * @param gl */ void shutdown(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME); /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { if (mEvent != null) { ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM); mEvent.run(); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW); /* draw a frame here */ mRenderer.drawFrame(gl); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_PAGE_FLIP); mEglHelper.swap(); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_PAGE_FLIP); } ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME); ProfileRecorder.sSingleton.endFrame(); } /* * clean-up everything... */ if (gl != null) { mRenderer.shutdown(gl); } mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void setEvent(Runnable r) { synchronized(this) { mEvent = r; } } public void clearEvent() { synchronized(this) { mEvent = null; } } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private Runnable mEvent; private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioGroup; /** * Main entry point for the SpriteMethodTest application. This application * provides a simple interface for testing the relative speed of 2D rendering * systems available on Android, namely the Canvas system and OpenGL ES. It * also serves as an example of how SurfaceHolders can be used to create an * efficient rendering thread for drawing. */ public class SpriteMethodTest extends Activity { private static final int ACTIVITY_TEST = 0; private static final int RESULTS_DIALOG = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Sets up a click listener for the Run Test button. Button button; button = (Button) findViewById(R.id.runTest); button.setOnClickListener(mRunTestListener); // Turns on one item by default in our radio groups--as it should be! RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod); group.setOnCheckedChangeListener(mMethodChangedListener); group.check(R.id.methodCanvas); RadioGroup glSettings = (RadioGroup)findViewById(R.id.GLSettings); glSettings.check(R.id.settingVerts); } /** Passes preferences about the test via its intent. */ protected void initializeIntent(Intent i) { final CheckBox checkBox = (CheckBox) findViewById(R.id.animateSprites); final boolean animate = checkBox.isChecked(); final EditText editText = (EditText) findViewById(R.id.spriteCount); final String spriteCountText = editText.getText().toString(); final int stringCount = Integer.parseInt(spriteCountText); i.putExtra("animate", animate); i.putExtra("spriteCount", stringCount); } /** * Responds to a click on the Run Test button by launching a new test * activity. */ View.OnClickListener mRunTestListener = new OnClickListener() { public void onClick(View v) { RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod); Intent i; if (group.getCheckedRadioButtonId() == R.id.methodCanvas) { i = new Intent(v.getContext(), CanvasTestActivity.class); } else { i = new Intent(v.getContext(), OpenGLTestActivity.class); RadioGroup glSettings = (RadioGroup)findViewById(R.id.GLSettings); if (glSettings.getCheckedRadioButtonId() == R.id.settingVerts) { i.putExtra("useVerts", true); } else if (glSettings.getCheckedRadioButtonId() == R.id.settingVBO) { i.putExtra("useVerts", true); i.putExtra("useHardwareBuffers", true); } } initializeIntent(i); startActivityForResult(i, ACTIVITY_TEST); } }; /** * Enables or disables OpenGL ES-specific settings controls when the render * method option changes. */ RadioGroup.OnCheckedChangeListener mMethodChangedListener = new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.methodCanvas) { findViewById(R.id.settingDrawTexture).setEnabled(false); findViewById(R.id.settingVerts).setEnabled(false); findViewById(R.id.settingVBO).setEnabled(false); } else { findViewById(R.id.settingDrawTexture).setEnabled(true); findViewById(R.id.settingVerts).setEnabled(true); findViewById(R.id.settingVBO).setEnabled(true); } } }; /** Creates the test results dialog and fills in a dummy message. */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; if (id == RESULTS_DIALOG) { String dummy = "No results yet."; CharSequence sequence = dummy.subSequence(0, dummy.length() -1); dialog = new AlertDialog.Builder(this) .setTitle(R.string.dialog_title) .setPositiveButton(R.string.dialog_ok, null) .setMessage(sequence) .create(); } return dialog; } /** * Replaces the dummy message in the test results dialog with a string that * describes the actual test results. */ protected void onPrepareDialog (int id, Dialog dialog) { if (id == RESULTS_DIALOG) { // Extract final timing information from the profiler. final ProfileRecorder profiler = ProfileRecorder.sSingleton; final long frameTime = profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME); final long frameMin = profiler.getMinTime(ProfileRecorder.PROFILE_FRAME); final long frameMax = profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME); final long drawTime = profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW); final long drawMin = profiler.getMinTime(ProfileRecorder.PROFILE_DRAW); final long drawMax = profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW); final long flipTime = profiler.getAverageTime(ProfileRecorder.PROFILE_PAGE_FLIP); final long flipMin = profiler.getMinTime(ProfileRecorder.PROFILE_PAGE_FLIP); final long flipMax = profiler.getMaxTime(ProfileRecorder.PROFILE_PAGE_FLIP); final long simTime = profiler.getAverageTime(ProfileRecorder.PROFILE_SIM); final long simMin = profiler.getMinTime(ProfileRecorder.PROFILE_SIM); final long simMax = profiler.getMaxTime(ProfileRecorder.PROFILE_SIM); final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f; String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n" + "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n" + "Draw: " + drawTime + "ms\n" + "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n" + "Page Flip: " + flipTime + "ms\n" + "\t\tMin: " + flipMin + "ms\t\tMax: " + flipMax + "\n" + "Sim: " + simTime + "ms\n" + "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n"; CharSequence sequence = result.subSequence(0, result.length() -1); AlertDialog alertDialog = (AlertDialog)dialog; alertDialog.setMessage(sequence); } } /** Shows the results dialog when the test activity closes. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); showDialog(RESULTS_DIALOG); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11Ext; /** * This is the OpenGL ES version of a sprite. It is more complicated than the * CanvasSprite class because it can be used in more than one way. This class * can draw using a grid of verts, a grid of verts stored in VBO objects, or * using the DrawTexture extension. */ public class GLSprite extends Renderable { // The OpenGL ES texture handle to draw. private int mTextureName; // The id of the original resource that mTextureName is based on. private int mResourceId; // If drawing with verts or VBO verts, the grid object defining those verts. private Grid mGrid; public GLSprite(int resourceId) { super(); mResourceId = resourceId; } public void setTextureName(int name) { mTextureName = name; } public int getTextureName() { return mTextureName; } public void setResourceId(int id) { mResourceId = id; } public int getResourceId() { return mResourceId; } public void setGrid(Grid grid) { mGrid = grid; } public Grid getGrid() { return mGrid; } public void draw(GL10 gl) { gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureName); if (mGrid == null) { // Draw using the DrawTexture extension. ((GL11Ext) gl).glDrawTexfOES(x, y, z, width, height); } else { // Draw using verts or VBO verts. gl.glPushMatrix(); gl.glLoadIdentity(); gl.glTranslatef( x, y, z); mGrid.draw(gl, true, false); gl.glPopMatrix(); } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.DisplayMetrics; /** * Activity for testing Canvas drawing speed. This activity sets up sprites and * passes them off to a CanvasSurfaceView for rendering and movement. It is * very similar to OpenGLTestActivity. Note that Bitmap objects come out of a * pool and must be explicitly recycled on shutdown. See onDestroy(). */ public class CanvasTestActivity extends Activity { private CanvasSurfaceView mCanvasSurfaceView; // Describes the image format our bitmaps should be converted to. private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options(); private Bitmap[] mBitmaps; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCanvasSurfaceView = new CanvasSurfaceView(this); SimpleCanvasRenderer spriteRenderer = new SimpleCanvasRenderer(); // Sets our preferred image format to 16-bit, 565 format. sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565; // Clear out any old profile results. ProfileRecorder.sSingleton.resetAll(); final Intent callingIntent = getIntent(); // Allocate our sprites and add them to an array. final int robotCount = callingIntent.getIntExtra("spriteCount", 10); final boolean animate = callingIntent.getBooleanExtra("animate", true); // Allocate space for the robot sprites + one background sprite. CanvasSprite[] spriteArray = new CanvasSprite[robotCount + 1]; mBitmaps = new Bitmap[4]; mBitmaps[0] = loadBitmap(this, R.drawable.background); mBitmaps[1] = loadBitmap(this, R.drawable.skate1); mBitmaps[2] = loadBitmap(this, R.drawable.skate2); mBitmaps[3] = loadBitmap(this, R.drawable.skate3); // We need to know the width and height of the display pretty soon, // so grab the information now. DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); // Make the background. // Note that the background image is larger than the screen, // so some clipping will occur when it is drawn. CanvasSprite background = new CanvasSprite(mBitmaps[0]); background.width = mBitmaps[0].getWidth(); background.height = mBitmaps[0].getHeight(); spriteArray[0] = background; // This list of things to move. It points to the same content as // spriteArray except for the background. Renderable[] renderableArray = new Renderable[robotCount]; final int robotBucketSize = robotCount / 3; for (int x = 0; x < robotCount; x++) { CanvasSprite robot; // Our robots come in three flavors. Split them up accordingly. if (x < robotBucketSize) { robot = new CanvasSprite(mBitmaps[1]); } else if (x < robotBucketSize * 2) { robot = new CanvasSprite(mBitmaps[2]); } else { robot = new CanvasSprite(mBitmaps[3]); } robot.width = 64; robot.height = 64; // Pick a random location for this sprite. robot.x = (float)(Math.random() * dm.widthPixels); robot.y = (float)(Math.random() * dm.heightPixels); // Add this robot to the spriteArray so it gets drawn and to the // renderableArray so that it gets moved. spriteArray[x + 1] = robot; renderableArray[x] = robot; } // Now's a good time to run the GC. Since we won't do any explicit // allocation during the test, the GC should stay dormant and not // influence our results. Runtime r = Runtime.getRuntime(); r.gc(); spriteRenderer.setSprites(spriteArray); mCanvasSurfaceView.setRenderer(spriteRenderer); if (animate) { Mover simulationRuntime = new Mover(); simulationRuntime.setRenderables(renderableArray); simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels); mCanvasSurfaceView.setEvent(simulationRuntime); } setContentView(mCanvasSurfaceView); } /** Recycles all of the bitmaps loaded in onCreate(). */ @Override protected void onDestroy() { super.onDestroy(); mCanvasSurfaceView.clearEvent(); mCanvasSurfaceView.stopDrawing(); for (int x = 0; x < mBitmaps.length; x++) { mBitmaps[x].recycle(); mBitmaps[x] = null; } } /** * Loads a bitmap from a resource and converts it to a bitmap. This is * a much-simplified version of the loadBitmap() that appears in * SimpleGLRenderer. * @param context The application context. * @param resourceId The id of the resource to load. * @return A bitmap containing the image contents of the resource, or null * if there was an error. */ protected Bitmap loadBitmap(Context context, int resourceId) { Bitmap bitmap = null; if (context != null) { InputStream is = context.getResources().openRawResource(resourceId); try { bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions); } finally { try { is.close(); } catch (IOException e) { // Ignore. } } } return bitmap; } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.os.SystemClock; /** * A simple runnable that updates the position of each sprite on the screen * every frame by applying a very simple gravity and bounce simulation. The * sprites are jumbled with random velocities every once and a while. */ public class Mover implements Runnable { private Renderable[] mRenderables; private long mLastTime; private long mLastJumbleTime; private int mViewWidth; private int mViewHeight; static final float COEFFICIENT_OF_RESTITUTION = 0.75f; static final float SPEED_OF_GRAVITY = 150.0f; static final long JUMBLE_EVERYTHING_DELAY = 15 * 1000; static final float MAX_VELOCITY = 8000.0f; public void run() { // Perform a single simulation step. if (mRenderables != null) { final long time = SystemClock.uptimeMillis(); final long timeDelta = time - mLastTime; final float timeDeltaSeconds = mLastTime > 0.0f ? timeDelta / 1000.0f : 0.0f; mLastTime = time; // Check to see if it's time to jumble again. final boolean jumble = (time - mLastJumbleTime > JUMBLE_EVERYTHING_DELAY); if (jumble) { mLastJumbleTime = time; } for (int x = 0; x < mRenderables.length; x++) { Renderable object = mRenderables[x]; // Jumble! Apply random velocities. if (jumble) { object.velocityX += (MAX_VELOCITY / 2.0f) - (float)(Math.random() * MAX_VELOCITY); object.velocityY += (MAX_VELOCITY / 2.0f) - (float)(Math.random() * MAX_VELOCITY); } // Move. object.x = object.x + (object.velocityX * timeDeltaSeconds); object.y = object.y + (object.velocityY * timeDeltaSeconds); object.z = object.z + (object.velocityZ * timeDeltaSeconds); // Apply Gravity. object.velocityY -= SPEED_OF_GRAVITY * timeDeltaSeconds; // Bounce. if ((object.x < 0.0f && object.velocityX < 0.0f) || (object.x > mViewWidth - object.width && object.velocityX > 0.0f)) { object.velocityX = -object.velocityX * COEFFICIENT_OF_RESTITUTION; object.x = Math.max(0.0f, Math.min(object.x, mViewWidth - object.width)); if (Math.abs(object.velocityX) < 0.1f) { object.velocityX = 0.0f; } } if ((object.y < 0.0f && object.velocityY < 0.0f) || (object.y > mViewHeight - object.height && object.velocityY > 0.0f)) { object.velocityY = -object.velocityY * COEFFICIENT_OF_RESTITUTION; object.y = Math.max(0.0f, Math.min(object.y, mViewHeight - object.height)); if (Math.abs(object.velocityY) < 0.1f) { object.velocityY = 0.0f; } } } } } public void setRenderables(Renderable[] renderables) { mRenderables = renderables; } public void setViewSize(int width, int height) { mViewHeight = height; mViewWidth = width; } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import java.io.IOException; import java.io.InputStream; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLUtils; import android.util.Log; /** * An OpenGL ES renderer based on the GLSurfaceView rendering framework. This * class is responsible for drawing a list of renderables to the screen every * frame. It also manages loading of textures and (when VBOs are used) the * allocation of vertex buffer objects. */ public class SimpleGLRenderer implements GLSurfaceView.Renderer { // Specifies the format our textures should be converted to upon load. private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options(); // An array of things to draw every frame. private GLSprite[] mSprites; // Pre-allocated arrays to use at runtime so that allocation during the // test can be avoided. private int[] mTextureNameWorkspace; private int[] mCropWorkspace; // A reference to the application context. private Context mContext; // Determines the use of vertex arrays. private boolean mUseVerts; // Determines the use of vertex buffer objects. private boolean mUseHardwareBuffers; public SimpleGLRenderer(Context context) { // Pre-allocate and store these objects so we can use them at runtime // without allocating memory mid-frame. mTextureNameWorkspace = new int[1]; mCropWorkspace = new int[4]; // Set our bitmaps to 16-bit, 565 format. sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565; mContext = context; } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void setSprites(GLSprite[] sprites) { mSprites = sprites; } /** * Changes the vertex mode used for drawing. * @param useVerts Specifies whether to use a vertex array. If false, the * DrawTexture extension is used. * @param useHardwareBuffers Specifies whether to store vertex arrays in * main memory or on the graphics card. Ignored if useVerts is false. */ public void setVertMode(boolean useVerts, boolean useHardwareBuffers) { mUseVerts = useVerts; mUseHardwareBuffers = useVerts ? useHardwareBuffers : false; } /** Draws the sprites. */ public void drawFrame(GL10 gl) { if (mSprites != null) { gl.glMatrixMode(GL10.GL_MODELVIEW); if (mUseVerts) { Grid.beginDrawing(gl, true, false); } for (int x = 0; x < mSprites.length; x++) { mSprites[x].draw(gl); } if (mUseVerts) { Grid.endDrawing(gl); } } } /* Called when the size of the window changes. */ public void sizeChanged(GL10 gl, int width, int height) { gl.glViewport(0, 0, width, height); /* * Set our projection matrix. This doesn't have to be done each time we * draw, but usually a new projection needs to be set when the viewport * is resized. */ gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrthof(0.0f, width, 0.0f, height, 0.0f, 1.0f); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000); gl.glEnable(GL10.GL_TEXTURE_2D); } /** * Called whenever the surface is created. This happens at startup, and * may be called again at runtime if the device context is lost (the screen * goes to sleep, etc). This function must fill the contents of vram with * texture data and (when using VBOs) hardware vertex arrays. */ public void surfaceCreated(GL10 gl) { /* * Some one-time OpenGL initialization can be made here probably based * on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(0.5f, 0.5f, 0.5f, 1); gl.glShadeModel(GL10.GL_FLAT); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * By default, OpenGL enables features that improve quality but reduce * performance. One might want to tweak that especially on software * renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glDisable(GL10.GL_LIGHTING); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); if (mSprites != null) { // If we are using hardware buffers and the screen lost context // then the buffer indexes that we recorded previously are now // invalid. Forget them here and recreate them below. if (mUseHardwareBuffers) { for (int x = 0; x < mSprites.length; x++) { // Ditch old buffer indexes. mSprites[x].getGrid().invalidateHardwareBuffers(); } } // Load our texture and set its texture name on all sprites. // To keep this sample simple we will assume that sprites that share // the same texture are grouped together in our sprite list. A real // app would probably have another level of texture management, // like a texture hash. int lastLoadedResource = -1; int lastTextureId = -1; for (int x = 0; x < mSprites.length; x++) { int resource = mSprites[x].getResourceId(); if (resource != lastLoadedResource) { lastTextureId = loadBitmap(mContext, gl, resource); lastLoadedResource = resource; } mSprites[x].setTextureName(lastTextureId); if (mUseHardwareBuffers) { Grid currentGrid = mSprites[x].getGrid(); if (!currentGrid.usingHardwareBuffers()) { currentGrid.generateHardwareBuffers(gl); } //mSprites[x].getGrid().generateHardwareBuffers(gl); } } } } /** * Called when the rendering thread shuts down. This is a good place to * release OpenGL ES resources. * @param gl */ public void shutdown(GL10 gl) { if (mSprites != null) { int lastFreedResource = -1; int[] textureToDelete = new int[1]; for (int x = 0; x < mSprites.length; x++) { int resource = mSprites[x].getResourceId(); if (resource != lastFreedResource) { textureToDelete[0] = mSprites[x].getTextureName(); gl.glDeleteTextures(1, textureToDelete, 0); mSprites[x].setTextureName(0); } if (mUseHardwareBuffers) { mSprites[x].getGrid().releaseHardwareBuffers(gl); } } } } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. */ protected int loadBitmap(Context context, GL10 gl, int resourceId) { int textureName = -1; if (context != null && gl != null) { gl.glGenTextures(1, mTextureNameWorkspace, 0); textureName = mTextureNameWorkspace[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = context.getResources().openRawResource(resourceId); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions); } finally { try { is.close(); } catch (IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); mCropWorkspace[0] = 0; mCropWorkspace[1] = bitmap.getHeight(); mCropWorkspace[2] = bitmap.getWidth(); mCropWorkspace[3] = -bitmap.getHeight(); bitmap.recycle(); ((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0); int error = gl.glGetError(); if (error != GL10.GL_NO_ERROR) { Log.e("SpriteMethodTest", "Texture Load GLError: " + error); } } return textureName; } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * This version is modified from the original Grid.java (found in * the SpriteText package in the APIDemos Android sample) to support hardware * vertex buffers. */ class Grid { private FloatBuffer mFloatVertexBuffer; private FloatBuffer mFloatTexCoordBuffer; private FloatBuffer mFloatColorBuffer; private IntBuffer mFixedVertexBuffer; private IntBuffer mFixedTexCoordBuffer; private IntBuffer mFixedColorBuffer; private CharBuffer mIndexBuffer; private Buffer mVertexBuffer; private Buffer mTexCoordBuffer; private Buffer mColorBuffer; private int mCoordinateSize; private int mCoordinateType; private int mW; private int mH; private int mIndexCount; private boolean mUseHardwareBuffers; private int mVertBufferIndex; private int mIndexBufferIndex; private int mTextureCoordBufferIndex; private int mColorBufferIndex; public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) { if (vertsAcross < 0 || vertsAcross >= 65536) { throw new IllegalArgumentException("vertsAcross"); } if (vertsDown < 0 || vertsDown >= 65536) { throw new IllegalArgumentException("vertsDown"); } if (vertsAcross * vertsDown >= 65536) { throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536"); } mUseHardwareBuffers = false; mW = vertsAcross; mH = vertsDown; int size = vertsAcross * vertsDown; final int FLOAT_SIZE = 4; final int FIXED_SIZE = 4; final int CHAR_SIZE = 2; if (useFixedPoint) { mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3) .order(ByteOrder.nativeOrder()).asIntBuffer(); mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2) .order(ByteOrder.nativeOrder()).asIntBuffer(); mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4) .order(ByteOrder.nativeOrder()).asIntBuffer(); mVertexBuffer = mFixedVertexBuffer; mTexCoordBuffer = mFixedTexCoordBuffer; mColorBuffer = mFixedColorBuffer; mCoordinateSize = FIXED_SIZE; mCoordinateType = GL10.GL_FIXED; } else { mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mVertexBuffer = mFloatVertexBuffer; mTexCoordBuffer = mFloatTexCoordBuffer; mColorBuffer = mFloatColorBuffer; mCoordinateSize = FLOAT_SIZE; mCoordinateType = GL10.GL_FLOAT; } int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) .order(ByteOrder.nativeOrder()).asCharBuffer(); /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); mIndexBuffer.put(i++, a); mIndexBuffer.put(i++, b); mIndexBuffer.put(i++, c); mIndexBuffer.put(i++, b); mIndexBuffer.put(i++, c); mIndexBuffer.put(i++, d); } } } mVertBufferIndex = 0; } void set(int i, int j, float x, float y, float z, float u, float v, float[] color) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } final int index = mW * j + i; final int posIndex = index * 3; final int texIndex = index * 2; final int colorIndex = index * 4; if (mCoordinateType == GL10.GL_FLOAT) { mFloatVertexBuffer.put(posIndex, x); mFloatVertexBuffer.put(posIndex + 1, y); mFloatVertexBuffer.put(posIndex + 2, z); mFloatTexCoordBuffer.put(texIndex, u); mFloatTexCoordBuffer.put(texIndex + 1, v); if (color != null) { mFloatColorBuffer.put(colorIndex, color[0]); mFloatColorBuffer.put(colorIndex + 1, color[1]); mFloatColorBuffer.put(colorIndex + 2, color[2]); mFloatColorBuffer.put(colorIndex + 3, color[3]); } } else { mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16))); mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16))); mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16))); mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16))); mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16))); if (color != null) { mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16))); } } } public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } if (useColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); } else { gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } } public void draw(GL10 gl, boolean useTexture, boolean useColor) { if (!mUseHardwareBuffers) { gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer); if (useTexture) { gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer); } if (useColor) { gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } else { GL11 gl11 = (GL11)gl; // draw using hardware buffers gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex); gl11.glVertexPointer(3, mCoordinateType, 0, 0); if (useTexture) { gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex); gl11.glTexCoordPointer(2, mCoordinateType, 0, 0); } if (useColor) { gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex); gl11.glColorPointer(4, mCoordinateType, 0, 0); } gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex); gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount, GL11.GL_UNSIGNED_SHORT, 0); gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } } public static void endDrawing(GL10 gl) { gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public boolean usingHardwareBuffers() { return mUseHardwareBuffers; } /** * When the OpenGL ES device is lost, GL handles become invalidated. * In that case, we just want to "forget" the old handles (without * explicitly deleting them) and make new ones. */ public void invalidateHardwareBuffers() { mVertBufferIndex = 0; mIndexBufferIndex = 0; mTextureCoordBufferIndex = 0; mColorBufferIndex = 0; mUseHardwareBuffers = false; } /** * Deletes the hardware buffers allocated by this object (if any). */ public void releaseHardwareBuffers(GL10 gl) { if (mUseHardwareBuffers) { if (gl instanceof GL11) { GL11 gl11 = (GL11)gl; int[] buffer = new int[1]; buffer[0] = mVertBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mTextureCoordBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mColorBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mIndexBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); } invalidateHardwareBuffers(); } } /** * Allocates hardware buffers on the graphics card and fills them with * data if a buffer has not already been previously allocated. Note that * this function uses the GL_OES_vertex_buffer_object extension, which is * not guaranteed to be supported on every device. * @param gl A pointer to the OpenGL ES context. */ public void generateHardwareBuffers(GL10 gl) { if (!mUseHardwareBuffers) { if (gl instanceof GL11) { GL11 gl11 = (GL11)gl; int[] buffer = new int[1]; // Allocate and fill the vertex buffer. gl11.glGenBuffers(1, buffer, 0); mVertBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex); final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize, mVertexBuffer, GL11.GL_STATIC_DRAW); // Allocate and fill the texture coordinate buffer. gl11.glGenBuffers(1, buffer, 0); mTextureCoordBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex); final int texCoordSize = mTexCoordBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize, mTexCoordBuffer, GL11.GL_STATIC_DRAW); // Allocate and fill the color buffer. gl11.glGenBuffers(1, buffer, 0); mColorBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex); final int colorSize = mColorBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize, mColorBuffer, GL11.GL_STATIC_DRAW); // Unbind the array buffer. gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); // Allocate and fill the index buffer. gl11.glGenBuffers(1, buffer, 0); mIndexBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex); // A char is 2 bytes. final int indexSize = mIndexBuffer.capacity() * 2; gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer, GL11.GL_STATIC_DRAW); // Unbind the element array buffer. gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); mUseHardwareBuffers = true; assert mVertBufferIndex != 0; assert mTextureCoordBufferIndex != 0; assert mIndexBufferIndex != 0; assert gl11.glGetError() == 0; } } } // These functions exposed to patch Grid info into native code. public final int getVertexBuffer() { return mVertBufferIndex; } public final int getTextureBuffer() { return mTextureCoordBufferIndex; } public final int getIndexBuffer() { return mIndexBufferIndex; } public final int getColorBuffer() { return mColorBufferIndex; } public final int getIndexCount() { return mIndexCount; } public boolean getFixedPoint() { return (mCoordinateType == GL10.GL_FIXED); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import com.google.android.maps.GeoPoint; /** * Library for some use useful latitude/longitude math */ public class GeoUtils { private static int EARTH_RADIUS_KM = 6371; public static int MILLION = 1000000; /** * Computes the distance in kilometers between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Distance between the two points in kilometers. */ public static double distanceKm(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM; } /** * Computes the distance in kilometers between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Distance between the two points in kilometers. */ public static double distanceKm(GeoPoint p1, GeoPoint p2) { double lat1 = p1.getLatitudeE6() / (double)MILLION; double lon1 = p1.getLongitudeE6() / (double)MILLION; double lat2 = p2.getLatitudeE6() / (double)MILLION; double lon2 = p2.getLongitudeE6() / (double)MILLION; return distanceKm(lat1, lon1, lat2, lon2); } /** * Computes the bearing in degrees between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ public static double bearing(GeoPoint p1, GeoPoint p2) { double lat1 = p1.getLatitudeE6() / (double) MILLION; double lon1 = p1.getLongitudeE6() / (double) MILLION; double lat2 = p2.getLatitudeE6() / (double) MILLION; double lon2 = p2.getLongitudeE6() / (double) MILLION; return bearing(lat1, lon1, lat2, lon2); } /** * Computes the bearing in degrees between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ public static double bearing(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad); double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad); return radToBearing(Math.atan2(y, x)); } /** * Converts an angle in radians to degrees */ public static double radToBearing(double rad) { return (Math.toDegrees(rad) + 360) % 360; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.drawable.BitmapDrawable; import android.hardware.SensorListener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.SystemClock; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; public class RadarView extends View implements SensorListener, LocationListener { private static final long RETAIN_GPS_MILLIS = 10000L; private Paint mGridPaint; private Paint mErasePaint; private float mOrientation; private double mTargetLat; private double mTargetLon; private double mMyLocationLat; private double mMyLocationLon; private int mLastScale = -1; private String[] mDistanceScale = new String[4]; private static float KM_PER_METERS = 0.001f; private static float METERS_PER_KM = 1000f; /** * These are the list of choices for the radius of the outer circle on the * screen when using metric units. All items are in kilometers. This array is * used to choose the scale of the radar display. */ private static double mMetricScaleChoices[] = { 100 * KM_PER_METERS, 200 * KM_PER_METERS, 400 * KM_PER_METERS, 1, 2, 4, 8, 20, 40, 100, 200, 400, 1000, 2000, 4000, 10000, 20000, 40000, 80000 }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #METERS_PER_KM}. (This * array is for metric measurements.) */ private static float mMetricDisplayUnitsPerKm[] = { METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for metric measurements.) */ private static String mMetricDisplayFormats[] = { "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.1fkm", "%.1fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm" }; /** * This array holds the formatting string used to display the distance on * each ring of the radar screen. (This array is for metric measurements.) */ private static String mMetricScaleFormats[] = { "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm" }; private static float KM_PER_YARDS = 0.0009144f; private static float KM_PER_MILES = 1.609344f; private static float YARDS_PER_KM = 1093.6133f; private static float MILES_PER_KM = 0.621371192f; /** * These are the list of choices for the radius of the outer circle on the * screen when using standard units. All items are in kilometers. This array is * used to choose the scale of the radar display. */ private static double mEnglishScaleChoices[] = { 100 * KM_PER_YARDS, 200 * KM_PER_YARDS, 400 * KM_PER_YARDS, 1000 * KM_PER_YARDS, 1 * KM_PER_MILES, 2 * KM_PER_MILES, 4 * KM_PER_MILES, 8 * KM_PER_MILES, 20 * KM_PER_MILES, 40 * KM_PER_MILES, 100 * KM_PER_MILES, 200 * KM_PER_MILES, 400 * KM_PER_MILES, 1000 * KM_PER_MILES, 2000 * KM_PER_MILES, 4000 * KM_PER_MILES, 10000 * KM_PER_MILES, 20000 * KM_PER_MILES, 40000 * KM_PER_MILES, 80000 * KM_PER_MILES }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #YARDS_PER_KM}. (This * array is for standard measurements.) */ private static float mEnglishDisplayUnitsPerKm[] = { YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for standard measurements.) */ private static String mEnglishDisplayFormats[] = { "%.0fyd", "%.0fyd", "%.0fyd", "%.0fyd", "%.1fmi", "%.1fmi", "%.1fmi", "%.1fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi" }; /** * This array holds the formatting string used to display the distance on * each ring of the radar screen. (This array is for standard measurements.) */ private static String mEnglishScaleFormats[] = { "%.0fyd", "%.0fyd", "%.0fyd", "%.0fyd", "%.2fmi", "%.1fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi" }; /** * True when we have know our own location */ private boolean mHaveLocation = false; /** * The view that will display the distance text */ private TextView mDistanceView; /** * Distance to target, in KM */ private double mDistance; /** * Bearing to target, in degrees */ private double mBearing; /** * Ratio of the distance to the target to the radius of the outermost ring on the radar screen */ private float mDistanceRatio; /** * Utility rect for calculating the ring labels */ private Rect mTextBounds = new Rect(); /** * The bitmap used to draw the target */ private Bitmap mBlip; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint0; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint1; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint2; /** * Time in millis when the most recent sweep began */ private long mSweepTime; /** * True if the sweep has not yet intersected the blip */ private boolean mSweepBefore; /** * Time in millis when the sweep last crossed the blip */ private long mBlipTime; /** * True if the display should use metric units; false if the display should use standard * units */ private boolean mUseMetric; /** * Time in millis for the last time GPS reported a location */ private long mLastGpsFixTime = 0L; /** * The last location reported by the network provider. Use this if we can't get a location from * GPS */ private Location mNetworkLocation; /** * True if GPS is reporting a location */ private boolean mGpsAvailable; /** * True if the network provider is reporting a location */ private boolean mNetworkAvailable; public RadarView(Context context) { this(context, null); } public RadarView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RadarView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Paint used for the rings and ring text mGridPaint = new Paint(); mGridPaint.setColor(0xFF00FF00); mGridPaint.setAntiAlias(true); mGridPaint.setStyle(Style.STROKE); mGridPaint.setStrokeWidth(1.0f); mGridPaint.setTextSize(10.0f); mGridPaint.setTextAlign(Align.CENTER); // Paint used to erase the rectangle behing the ring text mErasePaint = new Paint(); mErasePaint.setColor(0xFF191919); mErasePaint.setStyle(Style.FILL); // Outer ring of the sweep mSweepPaint0 = new Paint(); mSweepPaint0.setColor(0xFF33FF33); mSweepPaint0.setAntiAlias(true); mSweepPaint0.setStyle(Style.STROKE); mSweepPaint0.setStrokeWidth(2f); // Middle ring of the sweep mSweepPaint1 = new Paint(); mSweepPaint1.setColor(0x7733FF33); mSweepPaint1.setAntiAlias(true); mSweepPaint1.setStyle(Style.STROKE); mSweepPaint1.setStrokeWidth(2f); // Inner ring of the sweep mSweepPaint2 = new Paint(); mSweepPaint2.setColor(0x3333FF33); mSweepPaint2.setAntiAlias(true); mSweepPaint2.setStyle(Style.STROKE); mSweepPaint2.setStrokeWidth(2f); mBlip = ((BitmapDrawable)getResources().getDrawable(R.drawable.blip)).getBitmap(); } /** * Sets the target to track on the radar * @param latE6 Latitude of the target, multiplied by 1,000,000 * @param lonE6 Longitude of the target, multiplied by 1,000,000 */ public void setTarget(int latE6, int lonE6) { mTargetLat = latE6 / (double) GeoUtils.MILLION; mTargetLon = lonE6 / (double) GeoUtils.MILLION; } /** * Sets the view that we will use to report distance * * @param t The text view used to report distance */ public void setDistanceView(TextView t) { mDistanceView = t; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int center = getWidth() / 2; int radius = center - 8; // Draw the rings final Paint gridPaint = mGridPaint; canvas.drawCircle(center, center, radius, gridPaint); canvas.drawCircle(center, center, radius * 3 / 4, gridPaint); canvas.drawCircle(center, center, radius >> 1, gridPaint); canvas.drawCircle(center, center, radius >> 2, gridPaint); int blipRadius = (int) (mDistanceRatio * radius); final long now = SystemClock.uptimeMillis(); if (mSweepTime > 0 && mHaveLocation) { // Draw the sweep. Radius is determined by how long ago it started long sweepDifference = now - mSweepTime; if (sweepDifference < 512L) { int sweepRadius = (int) (((radius + 6) * sweepDifference) >> 9); canvas.drawCircle(center, center, sweepRadius, mSweepPaint0); canvas.drawCircle(center, center, sweepRadius - 2, mSweepPaint1); canvas.drawCircle(center, center, sweepRadius - 4, mSweepPaint2); // Note when the sweep has passed the blip boolean before = sweepRadius < blipRadius; if (!before && mSweepBefore) { mSweepBefore = false; mBlipTime = now; } } else { mSweepTime = now + 1000; mSweepBefore = true; } postInvalidate(); } // Draw horizontal and vertical lines canvas.drawLine(center, center - (radius >> 2) + 6, center, center - radius - 6, gridPaint); canvas.drawLine(center, center + (radius >> 2) - 6 , center, center + radius + 6, gridPaint); canvas.drawLine(center - (radius >> 2) + 6, center, center - radius - 6, center, gridPaint); canvas.drawLine(center + (radius >> 2) - 6, center, center + radius + 6, center, gridPaint); // Draw X in the center of the screen canvas.drawLine(center - 4, center - 4, center + 4, center + 4, gridPaint); canvas.drawLine(center - 4, center + 4, center + 4, center - 4, gridPaint); if (mHaveLocation) { double bearingToTarget = mBearing - mOrientation; double drawingAngle = Math.toRadians(bearingToTarget) - (Math.PI / 2); float cos = (float) Math.cos(drawingAngle); float sin = (float) Math.sin(drawingAngle); // Draw the text for the rings final String[] distanceScale = mDistanceScale; addText(canvas, distanceScale[0], center, center + (radius >> 2)); addText(canvas, distanceScale[1], center, center + (radius >> 1)); addText(canvas, distanceScale[2], center, center + radius * 3 / 4); addText(canvas, distanceScale[3], center, center + radius); // Draw the blip. Alpha is based on how long ago the sweep crossed the blip long blipDifference = now - mBlipTime; gridPaint.setAlpha(255 - (int)((128 * blipDifference) >> 10)); canvas.drawBitmap(mBlip, center + (cos * blipRadius) - 8 , center + (sin * blipRadius) - 8, gridPaint); gridPaint.setAlpha(255); } } private void addText(Canvas canvas, String str, int x, int y) { mGridPaint.getTextBounds(str, 0, str.length(), mTextBounds); mTextBounds.offset(x - (mTextBounds.width() >> 1), y); mTextBounds.inset(-2, -2); canvas.drawRect(mTextBounds, mErasePaint); canvas.drawText(str, x, y, mGridPaint); } public void onAccuracyChanged(int sensor, int accuracy) { } /** * Called when we get a new value from the compass * * @see android.hardware.SensorListener#onSensorChanged(int, float[]) */ public void onSensorChanged(int sensor, float[] values) { mOrientation = values[0]; postInvalidate(); } /** * Called when a location provider has a new location to report * * @see android.location.LocationListener#onLocationChanged(android.location.Location) */ public void onLocationChanged(Location location) { if (!mHaveLocation) { mHaveLocation = true; } final long now = SystemClock.uptimeMillis(); boolean useLocation = false; final String provider = location.getProvider(); if (LocationManager.GPS_PROVIDER.equals(provider)) { // Use GPS if available mLastGpsFixTime = SystemClock.uptimeMillis(); useLocation = true; } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) { // Use network provider if GPS is getting stale useLocation = now - mLastGpsFixTime > RETAIN_GPS_MILLIS; if (mNetworkLocation == null) { mNetworkLocation = new Location(location); } else { mNetworkLocation.set(location); } mLastGpsFixTime = 0L; } if (useLocation) { mMyLocationLat = location.getLatitude(); mMyLocationLon = location.getLongitude(); mDistance = GeoUtils.distanceKm(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon); mBearing = GeoUtils.bearing(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon); updateDistance(mDistance); } } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } /** * Called when a location provider has changed its availability. * * @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle) */ public void onStatusChanged(String provider, int status, Bundle extras) { if (LocationManager.GPS_PROVIDER.equals(provider)) { switch (status) { case LocationProvider.AVAILABLE: mGpsAvailable = true; break; case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: mGpsAvailable = false; if (mNetworkLocation != null && mNetworkAvailable) { // Fallback to network location mLastGpsFixTime = 0L; onLocationChanged(mNetworkLocation); } else { handleUnknownLocation(); } break; } } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) { switch (status) { case LocationProvider.AVAILABLE: mNetworkAvailable = true; break; case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: mNetworkAvailable = false; if (!mGpsAvailable) { handleUnknownLocation(); } break; } } } /** * Called when we no longer have a valid lcoation. */ private void handleUnknownLocation() { mHaveLocation = false; mDistanceView.setText(R.string.scanning); } /** * Update state to reflect whether we are using metric or standard units. * * @param useMetric True if the display should use metric units */ public void setUseMetric(boolean useMetric) { mUseMetric = useMetric; mLastScale = -1; if (mHaveLocation) { updateDistance(mDistance); } invalidate(); } /** * Update our state to reflect a new distance to the target. This may require * choosing a new scale for the radar rings. * * @param distanceKm The new distance to the target */ private void updateDistance(double distanceKm) { final double[] scaleChoices; final float[] displayUnitsPerKm; final String[] displayFormats; final String[] scaleFormats; String distanceStr = null; if (mUseMetric) { scaleChoices = mMetricScaleChoices; displayUnitsPerKm = mMetricDisplayUnitsPerKm; displayFormats = mMetricDisplayFormats; scaleFormats = mMetricScaleFormats; } else { scaleChoices = mEnglishScaleChoices; displayUnitsPerKm = mEnglishDisplayUnitsPerKm; displayFormats = mEnglishDisplayFormats; scaleFormats = mEnglishScaleFormats; } int count = scaleChoices.length; for (int i = 0; i < count; i++) { if (distanceKm < scaleChoices[i] || i == (count - 1)) { String format = displayFormats[i]; double distanceDisplay = distanceKm * displayUnitsPerKm[i]; if (mLastScale != i) { mLastScale = i; String scaleFormat = scaleFormats[i]; float scaleDistance = (float) (scaleChoices[i] * displayUnitsPerKm[i]); mDistanceScale[0] = String.format(scaleFormat, (scaleDistance / 4)); mDistanceScale[1] = String.format(scaleFormat, (scaleDistance / 2)); mDistanceScale[2] = String.format(scaleFormat, (scaleDistance * 3 / 4)); mDistanceScale[3] = String.format(scaleFormat, scaleDistance); } mDistanceRatio = (float) (mDistance / scaleChoices[mLastScale]); distanceStr = String.format(format, distanceDisplay); break; } } mDistanceView.setText(distanceStr); } /** * Turn on the sweep animation starting with the next draw */ public void startSweep() { mSweepTime = SystemClock.uptimeMillis(); mSweepBefore = true; } /** * Turn off the sweep animation */ public void stopSweep() { mSweepTime = 0L; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.SensorManager; import android.location.LocationManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.widget.TextView; /** * Simple Activity wrapper that hosts a {@link RadarView} * */ public class RadarActivity extends Activity { private static final int LOCATION_UPDATE_INTERVAL_MILLIS = 1000; private static final int MENU_STANDARD = Menu.FIRST + 1; private static final int MENU_METRIC = Menu.FIRST + 2; private static final String RADAR = "radar"; private static final String PREF_METRIC = "metric"; private SensorManager mSensorManager; private RadarView mRadar; private LocationManager mLocationManager; private SharedPreferences mPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.radar); mRadar = (RadarView) findViewById(R.id.radar); mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE); mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Metric or standard units? mPrefs = getSharedPreferences(RADAR, MODE_PRIVATE); boolean useMetric = mPrefs.getBoolean(PREF_METRIC, false); mRadar.setUseMetric(useMetric); // Read the target from our intent Intent i = getIntent(); int latE6 = (int)(i.getFloatExtra("latitude", 0) * GeoUtils.MILLION); int lonE6 = (int)(i.getFloatExtra("longitude", 0) * GeoUtils.MILLION); mRadar.setTarget(latE6, lonE6); mRadar.setDistanceView((TextView) findViewById(R.id.distance)); } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(mRadar, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_GAME); // Start animating the radar screen mRadar.startSweep(); // Register for location updates mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_UPDATE_INTERVAL_MILLIS, 1, mRadar); mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_INTERVAL_MILLIS, 1, mRadar); } @Override protected void onPause() { mSensorManager.unregisterListener(mRadar); mLocationManager.removeUpdates(mRadar); // Stop animating the radar screen mRadar.stopSweep(); super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_STANDARD, 0, R.string.menu_standard) .setIcon(R.drawable.ic_menu_standard) .setAlphabeticShortcut('A'); menu.add(0, MENU_METRIC, 0, R.string.menu_metric) .setIcon(R.drawable.ic_menu_metric) .setAlphabeticShortcut('C'); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_STANDARD: { setUseMetric(false); return true; } case MENU_METRIC: { setUseMetric(true); return true; } } return super.onOptionsItemSelected(item); } private void setUseMetric(boolean useMetric) { SharedPreferences.Editor e = mPrefs.edit(); e.putBoolean(PREF_METRIC, useMetric); e.commit(); mRadar.setUseMetric(useMetric); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.panoramio; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; /** * Utilities for loading a bitmap from a URL * */ public class BitmapUtils { private static final String TAG = "Panoramio"; private static final int IO_BUFFER_SIZE = 4 * 1024; /** * Loads a bitmap from the specified url. This can take a while, so it should not * be called from the UI thread. * * @param url The location of the bitmap asset * * @return The bitmap, or null if it could not be loaded */ public static Bitmap loadBitmap(String url) { Bitmap bitmap = null; InputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); copy(in, out); out.flush(); final byte[] data = dataStream.toByteArray(); bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } catch (IOException e) { Log.e(TAG, "Could not load Bitmap from: " + url); } finally { closeStream(in); closeStream(out); } return bitmap; } /** * Closes the specified stream. * * @param stream The stream to close. */ private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { android.util.Log.e(TAG, "Could not close stream", e); } } } /** * Copy the content of the input stream into the output stream, using a * temporary byte array buffer whose size is defined by * {@link #IO_BUFFER_SIZE}. * * @param in The input stream to copy from. * @param out The output stream to copy to. * @throws IOException If any error occurs during the copy. */ private static void copy(InputStream in, OutputStream out) throws IOException { byte[] b = new byte[IO_BUFFER_SIZE]; int read; while ((read = in.read(b)) != -1) { out.write(b, 0, read); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.panoramio; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Bitmap; import android.os.Handler; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.WeakReference; import java.net.URI; import java.util.ArrayList; /** * This class is responsible for downloading and parsing the search results for * a particular area. All of the work is done on a separate thread, and progress * is reported back through the DataSetObserver set in * {@link #addObserver(DataSetObserver). State is held in memory by in memory * maintained by a single instance of the ImageManager class. */ public class ImageManager { private static final String TAG = "Panoramio"; /** * Base URL for Panoramio's web API */ private static final String THUMBNAIL_URL = "//www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to=20&miny=%f&minx=%f&maxy=%f&maxx=%f&size=thumbnail"; /** * Used to post results back to the UI thread */ private Handler mHandler = new Handler(); /** * Holds the single instance of a ImageManager that is shared by the process. */ private static ImageManager sInstance; /** * Holds the images and related data that have been downloaded */ private ArrayList<PanoramioItem> mImages = new ArrayList<PanoramioItem>(); /** * Observers interested in changes to the current search results */ private ArrayList<WeakReference<DataSetObserver>> mObservers = new ArrayList<WeakReference<DataSetObserver>>(); /** * True if we are in the process of loading */ private boolean mLoading; private Context mContext; /** * Key for an Intent extra. The value is the zoom level selected by the user. */ public static final String ZOOM_EXTRA = "zoom"; /** * Key for an Intent extra. The value is the latitude of the center of the search * area chosen by the user. */ public static final String LATITUDE_E6_EXTRA = "latitudeE6"; /** * Key for an Intent extra. The value is the latitude of the center of the search * area chosen by the user. */ public static final String LONGITUDE_E6_EXTRA = "longitudeE6"; /** * Key for an Intent extra. The value is an item to display */ public static final String PANORAMIO_ITEM_EXTRA = "item"; public static ImageManager getInstance(Context c) { if (sInstance == null) { sInstance = new ImageManager(c.getApplicationContext()); } return sInstance; } private ImageManager(Context c) { mContext = c; } /** * @return True if we are still loading content */ public boolean isLoading() { return mLoading; } /** * Clear all downloaded content */ public void clear() { mImages.clear(); notifyObservers(); } /** * Add an item to and notify observers of the change. * @param item The item to add */ private void add(PanoramioItem item) { mImages.add(item); notifyObservers(); } /** * @return The number of items displayed so far */ public int size() { return mImages.size(); } /** * Gets the item at the specified position */ public PanoramioItem get(int position) { return mImages.get(position); } /** * Adds an observer to be notified when the set of items held by this ImageManager changes. */ public void addObserver(DataSetObserver observer) { WeakReference<DataSetObserver> obs = new WeakReference<DataSetObserver>(observer); mObservers.add(obs); } /** * Load a new set of search results for the specified area. * * @param minLong The minimum longitude for the search area * @param maxLong The maximum longitude for the search area * @param minLat The minimum latitude for the search area * @param maxLat The minimum latitude for the search area */ public void load(float minLong, float maxLong, float minLat, float maxLat) { mLoading = true; new NetworkThread(minLong, maxLong, minLat, maxLat).start(); } /** * Called when something changes in our data set. Cleans up any weak references that * are no longer valid along the way. */ private void notifyObservers() { final ArrayList<WeakReference<DataSetObserver>> observers = mObservers; final int count = observers.size(); for (int i = count - 1; i >= 0; i--) { WeakReference<DataSetObserver> weak = observers.get(i); DataSetObserver obs = weak.get(); if (obs != null) { obs.onChanged(); } else { observers.remove(i); } } } /** * This thread does the actual work of downloading and parsing data. * */ private class NetworkThread extends Thread { private float mMinLong; private float mMaxLong; private float mMinLat; private float mMaxLat; public NetworkThread(float minLong, float maxLong, float minLat, float maxLat) { mMinLong = minLong; mMaxLong = maxLong; mMinLat = minLat; mMaxLat = maxLat; } @Override public void run() { String url = THUMBNAIL_URL; url = String.format(url, mMinLat, mMinLong, mMaxLat, mMaxLong); try { URI uri = new URI("http", url, null); HttpGet get = new HttpGet(uri); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); String str = convertStreamToString(entity.getContent()); JSONObject json = new JSONObject(str); parse(json); } catch (Exception e) { Log.e(TAG, e.toString()); } } private void parse(JSONObject json) { try { JSONArray array = json.getJSONArray("photos"); int count = array.length(); for (int i = 0; i < count; i++) { JSONObject obj = array.getJSONObject(i); long id = obj.getLong("photo_id"); String title = obj.getString("photo_title"); String owner = obj.getString("owner_name"); String thumb = obj.getString("photo_file_url"); String ownerUrl = obj.getString("owner_url"); String photoUrl = obj.getString("photo_url"); double latitude = obj.getDouble("latitude"); double longitude = obj.getDouble("longitude"); Bitmap b = BitmapUtils.loadBitmap(thumb); if (title == null) { title = mContext.getString(R.string.untitled); } final PanoramioItem item = new PanoramioItem(id, thumb, b, (int) (latitude * Panoramio.MILLION), (int) (longitude * Panoramio.MILLION), title, owner, ownerUrl, photoUrl); final boolean done = i == count - 1; mHandler.post(new Runnable() { public void run() { sInstance.mLoading = !done; sInstance.add(item); } }); } } catch (JSONException e) { Log.e(TAG, e.toString()); } } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8*1024); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.panoramio; import com.google.android.maps.GeoPoint; import android.graphics.Bitmap; import android.os.Parcel; import android.os.Parcelable; /** * Holds one item returned from the Panoramio server. This includes * the bitmap along with other meta info. * */ public class PanoramioItem implements Parcelable { private long mId; private Bitmap mBitmap; private GeoPoint mLocation; private String mTitle; private String mOwner; private String mThumbUrl; private String mOwnerUrl; private String mPhotoUrl; public PanoramioItem(Parcel in) { mId = in.readLong(); mBitmap = Bitmap.CREATOR.createFromParcel(in); mLocation = new GeoPoint(in.readInt(), in.readInt()); mTitle = in.readString(); mOwner = in.readString(); mThumbUrl = in.readString(); mOwnerUrl = in.readString(); mPhotoUrl = in.readString(); } public PanoramioItem(long id, String thumbUrl, Bitmap b, int latitudeE6, int longitudeE6, String title, String owner, String ownerUrl, String photoUrl) { mBitmap = b; mLocation = new GeoPoint(latitudeE6, longitudeE6); mTitle = title; mOwner = owner; mThumbUrl = thumbUrl; mOwnerUrl = ownerUrl; mPhotoUrl = photoUrl; } public long getId() { return mId; } public Bitmap getBitmap() { return mBitmap; } public GeoPoint getLocation() { return mLocation; } public String getTitle() { return mTitle; } public String getOwner() { return mOwner; } public String getThumbUrl() { return mThumbUrl; } public String getOwnerUrl() { return mOwnerUrl; } public String getPhotoUrl() { return mPhotoUrl; } public static final Parcelable.Creator<PanoramioItem> CREATOR = new Parcelable.Creator<PanoramioItem>() { public PanoramioItem createFromParcel(Parcel in) { return new PanoramioItem(in); } public PanoramioItem[] newArray(int size) { return new PanoramioItem[size]; } }; public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int flags) { parcel.writeLong(mId); mBitmap.writeToParcel(parcel, 0); parcel.writeInt(mLocation.getLatitudeE6()); parcel.writeInt(mLocation.getLongitudeE6()); parcel.writeString(mTitle); parcel.writeString(mOwner); parcel.writeString(mThumbUrl); parcel.writeString(mOwnerUrl); parcel.writeString(mPhotoUrl); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.panoramio; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.database.DataSetObserver; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.widget.ListView; /** * Activity which displays the list of images. */ public class ImageList extends ListActivity { ImageManager mImageManager; private MyDataSetObserver mObserver = new MyDataSetObserver(); /** * The zoom level the user chose when picking the search area */ private int mZoom; /** * The latitude of the center of the search area chosen by the user */ private int mLatitudeE6; /** * The longitude of the center of the search area chosen by the user */ private int mLongitudeE6; /** * Observer used to turn the progress indicator off when the {@link ImageManager} is * done downloading. */ private class MyDataSetObserver extends DataSetObserver { @Override public void onChanged() { if (!mImageManager.isLoading()) { getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_OFF); } } @Override public void onInvalidated() { } } @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); mImageManager = ImageManager.getInstance(this); ListView listView = getListView(); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View footer = inflater.inflate(R.layout.list_footer, listView, false); listView.addFooterView(footer, null, false); setListAdapter(new ImageAdapter(this)); // Theme.Light sets a background on our list. listView.setBackgroundDrawable(null); if (mImageManager.isLoading()) { getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); mImageManager.addObserver(mObserver); } // Read the user's search area from the intent Intent i = getIntent(); mZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE); mLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE); mLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { PanoramioItem item = mImageManager.get(position); // Create an intent to show a particular item. // Pass the user's search area along so the next activity can use it Intent i = new Intent(this, ViewImage.class); i.putExtra(ImageManager.PANORAMIO_ITEM_EXTRA, item); i.putExtra(ImageManager.ZOOM_EXTRA, mZoom); i.putExtra(ImageManager.LATITUDE_E6_EXTRA, mLatitudeE6); i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, mLongitudeE6); startActivity(i); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.panoramio; import com.google.android.maps.GeoPoint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ImageView; import android.widget.TextView; /** * Activity which displays a single image. */ public class ViewImage extends Activity { private static final String TAG = "Panoramio"; private static final int MENU_RADAR = Menu.FIRST + 1; private static final int MENU_MAP = Menu.FIRST + 2; private static final int MENU_AUTHOR = Menu.FIRST + 3; private static final int MENU_VIEW = Menu.FIRST + 4; private static final int DIALOG_NO_RADAR = 1; PanoramioItem mItem; private Handler mHandler; private ImageView mImage; private TextView mTitle; private TextView mOwner; private View mContent; private int mMapZoom; private int mMapLatitudeE6; private int mMapLongitudeE6; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.view_image); // Remember the user's original search area and zoom level Intent i = getIntent(); mItem = i.getParcelableExtra(ImageManager.PANORAMIO_ITEM_EXTRA); mMapZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE); mMapLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE); mMapLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE); mHandler = new Handler(); mContent = findViewById(R.id.content); mImage = (ImageView) findViewById(R.id.image); mTitle = (TextView) findViewById(R.id.title); mOwner = (TextView) findViewById(R.id.owner); mContent.setVisibility(View.GONE); getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); new LoadThread().start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_RADAR, 0, R.string.menu_radar) .setIcon(R.drawable.ic_menu_radar) .setAlphabeticShortcut('R'); menu.add(0, MENU_MAP, 0, R.string.menu_map) .setIcon(R.drawable.ic_menu_map) .setAlphabeticShortcut('M'); menu.add(0, MENU_AUTHOR, 0, R.string.menu_author) .setIcon(R.drawable.ic_menu_author) .setAlphabeticShortcut('A'); menu.add(0, MENU_VIEW, 0, R.string.menu_view) .setIcon(android.R.drawable.ic_menu_view) .setAlphabeticShortcut('V'); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_RADAR: { // Launch the radar activity (if it is installed) Intent i = new Intent("com.google.android.radar.SHOW_RADAR"); GeoPoint location = mItem.getLocation(); i.putExtra("latitude", (float)(location.getLatitudeE6() / 1000000f)); i.putExtra("longitude", (float)(location.getLongitudeE6() / 1000000f)); try { startActivity(i); } catch (ActivityNotFoundException ex) { showDialog(DIALOG_NO_RADAR); } return true; } case MENU_MAP: { // Display our custom map Intent i = new Intent(this, ViewMap.class); i.putExtra(ImageManager.PANORAMIO_ITEM_EXTRA, mItem); i.putExtra(ImageManager.ZOOM_EXTRA, mMapZoom); i.putExtra(ImageManager.LATITUDE_E6_EXTRA, mMapLatitudeE6); i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, mMapLongitudeE6); startActivity(i); return true; } case MENU_AUTHOR: { // Display the author info page in the browser Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(mItem.getOwnerUrl())); startActivity(i); return true; } case MENU_VIEW: { // Display the photo info page in the browser Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(mItem.getPhotoUrl())); startActivity(i); return true; } } return super.onOptionsItemSelected(item); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_NO_RADAR: AlertDialog.Builder builder = new AlertDialog.Builder(this); return builder.setTitle(R.string.no_radar_title) .setMessage(R.string.no_radar) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.ok, null).create(); } return null; } /** * Utility to load a larger version of the image in a separate thread. * */ private class LoadThread extends Thread { public LoadThread() { } @Override public void run() { try { String uri = mItem.getThumbUrl(); uri = uri.replace("thumbnail", "medium"); final Bitmap b = BitmapUtils.loadBitmap(uri); mHandler.post(new Runnable() { public void run() { mImage.setImageBitmap(b); mTitle.setText(mItem.getTitle()); mOwner.setText(mItem.getOwner()); mContent.setVisibility(View.VISIBLE); getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_OFF); } }); } catch (Exception e) { Log.e(TAG, e.toString()); } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.panoramio; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; import com.google.android.maps.Projection; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.FrameLayout; import java.util.ArrayList; import java.util.List; /** * Displays a custom map which shows our current location and the location * where the photo was taken. */ public class ViewMap extends MapActivity { private MapView mMapView; private MyLocationOverlay mMyLocationOverlay; ArrayList<PanoramioItem> mItems = null; private PanoramioItem mItem; private Drawable mMarker; private int mMarkerXOffset; private int mMarkerYOffset; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout frame = new FrameLayout(this); mMapView = new MapView(this, "MapViewCompassDemo_DummyAPIKey"); frame.addView(mMapView, new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); setContentView(frame); mMyLocationOverlay = new MyLocationOverlay(this, mMapView); mMarker = getResources().getDrawable(R.drawable.map_pin); // Make sure to give mMarker bounds so it will draw in the overlay final int intrinsicWidth = mMarker.getIntrinsicWidth(); final int intrinsicHeight = mMarker.getIntrinsicHeight(); mMarker.setBounds(0, 0, intrinsicWidth, intrinsicHeight); mMarkerXOffset = -(intrinsicWidth / 2); mMarkerYOffset = -intrinsicHeight; // Read the item we are displaying from the intent, along with the // parameters used to set up the map Intent i = getIntent(); mItem = i.getParcelableExtra(ImageManager.PANORAMIO_ITEM_EXTRA); int mapZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE); int mapLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE); int mapLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE); final List<Overlay> overlays = mMapView.getOverlays(); overlays.add(mMyLocationOverlay); overlays.add(new PanoramioOverlay()); final MapController controller = mMapView.getController(); if (mapZoom != Integer.MIN_VALUE && mapLatitudeE6 != Integer.MIN_VALUE && mapLongitudeE6 != Integer.MIN_VALUE) { controller.setZoom(mapZoom); controller.setCenter(new GeoPoint(mapLatitudeE6, mapLongitudeE6)); } else { controller.setZoom(15); mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() { controller.animateTo(mMyLocationOverlay.getMyLocation()); } }); } mMapView.setClickable(true); mMapView.setEnabled(true); mMapView.setSatellite(true); addZoomControls(frame); } @Override protected void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); } @Override protected void onStop() { mMyLocationOverlay.disableMyLocation(); super.onStop(); } /** * Get the zoom controls and add them to the bottom of the map */ private void addZoomControls(FrameLayout frame) { View zoomControls = mMapView.getZoomControls(); FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL); frame.addView(zoomControls, p); } @Override protected boolean isRouteDisplayed() { return false; } /** * Custom overlay to display the Panoramio pushpin */ public class PanoramioOverlay extends Overlay { @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { if (!shadow) { Point point = new Point(); Projection p = mapView.getProjection(); p.toPixels(mItem.getLocation(), point); super.draw(canvas, mapView, shadow); drawAt(canvas, mMarker, point.x + mMarkerXOffset, point.y + mMarkerYOffset, shadow); } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.panoramio; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.FrameLayout; /** * Activity which lets the user select a search area * */ public class Panoramio extends MapActivity implements OnClickListener { private MapView mMapView; private MyLocationOverlay mMyLocationOverlay; private ImageManager mImageManager; public static final int MILLION = 1000000; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mImageManager = ImageManager.getInstance(this); FrameLayout frame = (FrameLayout) findViewById(R.id.frame); Button goButton = (Button) findViewById(R.id.go); goButton.setOnClickListener(this); // Add the map view to the frame mMapView = new MapView(this, "Panoramio_DummyAPIKey"); frame.addView(mMapView, new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); // Create an overlay to show current location mMyLocationOverlay = new MyLocationOverlay(this, mMapView); mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() { mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation()); }}); mMapView.getOverlays().add(mMyLocationOverlay); mMapView.getController().setZoom(15); mMapView.setClickable(true); mMapView.setEnabled(true); mMapView.setSatellite(true); addZoomControls(frame); } @Override protected void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); } @Override protected void onStop() { mMyLocationOverlay.disableMyLocation(); super.onStop(); } /** * Add zoom controls to our frame layout */ private void addZoomControls(FrameLayout frame) { // Get the zoom controls and add them to the bottom of the map View zoomControls = mMapView.getZoomControls(); FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL); frame.addView(zoomControls, p); } @Override protected boolean isRouteDisplayed() { return false; } /** * Starts a new search when the user clicks the search button. */ public void onClick(View view) { // Get the search area int latHalfSpan = mMapView.getLatitudeSpan() >> 1; int longHalfSpan = mMapView.getLongitudeSpan() >> 1; // Remember how the map was displayed so we can show it the same way later GeoPoint center = mMapView.getMapCenter(); int zoom = mMapView.getZoomLevel(); int latitudeE6 = center.getLatitudeE6(); int longitudeE6 = center.getLongitudeE6(); Intent i = new Intent(this, ImageList.class); i.putExtra(ImageManager.ZOOM_EXTRA, zoom); i.putExtra(ImageManager.LATITUDE_E6_EXTRA, latitudeE6); i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, longitudeE6); float minLong = ((float) (longitudeE6 - longHalfSpan)) / MILLION; float maxLong = ((float) (longitudeE6 + longHalfSpan)) / MILLION; float minLat = ((float) (latitudeE6 - latHalfSpan)) / MILLION; float maxLat = ((float) (latitudeE6 + latHalfSpan)) / MILLION; mImageManager.clear(); // Start downloading mImageManager.load(minLong, maxLong, minLat, maxLat); // Show results startActivity(i); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.panoramio; import android.content.Context; import android.database.DataSetObserver; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; /** * Adapter used to bind data for the main list of photos */ public class ImageAdapter extends BaseAdapter { /** * Maintains the state of our data */ private ImageManager mImageManager; private Context mContext; private MyDataSetObserver mObserver; /** * Used by the {@link ImageManager} to report changes in the list back to * this adapter. */ private class MyDataSetObserver extends DataSetObserver { @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onInvalidated() { notifyDataSetInvalidated(); } } public ImageAdapter(Context c) { mImageManager = ImageManager.getInstance(c); mContext = c; mObserver = new MyDataSetObserver(); mImageManager.addObserver(mObserver); } /** * Returns the number of images to display * * @see android.widget.Adapter#getCount() */ public int getCount() { return mImageManager.size(); } /** * Returns the image at a specified position * * @see android.widget.Adapter#getItem(int) */ public Object getItem(int position) { return mImageManager.get(position); } /** * Returns the id of an image at a specified position * * @see android.widget.Adapter#getItemId(int) */ public long getItemId(int position) { PanoramioItem s = mImageManager.get(position); return s.getId(); } /** * Returns a view to display the image at a specified position * * @param position The position to display * @param convertView An existing view that we can reuse. May be null. * @param parent The parent view that will eventually hold the view we return. * @return A view to display the image at a specified position */ public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { // Make up a new view LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.image_item, null); } else { // Use convertView if it is available view = convertView; } PanoramioItem s = mImageManager.get(position); ImageView i = (ImageView) view.findViewById(R.id.image); i.setImageBitmap(s.getBitmap()); i.setBackgroundResource(R.drawable.picture_frame); TextView t = (TextView) view.findViewById(R.id.title); t.setText(s.getTitle()); t = (TextView) view.findViewById(R.id.owner); t.setText(s.getOwner()); return view; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.lolcat; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Lolcat builder activity. * * Instructions: * (1) Take photo of cat using Camera * (2) Run LolcatActivity * (3) Pick photo * (4) Add caption(s) * (5) Save and share * * See README.txt for a list of currently-missing features and known bugs. */ public class LolcatActivity extends Activity implements View.OnClickListener { private static final String TAG = "LolcatActivity"; // Location on the SD card for saving lolcat images private static final String LOLCAT_SAVE_DIRECTORY = "lolcats/"; // Mime type / format / extension we use (must be self-consistent!) private static final String SAVED_IMAGE_EXTENSION = ".png"; private static final Bitmap.CompressFormat SAVED_IMAGE_COMPRESS_FORMAT = Bitmap.CompressFormat.PNG; private static final String SAVED_IMAGE_MIME_TYPE = "image/png"; // UI Elements private Button mPickButton; private Button mCaptionButton; private Button mSaveButton; private Button mClearCaptionButton; private Button mClearPhotoButton; private LolcatView mLolcatView; private AlertDialog mCaptionDialog; private ProgressDialog mSaveProgressDialog; private AlertDialog mSaveSuccessDialog; private Handler mHandler; private Uri mPhotoUri; private String mSavedImageFilename; private Uri mSavedImageUri; private MediaScannerConnection mMediaScannerConnection; // Request codes used with startActivityForResult() private static final int PHOTO_PICKED = 1; // Dialog IDs private static final int DIALOG_CAPTION = 1; private static final int DIALOG_SAVE_PROGRESS = 2; private static final int DIALOG_SAVE_SUCCESS = 3; // Keys used with onSaveInstanceState() private static final String PHOTO_URI_KEY = "photo_uri"; private static final String SAVED_IMAGE_FILENAME_KEY = "saved_image_filename"; private static final String SAVED_IMAGE_URI_KEY = "saved_image_uri"; private static final String TOP_CAPTION_KEY = "top_caption"; private static final String BOTTOM_CAPTION_KEY = "bottom_caption"; private static final String CAPTION_POSITIONS_KEY = "caption_positions"; @Override protected void onCreate(Bundle icicle) { Log.i(TAG, "onCreate()... icicle = " + icicle); super.onCreate(icicle); setContentView(R.layout.lolcat_activity); // Look up various UI elements mPickButton = (Button) findViewById(R.id.pick_button); mPickButton.setOnClickListener(this); mCaptionButton = (Button) findViewById(R.id.caption_button); mCaptionButton.setOnClickListener(this); mSaveButton = (Button) findViewById(R.id.save_button); mSaveButton.setOnClickListener(this); mClearCaptionButton = (Button) findViewById(R.id.clear_caption_button); // This button doesn't exist in portrait mode. if (mClearCaptionButton != null) mClearCaptionButton.setOnClickListener(this); mClearPhotoButton = (Button) findViewById(R.id.clear_photo_button); mClearPhotoButton.setOnClickListener(this); mLolcatView = (LolcatView) findViewById(R.id.main_image); // Need one of these to call back to the UI thread // (and run AlertDialog.show(), for that matter) mHandler = new Handler(); mMediaScannerConnection = new MediaScannerConnection(this, mMediaScanConnClient); if (icicle != null) { Log.i(TAG, "- reloading state from icicle!"); restoreStateFromIcicle(icicle); } } @Override protected void onResume() { Log.i(TAG, "onResume()..."); super.onResume(); updateButtons(); } @Override protected void onSaveInstanceState(Bundle outState) { Log.i(TAG, "onSaveInstanceState()..."); super.onSaveInstanceState(outState); // State from the Activity: outState.putParcelable(PHOTO_URI_KEY, mPhotoUri); outState.putString(SAVED_IMAGE_FILENAME_KEY, mSavedImageFilename); outState.putParcelable(SAVED_IMAGE_URI_KEY, mSavedImageUri); // State from the LolcatView: // (TODO: Consider making Caption objects, or even the LolcatView // itself, Parcelable? Probably overkill, though...) outState.putString(TOP_CAPTION_KEY, mLolcatView.getTopCaption()); outState.putString(BOTTOM_CAPTION_KEY, mLolcatView.getBottomCaption()); outState.putIntArray(CAPTION_POSITIONS_KEY, mLolcatView.getCaptionPositions()); } /** * Restores the activity state from the specified icicle. * @see onCreate() * @see onSaveInstanceState() */ private void restoreStateFromIcicle(Bundle icicle) { Log.i(TAG, "restoreStateFromIcicle()..."); // State of the Activity: Uri photoUri = icicle.getParcelable(PHOTO_URI_KEY); Log.i(TAG, " - photoUri: " + photoUri); if (photoUri != null) { loadPhoto(photoUri); } mSavedImageFilename = icicle.getString(SAVED_IMAGE_FILENAME_KEY); mSavedImageUri = icicle.getParcelable(SAVED_IMAGE_URI_KEY); // State of the LolcatView: String topCaption = icicle.getString(TOP_CAPTION_KEY); String bottomCaption = icicle.getString(BOTTOM_CAPTION_KEY); int[] captionPositions = icicle.getIntArray(CAPTION_POSITIONS_KEY); Log.i(TAG, " - captions: '" + topCaption + "', '" + bottomCaption + "'"); if (!TextUtils.isEmpty(topCaption) || !TextUtils.isEmpty(bottomCaption)) { mLolcatView.setCaptions(topCaption, bottomCaption); mLolcatView.setCaptionPositions(captionPositions); } } @Override protected void onDestroy() { Log.i(TAG, "onDestroy()..."); super.onDestroy(); clearPhoto(); // Free up some resources, and force a GC } // View.OnClickListener implementation public void onClick(View view) { int id = view.getId(); Log.i(TAG, "onClick(View " + view + ", id " + id + ")..."); switch (id) { case R.id.pick_button: Log.i(TAG, "onClick: pick_button..."); Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); // Note: we could have the "crop" UI come up here by // default by doing this: // intent.putExtra("crop", "true"); // (But watch out: if you do that, the Intent that comes // back to onActivityResult() will have the URI (of the // cropped image) in the "action" field, not the "data" // field!) startActivityForResult(intent, PHOTO_PICKED); break; case R.id.caption_button: Log.i(TAG, "onClick: caption_button..."); showCaptionDialog(); break; case R.id.save_button: Log.i(TAG, "onClick: save_button..."); saveImage(); break; case R.id.clear_caption_button: Log.i(TAG, "onClick: clear_caption_button..."); clearCaptions(); updateButtons(); break; case R.id.clear_photo_button: Log.i(TAG, "onClick: clear_photo_button..."); clearPhoto(); // Also does clearCaptions() updateButtons(); break; default: Log.w(TAG, "Click from unexpected source: " + view + ", id " + id); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "onActivityResult(request " + requestCode + ", result " + resultCode + ", data " + data + ")..."); if (resultCode != RESULT_OK) { Log.i(TAG, "==> result " + resultCode + " from subactivity! Ignoring..."); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } if (requestCode == PHOTO_PICKED) { // "data" is an Intent containing (presumably) a URI like // "content://media/external/images/media/3". if (data == null) { Log.w(TAG, "Null data, but RESULT_OK, from image picker!"); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } if (data.getData() == null) { Log.w(TAG, "'data' intent from image picker contained no data!"); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } loadPhoto(data.getData()); updateButtons(); } } /** * Updates the enabled/disabled state of the onscreen buttons. */ private void updateButtons() { Log.i(TAG, "updateButtons()..."); // mPickButton is always enabled. // Do we have a valid photo and/or caption(s) yet? Drawable d = mLolcatView.getDrawable(); // Log.i(TAG, "===> current mLolcatView drawable: " + d); boolean validPhoto = (d != null); boolean validCaption = mLolcatView.hasValidCaption(); mCaptionButton.setText(validCaption ? R.string.lolcat_change_captions : R.string.lolcat_add_captions); mCaptionButton.setEnabled(validPhoto); mSaveButton.setEnabled(validPhoto && validCaption); if (mClearCaptionButton != null) { mClearCaptionButton.setEnabled(validPhoto && validCaption); } mClearPhotoButton.setEnabled(validPhoto); } /** * Clears out any already-entered captions for this lolcat. */ private void clearCaptions() { mLolcatView.clearCaptions(); // Clear the text fields in the caption dialog too. if (mCaptionDialog != null) { EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); topText.setText(""); EditText bottomText = (EditText) mCaptionDialog.findViewById(R.id.bottom_edittext); bottomText.setText(""); topText.requestFocus(); } // This also invalidates any image we've previously written to the // SD card... mSavedImageFilename = null; mSavedImageUri = null; } /** * Completely resets the UI to its initial state, with no photo * loaded, and no captions. */ private void clearPhoto() { mLolcatView.clear(); mPhotoUri = null; mSavedImageFilename = null; mSavedImageUri = null; clearCaptions(); // Force a gc (to be sure to reclaim the memory used by our // potentially huge bitmap): System.gc(); } /** * Loads the image with the specified Uri into the UI. */ private void loadPhoto(Uri uri) { Log.i(TAG, "loadPhoto: uri = " + uri); clearPhoto(); // Be sure to release the previous bitmap // before creating another one mPhotoUri = uri; // A new photo always starts out uncaptioned. clearCaptions(); // Load the selected photo into our ImageView. mLolcatView.loadFromUri(mPhotoUri); } private void showCaptionDialog() { // If the dialog already exists, always reset focus to the top // item each time it comes up. if (mCaptionDialog != null) { EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); topText.requestFocus(); } showDialog(DIALOG_CAPTION); } private void showSaveSuccessDialog() { // If the dialog already exists, update the body text based on the // current values of mSavedImageFilename and mSavedImageUri // (otherwise the dialog will still have the body text from when // it was first created!) if (mSaveSuccessDialog != null) { updateSaveSuccessDialogBody(); } showDialog(DIALOG_SAVE_SUCCESS); } private void updateSaveSuccessDialogBody() { if (mSaveSuccessDialog == null) { throw new IllegalStateException( "updateSaveSuccessDialogBody: mSaveSuccessDialog hasn't been created yet"); } String dialogBody = String.format( getResources().getString(R.string.lolcat_save_succeeded_dialog_body_format), mSavedImageFilename, mSavedImageUri); mSaveSuccessDialog.setMessage(dialogBody); } @Override protected Dialog onCreateDialog(int id) { Log.i(TAG, "onCreateDialog(id " + id + ")..."); // This is only run once (per dialog), the very first time // a given dialog needs to be shown. switch (id) { case DIALOG_CAPTION: LayoutInflater factory = LayoutInflater.from(this); final View textEntryView = factory.inflate(R.layout.lolcat_caption_dialog, null); mCaptionDialog = new AlertDialog.Builder(this) .setTitle(R.string.lolcat_caption_dialog_title) .setIcon(0) .setView(textEntryView) .setPositiveButton( R.string.lolcat_caption_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Caption dialog: OK..."); updateCaptionsFromDialog(); } }) .setNegativeButton( R.string.lolcat_caption_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Caption dialog: CANCEL..."); // Nothing to do here (for now at least) } }) .create(); return mCaptionDialog; case DIALOG_SAVE_PROGRESS: mSaveProgressDialog = new ProgressDialog(this); mSaveProgressDialog.setMessage(getResources().getString(R.string.lolcat_saving)); mSaveProgressDialog.setIndeterminate(true); mSaveProgressDialog.setCancelable(false); return mSaveProgressDialog; case DIALOG_SAVE_SUCCESS: mSaveSuccessDialog = new AlertDialog.Builder(this) .setTitle(R.string.lolcat_save_succeeded_dialog_title) .setIcon(0) .setPositiveButton( R.string.lolcat_save_succeeded_dialog_view, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: View..."); viewSavedImage(); } }) .setNeutralButton( R.string.lolcat_save_succeeded_dialog_share, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: Share..."); shareSavedImage(); } }) .setNegativeButton( R.string.lolcat_save_succeeded_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: CANCEL..."); // Nothing to do here... } }) .create(); updateSaveSuccessDialogBody(); return mSaveSuccessDialog; default: Log.w(TAG, "Request for unexpected dialog id: " + id); break; } return null; } private void updateCaptionsFromDialog() { Log.i(TAG, "updateCaptionsFromDialog()..."); if (mCaptionDialog == null) { Log.w(TAG, "updateCaptionsFromDialog: null mCaptionDialog!"); return; } // Get the two caption strings: EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); Log.i(TAG, "- Top editText: " + topText); String topString = topText.getText().toString(); Log.i(TAG, " - String: '" + topString + "'"); EditText bottomText = (EditText) mCaptionDialog.findViewById(R.id.bottom_edittext); Log.i(TAG, "- Bottom editText: " + bottomText); String bottomString = bottomText.getText().toString(); Log.i(TAG, " - String: '" + bottomString + "'"); mLolcatView.setCaptions(topString, bottomString); updateButtons(); } /** * Kicks off the process of saving the LolcatView's working Bitmap to * the SD card, in preparation for viewing it later and/or sharing it. */ private void saveImage() { Log.i(TAG, "saveImage()..."); // First of all, bring up a progress dialog. showDialog(DIALOG_SAVE_PROGRESS); // We now need to save the bitmap to the SD card, and then ask the // MediaScanner to scan it. Do the actual work of all this in a // helper thread, since it's fairly slow (and will occasionally // ANR if we do it here in the UI thread.) Thread t = new Thread() { public void run() { Log.i(TAG, "Running worker thread..."); saveImageInternal(); } }; t.start(); // Next steps: // - saveImageInternal() // - onMediaScannerConnected() // - onScanCompleted } /** * Saves the LolcatView's working Bitmap to the SD card, in * preparation for viewing it later and/or sharing it. * * The bitmap will be saved as a new file in the directory * LOLCAT_SAVE_DIRECTORY, with an automatically-generated filename * based on the current time. It also connects to the * MediaScanner service, since we'll need to scan that new file (in * order to get a Uri we can then VIEW or share.) * * This method is run in a worker thread; @see saveImage(). */ private void saveImageInternal() { Log.i(TAG, "saveImageInternal()..."); // TODO: Currently we save the bitmap to a file on the sdcard, // then ask the MediaScanner to scan it (which gives us a Uri we // can then do an ACTION_VIEW on.) But rather than doing these // separate steps, maybe there's some easy way (given an // OutputStream) to directly talk to the MediaProvider // (i.e. com.android.provider.MediaStore) and say "here's an // image, please save it somwhere and return the URI to me"... // Save the bitmap to a file on the sdcard. // (Based on similar code in MusicUtils.java.) // TODO: Make this filename more human-readable? Maybe "Lolcat-YYYY-MM-DD-HHMMSS.png"? String filename = Environment.getExternalStorageDirectory() + "/" + LOLCAT_SAVE_DIRECTORY + String.valueOf(System.currentTimeMillis() + SAVED_IMAGE_EXTENSION); Log.i(TAG, "- filename: '" + filename + "'"); if (ensureFileExists(filename)) { try { OutputStream outstream = new FileOutputStream(filename); Bitmap bitmap = mLolcatView.getWorkingBitmap(); boolean success = bitmap.compress(SAVED_IMAGE_COMPRESS_FORMAT, 100, outstream); Log.i(TAG, "- success code from Bitmap.compress: " + success); outstream.close(); if (success) { Log.i(TAG, "- Saved! filename = " + filename); mSavedImageFilename = filename; // Ok, now we need to get the MediaScanner to scan the // file we just wrote. Step 1 is to get our // MediaScannerConnection object to connect to the // MediaScanner service. mMediaScannerConnection.connect(); // See onMediaScannerConnected() for the next step } else { Log.w(TAG, "Bitmap.compress failed: bitmap " + bitmap + ", filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } } catch (FileNotFoundException e) { Log.w(TAG, "error creating file", e); onSaveFailed(R.string.lolcat_save_failed); } catch (IOException e) { Log.w(TAG, "error creating file", e); onSaveFailed(R.string.lolcat_save_failed); } } else { Log.w(TAG, "ensureFileExists failed for filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } } // // MediaScanner-related code // /** * android.media.MediaScannerConnection.MediaScannerConnectionClient implementation. */ private MediaScannerConnection.MediaScannerConnectionClient mMediaScanConnClient = new MediaScannerConnection.MediaScannerConnectionClient() { /** * Called when a connection to the MediaScanner service has been established. */ public void onMediaScannerConnected() { Log.i(TAG, "MediaScannerConnectionClient.onMediaScannerConnected..."); // The next step happens in the UI thread: mHandler.post(new Runnable() { public void run() { LolcatActivity.this.onMediaScannerConnected(); } }); } /** * Called when the media scanner has finished scanning a file. * @param path the path to the file that has been scanned. * @param uri the Uri for the file if the scanning operation succeeded * and the file was added to the media database, or null if scanning failed. */ public void onScanCompleted(final String path, final Uri uri) { Log.i(TAG, "MediaScannerConnectionClient.onScanCompleted: path " + path + ", uri " + uri); // Just run the "real" onScanCompleted() method in the UI thread: mHandler.post(new Runnable() { public void run() { LolcatActivity.this.onScanCompleted(path, uri); } }); } }; /** * This method is called when our MediaScannerConnection successfully * connects to the MediaScanner service. At that point we fire off a * request to scan the lolcat image we just saved. * * This needs to run in the UI thread, so it's called from * mMediaScanConnClient's onMediaScannerConnected() method via our Handler. */ private void onMediaScannerConnected() { Log.i(TAG, "onMediaScannerConnected()..."); // Update the message in the progress dialog... mSaveProgressDialog.setMessage(getResources().getString(R.string.lolcat_scanning)); // Fire off a request to the MediaScanner service to scan this // file; we'll get notified when the scan completes. Log.i(TAG, "- Requesting scan for file: " + mSavedImageFilename); mMediaScannerConnection.scanFile(mSavedImageFilename, null /* mimeType */); // Next step: mMediaScanConnClient will get an onScanCompleted() callback, // which calls our own onScanCompleted() method via our Handler. } /** * Updates the UI after the media scanner finishes the scanFile() * request we issued from onMediaScannerConnected(). * * This needs to run in the UI thread, so it's called from * mMediaScanConnClient's onScanCompleted() method via our Handler. */ private void onScanCompleted(String path, final Uri uri) { Log.i(TAG, "onScanCompleted: path " + path + ", uri " + uri); mMediaScannerConnection.disconnect(); if (uri == null) { Log.w(TAG, "onScanCompleted: scan failed."); mSavedImageUri = null; onSaveFailed(R.string.lolcat_scan_failed); return; } // Success! dismissDialog(DIALOG_SAVE_PROGRESS); // We can now access the saved lolcat image using the specified Uri. mSavedImageUri = uri; // Bring up a success dialog, giving the user the option to go to // the pictures app (so you can share the image). showSaveSuccessDialog(); } // // Other misc utility methods // /** * Ensure that the specified file exists on the SD card, creating it * if necessary. * * Copied from MediaProvider / MusicUtils. * * @return true if the file already exists, or we * successfully created it. */ private static boolean ensureFileExists(String path) { File file = new File(path); if (file.exists()) { return true; } else { // we will not attempt to create the first directory in the path // (for example, do not create /sdcard if the SD card is not mounted) int secondSlash = path.indexOf('/', 1); if (secondSlash < 1) return false; String directoryPath = path.substring(0, secondSlash); File directory = new File(directoryPath); if (!directory.exists()) return false; file.getParentFile().mkdirs(); try { return file.createNewFile(); } catch (IOException ioe) { Log.w(TAG, "File creation failed", ioe); } return false; } } /** * Updates the UI after a failure anywhere in the bitmap saving / scanning * sequence. */ private void onSaveFailed(int errorMessageResId) { dismissDialog(DIALOG_SAVE_PROGRESS); Toast.makeText(this, errorMessageResId, Toast.LENGTH_SHORT).show(); } /** * Goes to the Pictures app for the specified URI. */ private void viewSavedImage(Uri uri) { Log.i(TAG, "viewSavedImage(" + uri + ")..."); if (uri == null) { Log.w(TAG, "viewSavedImage: null uri!"); return; } Intent intent = new Intent(Intent.ACTION_VIEW, uri); Log.i(TAG, "- running startActivity... Intent = " + intent); startActivity(intent); } private void viewSavedImage() { viewSavedImage(mSavedImageUri); } /** * Shares the image with the specified URI. */ private void shareSavedImage(Uri uri) { Log.i(TAG, "shareSavedImage(" + uri + ")..."); if (uri == null) { Log.w(TAG, "shareSavedImage: null uri!"); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType(SAVED_IMAGE_MIME_TYPE); intent.putExtra(Intent.EXTRA_STREAM, uri); try { startActivity( Intent.createChooser( intent, getResources().getString(R.string.lolcat_sendImage_label))); } catch (android.content.ActivityNotFoundException ex) { Log.w(TAG, "shareSavedImage: startActivity failed", ex); Toast.makeText(this, R.string.lolcat_share_failed, Toast.LENGTH_SHORT).show(); } } private void shareSavedImage() { shareSavedImage(mSavedImageUri); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.lolcat; 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.RectF; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.ImageView; /** * Lolcat-specific subclass of ImageView, which manages the various * scaled-down Bitmaps and knows how to render and manipulate the * image captions. */ public class LolcatView extends ImageView { private static final String TAG = "LolcatView"; // Standard lolcat size is 500x375. (But to preserve the original // image's aspect ratio, we rescale so that the larger dimension ends // up being 500 pixels.) private static final float SCALED_IMAGE_MAX_DIMENSION = 500f; // Other standard lolcat image parameters private static final int FONT_SIZE = 44; private Bitmap mScaledBitmap; // The photo picked by the user, scaled-down private Bitmap mWorkingBitmap; // The Bitmap we render the caption text into // Current state of the captions. // TODO: This array currently has a hardcoded length of 2 (for "top" // and "bottom" captions), but eventually should support as many // captions as the user wants to add. private final Caption[] mCaptions = new Caption[] { new Caption(), new Caption() }; // State used while dragging a caption around private boolean mDragging; private int mDragCaptionIndex; // index of the caption (in mCaptions[]) that's being dragged private int mTouchDownX, mTouchDownY; private final Rect mInitialDragBox = new Rect(); private final Rect mCurrentDragBox = new Rect(); private final RectF mCurrentDragBoxF = new RectF(); // used in onDraw() private final RectF mTransformedDragBoxF = new RectF(); // used in onDraw() private final Rect mTmpRect = new Rect(); public LolcatView(Context context) { super(context); } public LolcatView(Context context, AttributeSet attrs) { super(context, attrs); } public LolcatView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public Bitmap getWorkingBitmap() { return mWorkingBitmap; } public String getTopCaption() { return mCaptions[0].caption; } public String getBottomCaption() { return mCaptions[1].caption; } /** * @return true if the user has set caption(s) for this LolcatView. */ public boolean hasValidCaption() { return !TextUtils.isEmpty(mCaptions[0].caption) || !TextUtils.isEmpty(mCaptions[1].caption); } public void clear() { mScaledBitmap = null; mWorkingBitmap = null; setImageDrawable(null); // TODO: Anything else we need to do here to release resources // associated with this object, like maybe the Bitmap that got // created by the previous setImageURI() call? } public void loadFromUri(Uri uri) { // For now, directly load the specified Uri. setImageURI(uri); // TODO: Rather than calling setImageURI() with the URI of // the (full-size) photo, it would be better to turn the URI into // a scaled-down Bitmap right here, and load *that* into ourself. // I'd do that basically the same way that ImageView.setImageURI does it: // [ . . . ] // android.graphics.BitmapFactory.nativeDecodeStream(Native Method) // android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:304) // android.graphics.drawable.Drawable.createFromStream(Drawable.java:635) // android.widget.ImageView.resolveUri(ImageView.java:477) // android.widget.ImageView.setImageURI(ImageView.java:281) // [ . . . ] // But for now let's let ImageView do the work: we call setImageURI (above) // and immediately pull out a Bitmap (below). // Stash away a scaled-down bitmap. // TODO: is it safe to assume this will always be a BitmapDrawable? BitmapDrawable drawable = (BitmapDrawable) getDrawable(); Log.i(TAG, "===> current drawable: " + drawable); Bitmap fullSizeBitmap = drawable.getBitmap(); Log.i(TAG, "===> fullSizeBitmap: " + fullSizeBitmap + " dimensions: " + fullSizeBitmap.getWidth() + " x " + fullSizeBitmap.getHeight()); Bitmap.Config config = fullSizeBitmap.getConfig(); Log.i(TAG, " - config = " + config); // Standard lolcat size is 500x375. But we don't want to distort // the image if it isn't 4x3, so let's just set the larger // dimension to 500 pixels and preserve the source aspect ratio. float origWidth = fullSizeBitmap.getWidth(); float origHeight = fullSizeBitmap.getHeight(); float aspect = origWidth / origHeight; Log.i(TAG, " - aspect = " + aspect + "(" + origWidth + " x " + origHeight + ")"); float scaleFactor = ((aspect > 1.0) ? origWidth : origHeight) / SCALED_IMAGE_MAX_DIMENSION; int scaledWidth = Math.round(origWidth / scaleFactor); int scaledHeight = Math.round(origHeight / scaleFactor); mScaledBitmap = Bitmap.createScaledBitmap(fullSizeBitmap, scaledWidth, scaledHeight, true /* filter */); Log.i(TAG, " ===> mScaledBitmap: " + mScaledBitmap + " dimensions: " + mScaledBitmap.getWidth() + " x " + mScaledBitmap.getHeight()); Log.i(TAG, " isMutable = " + mScaledBitmap.isMutable()); } /** * Sets the captions for this LolcatView. */ public void setCaptions(String topCaption, String bottomCaption) { Log.i(TAG, "setCaptions: '" + topCaption + "', '" + bottomCaption + "'"); if (topCaption == null) topCaption = ""; if (bottomCaption == null) bottomCaption = ""; mCaptions[0].caption = topCaption; mCaptions[1].caption = bottomCaption; // If the user clears a caption, reset its position (so that it'll // come back in the default position if the user re-adds it.) if (TextUtils.isEmpty(mCaptions[0].caption)) { Log.i(TAG, "- invalidating position of caption 0..."); mCaptions[0].positionValid = false; } if (TextUtils.isEmpty(mCaptions[1].caption)) { Log.i(TAG, "- invalidating position of caption 1..."); mCaptions[1].positionValid = false; } // And *any* time the captions change, blow away the cached // caption bounding boxes to make sure we'll recompute them in // renderCaptions(). mCaptions[0].captionBoundingBox = null; mCaptions[1].captionBoundingBox = null; renderCaptions(mCaptions); } /** * Clears the captions for this LolcatView. */ public void clearCaptions() { setCaptions("", ""); } /** * Renders this LolcatView's current image captions into our * underlying ImageView. * * We start with a scaled-down version of the photo originally chosed * by the user (mScaledBitmap), make a mutable copy (mWorkingBitmap), * render the specified strings into the bitmap, and show the * resulting image onscreen. */ public void renderCaptions(Caption[] captions) { // TODO: handle an arbitrary array of strings, rather than // assuming "top" and "bottom" captions. String topString = captions[0].caption; boolean topStringValid = !TextUtils.isEmpty(topString); String bottomString = captions[1].caption; boolean bottomStringValid = !TextUtils.isEmpty(bottomString); Log.i(TAG, "renderCaptions: '" + topString + "', '" + bottomString + "'"); if (mScaledBitmap == null) return; // Make a fresh (mutable) copy of the scaled-down photo Bitmap, // and render the desired text into it. Bitmap.Config config = mScaledBitmap.getConfig(); Log.i(TAG, " - mScaledBitmap config = " + config); mWorkingBitmap = mScaledBitmap.copy(config, true /* isMutable */); Log.i(TAG, " ===> mWorkingBitmap: " + mWorkingBitmap + " dimensions: " + mWorkingBitmap.getWidth() + " x " + mWorkingBitmap.getHeight()); Log.i(TAG, " isMutable = " + mWorkingBitmap.isMutable()); Canvas canvas = new Canvas(mWorkingBitmap); Log.i(TAG, "- Canvas: " + canvas + " dimensions: " + canvas.getWidth() + " x " + canvas.getHeight()); Paint textPaint = new Paint(); textPaint.setAntiAlias(true); textPaint.setTextSize(FONT_SIZE); textPaint.setColor(0xFFFFFFFF); Log.i(TAG, "- Paint: " + textPaint); Typeface face = textPaint.getTypeface(); Log.i(TAG, "- default typeface: " + face); // The most standard font for lolcat captions is Impact. (Arial // Black is also common.) Unfortunately we don't have either of // these on the device by default; the closest we can do is // DroidSans-Bold: face = Typeface.DEFAULT_BOLD; Log.i(TAG, "- new face: " + face); textPaint.setTypeface(face); // Look up the positions of the captions, or if this is our very // first time rendering them, initialize the positions to default // values. final int edgeBorder = 20; final int fontHeight = textPaint.getFontMetricsInt(null); Log.i(TAG, "- fontHeight: " + fontHeight); Log.i(TAG, "- Caption positioning:"); int topX = 0; int topY = 0; if (topStringValid) { if (mCaptions[0].positionValid) { topX = mCaptions[0].xpos; topY = mCaptions[0].ypos; Log.i(TAG, " - TOP: already had a valid position: " + topX + ", " + topY); } else { // Start off with the "top" caption at the upper-left: topX = edgeBorder; topY = edgeBorder + (fontHeight * 3 / 4); mCaptions[0].setPosition(topX, topY); Log.i(TAG, " - TOP: initializing to default position: " + topX + ", " + topY); } } int bottomX = 0; int bottomY = 0; if (bottomStringValid) { if (mCaptions[1].positionValid) { bottomX = mCaptions[1].xpos; bottomY = mCaptions[1].ypos; Log.i(TAG, " - Bottom: already had a valid position: " + bottomX + ", " + bottomY); } else { // Start off with the "bottom" caption at the lower-right: final int bottomTextWidth = (int) textPaint.measureText(bottomString); Log.i(TAG, "- bottomTextWidth (" + bottomString + "): " + bottomTextWidth); bottomX = canvas.getWidth() - edgeBorder - bottomTextWidth; bottomY = canvas.getHeight() - edgeBorder; mCaptions[1].setPosition(bottomX, bottomY); Log.i(TAG, " - BOTTOM: initializing to default position: " + bottomX + ", " + bottomY); } } // Finally, render the text. // Standard lolcat captions are drawn in white with a heavy black // outline (i.e. white fill, black stroke). Our Canvas APIs can't // do this exactly, though. // We *could* get something decent-looking using a regular // drop-shadow, like this: // textPaint.setShadowLayer(3.0f, 3, 3, 0xff000000); // but instead let's simulate the "outline" style by drawing the // text 4 separate times, with the shadow in a different direction // each time. // (TODO: This is a hack, and still doesn't look as good // as a real "white fill, black stroke" style.) final float shadowRadius = 2.0f; final int shadowOffset = 2; final int shadowColor = 0xff000000; // TODO: Right now we use offsets of 2,2 / -2,2 / 2,-2 / -2,-2 . // But 2,0 / 0,2 / -2,0 / 0,-2 might look better. textPaint.setShadowLayer(shadowRadius, shadowOffset, shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, -shadowOffset, shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, shadowOffset, -shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, -shadowOffset, -shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // Stash away bounding boxes for the captions if this // is our first time rendering them. // Watch out: the x/y position we use for drawing the text is // actually the *lower* left corner of the bounding box... int textWidth, textHeight; if (topStringValid && mCaptions[0].captionBoundingBox == null) { Log.i(TAG, "- Computing initial bounding box for top caption..."); textPaint.getTextBounds(topString, 0, topString.length(), mTmpRect); textWidth = mTmpRect.width(); textHeight = mTmpRect.height(); Log.i(TAG, "- text dimensions: " + textWidth + " x " + textHeight); mCaptions[0].captionBoundingBox = new Rect(topX, topY - textHeight, topX + textWidth, topY); Log.i(TAG, "- RESULTING RECT: " + mCaptions[0].captionBoundingBox); } if (bottomStringValid && mCaptions[1].captionBoundingBox == null) { Log.i(TAG, "- Computing initial bounding box for bottom caption..."); textPaint.getTextBounds(bottomString, 0, bottomString.length(), mTmpRect); textWidth = mTmpRect.width(); textHeight = mTmpRect.height(); Log.i(TAG, "- text dimensions: " + textWidth + " x " + textHeight); mCaptions[1].captionBoundingBox = new Rect(bottomX, bottomY - textHeight, bottomX + textWidth, bottomY); Log.i(TAG, "- RESULTING RECT: " + mCaptions[1].captionBoundingBox); } // Finally, display the new Bitmap to the user: setImageBitmap(mWorkingBitmap); } @Override protected void onDraw(Canvas canvas) { Log.i(TAG, "onDraw: " + canvas); super.onDraw(canvas); if (mDragging) { Log.i(TAG, "- dragging! Drawing box at " + mCurrentDragBox); // mCurrentDragBox is in the coordinate system of our bitmap; // need to convert it into the coordinate system of the // overall LolcatView. // // To transform between coordinate systems we need to apply the // transformation described by the ImageView's matrix *and* also // account for our left and top padding. Matrix m = getImageMatrix(); mCurrentDragBoxF.set(mCurrentDragBox); m.mapRect(mTransformedDragBoxF, mCurrentDragBoxF); mTransformedDragBoxF.offset(getPaddingLeft(), getPaddingTop()); Paint p = new Paint(); p.setColor(0xFFFFFFFF); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(2f); Log.i(TAG, "- Paint: " + p); canvas.drawRect(mTransformedDragBoxF, p); } } @Override public boolean onTouchEvent(MotionEvent ev) { Log.i(TAG, "onTouchEvent: " + ev); // Watch out: ev.getX() and ev.getY() are in the // coordinate system of the entire LolcatView, although // all the positions and rects we use here (like // mCaptions[].captionBoundingBox) are relative to the bitmap // that's drawn inside the LolcatView. // // To transform between coordinate systems we need to apply the // transformation described by the ImageView's matrix *and* also // account for our left and top padding. Matrix m = getImageMatrix(); Matrix invertedMatrix = new Matrix(); m.invert(invertedMatrix); float[] pointArray = new float[] { ev.getX() - getPaddingLeft(), ev.getY() - getPaddingTop() }; Log.i(TAG, " - BEFORE: pointArray = " + pointArray[0] + ", " + pointArray[1]); // Transform the X/Y position of the DOWN event back into bitmap coords invertedMatrix.mapPoints(pointArray); Log.i(TAG, " - AFTER: pointArray = " + pointArray[0] + ", " + pointArray[1]); int eventX = (int) pointArray[0]; int eventY = (int) pointArray[1]; int action = ev.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: if (mDragging) { Log.w(TAG, "Got an ACTION_DOWN, but we were already dragging!"); mDragging = false; // and continue as if we weren't already dragging... } if (!hasValidCaption()) { Log.w(TAG, "No caption(s) yet; ignoring this ACTION_DOWN event."); return true; } // See if this DOWN event hit one of the caption bounding // boxes. If so, start dragging! for (int i = 0; i < mCaptions.length; i++) { Rect boundingBox = mCaptions[i].captionBoundingBox; Log.i(TAG, " - boundingBox #" + i + ": " + boundingBox + "..."); if (boundingBox != null) { // Expand the bounding box by a fudge factor to make it // easier to hit (since touch accuracy is pretty poor on a // real device, and the captions are fairly small...) mTmpRect.set(boundingBox); final int touchPositionSlop = 40; // pixels mTmpRect.inset(-touchPositionSlop, -touchPositionSlop); Log.i(TAG, " - Checking expanded bounding box #" + i + ": " + mTmpRect + "..."); if (mTmpRect.contains(eventX, eventY)) { Log.i(TAG, " - Hit! " + mCaptions[i]); mDragging = true; mDragCaptionIndex = i; break; } } } if (!mDragging) { Log.i(TAG, "- ACTION_DOWN event didn't hit any captions; ignoring."); return true; } mTouchDownX = eventX; mTouchDownY = eventY; mInitialDragBox.set(mCaptions[mDragCaptionIndex].captionBoundingBox); mCurrentDragBox.set(mCaptions[mDragCaptionIndex].captionBoundingBox); invalidate(); return true; case MotionEvent.ACTION_MOVE: if (!mDragging) { return true; } int displacementX = eventX - mTouchDownX; int displacementY = eventY - mTouchDownY; mCurrentDragBox.set(mInitialDragBox); mCurrentDragBox.offset(displacementX, displacementY); invalidate(); return true; case MotionEvent.ACTION_UP: if (!mDragging) { return true; } mDragging = false; // Reposition the selected caption! Log.i(TAG, "- Done dragging! Repositioning caption #" + mDragCaptionIndex + ": " + mCaptions[mDragCaptionIndex]); int offsetX = eventX - mTouchDownX; int offsetY = eventY - mTouchDownY; Log.i(TAG, " - OFFSET: " + offsetX + ", " + offsetY); // Reposition the the caption we just dragged, and blow // away the cached bounding box to make sure it'll get // recomputed in renderCaptions(). mCaptions[mDragCaptionIndex].xpos += offsetX; mCaptions[mDragCaptionIndex].ypos += offsetY; mCaptions[mDragCaptionIndex].captionBoundingBox = null; Log.i(TAG, " - Updated caption: " + mCaptions[mDragCaptionIndex]); // Finally, refresh the screen. renderCaptions(mCaptions); return true; // This case isn't expected to happen. case MotionEvent.ACTION_CANCEL: if (!mDragging) { return true; } mDragging = false; // Refresh the screen. renderCaptions(mCaptions); return true; default: return super.onTouchEvent(ev); } } /** * Returns an array containing the xpos/ypos of each Caption in our * array of captions. (This method and setCaptionPositions() are used * by LolcatActivity to save and restore the activity state across * orientation changes.) */ public int[] getCaptionPositions() { // TODO: mCaptions currently has a hardcoded length of 2 (for // "top" and "bottom" captions). int[] captionPositions = new int[4]; if (mCaptions[0].positionValid) { captionPositions[0] = mCaptions[0].xpos; captionPositions[1] = mCaptions[0].ypos; } else { captionPositions[0] = -1; captionPositions[1] = -1; } if (mCaptions[1].positionValid) { captionPositions[2] = mCaptions[1].xpos; captionPositions[3] = mCaptions[1].ypos; } else { captionPositions[2] = -1; captionPositions[3] = -1; } Log.i(TAG, "getCaptionPositions: returning " + captionPositions); return captionPositions; } /** * Sets the xpos and ypos values of each Caption in our array based on * the specified values. (This method and getCaptionPositions() are * used by LolcatActivity to save and restore the activity state * across orientation changes.) */ public void setCaptionPositions(int[] captionPositions) { // TODO: mCaptions currently has a hardcoded length of 2 (for // "top" and "bottom" captions). Log.i(TAG, "setCaptionPositions(" + captionPositions + ")..."); if (captionPositions[0] < 0) { mCaptions[0].positionValid = false; Log.i(TAG, "- TOP caption: no valid position"); } else { mCaptions[0].setPosition(captionPositions[0], captionPositions[1]); Log.i(TAG, "- TOP caption: got valid position: " + mCaptions[0].xpos + ", " + mCaptions[0].ypos); } if (captionPositions[2] < 0) { mCaptions[1].positionValid = false; Log.i(TAG, "- BOTTOM caption: no valid position"); } else { mCaptions[1].setPosition(captionPositions[2], captionPositions[3]); Log.i(TAG, "- BOTTOM caption: got valid position: " + mCaptions[1].xpos + ", " + mCaptions[1].ypos); } // Finally, refresh the screen. renderCaptions(mCaptions); } /** * Structure used to hold the entire state of a single caption. */ class Caption { public String caption; public Rect captionBoundingBox; // updated by renderCaptions() public int xpos, ypos; public boolean positionValid; public void setPosition(int x, int y) { positionValid = true; xpos = x; ypos = y; // Also blow away the cached bounding box, to make sure it'll // get recomputed in renderCaptions(). captionBoundingBox = null; } @Override public String toString() { return "Caption['" + caption + "'; bbox " + captionBoundingBox + "; pos " + xpos + ", " + ypos + "; posValid = " + positionValid + "]"; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentUris; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import com.google.android.wikinotes.db.WikiNote; /** * A helper class that implements operations required by Activities in the * system. Notably, this includes launching the Activities for edit and * delete. */ public class WikiActivityHelper { public static final int ACTIVITY_EDIT = 1; public static final int ACTIVITY_DELETE = 2; public static final int ACTIVITY_LIST = 3; public static final int ACTIVITY_SEARCH = 4; private Activity mContext; /** * Preferred constructor. * * @param context * the Activity to be used for things like calling * startActivity */ public WikiActivityHelper(Activity context) { mContext = context; } /** * @see #WikiActivityHelper(Activity) */ // intentionally private; tell IDEs not to warn us about it @SuppressWarnings("unused") private WikiActivityHelper() { } /** * If a list of notes is requested, fire the WikiNotes list Content URI * and let the WikiNotesList activity handle it. */ public void listNotes() { Intent i = new Intent(Intent.ACTION_VIEW, WikiNote.Notes.ALL_NOTES_URI); mContext.startActivity(i); } /** * If requested, go back to the start page wikinote by requesting an * intent with the default start page URI */ public void goHome() { Uri startPageURL = Uri .withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, mContext .getResources().getString(R.string.start_page)); Intent startPage = new Intent(Intent.ACTION_VIEW, startPageURL); mContext.startActivity(startPage); } /** * Create an intent to start the WikiNoteEditor using the current title * and body information (if any). */ public void editNote(String mNoteName, Cursor cursor) { // This intent could use the android.intent.action.EDIT for a wiki // note // to invoke, but instead I wanted to demonstrate the mechanism for // invoking // an intent on a known class within the same application directly. // Note // also that the title and body of the note to edit are passed in // using // the extras bundle. Intent i = new Intent(mContext, WikiNoteEditor.class); i.putExtra(WikiNote.Notes.TITLE, mNoteName); String body; if (cursor != null) { body = cursor.getString(cursor .getColumnIndexOrThrow(WikiNote.Notes.BODY)); } else { body = ""; } i.putExtra(WikiNote.Notes.BODY, body); mContext.startActivityForResult(i, ACTIVITY_EDIT); } /** * If requested, delete the current note. The user is prompted to confirm * this operation with a dialog, and if they choose to go ahead with the * deletion, the current activity is finish()ed once the data has been * removed, so that android naturally backtracks to the previous activity. */ public void deleteNote(final Cursor cursor) { new AlertDialog.Builder(mContext) .setTitle( mContext.getResources() .getString(R.string.delete_title)) .setMessage(R.string.delete_message) .setPositiveButton(R.string.yes_button, new OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { Uri noteUri = ContentUris .withAppendedId(WikiNote.Notes.ALL_NOTES_URI, cursor .getInt(0)); mContext.getContentResolver().delete(noteUri, null, null); mContext.setResult(Activity.RESULT_OK); mContext.finish(); } }).setNegativeButton(R.string.no_button, null).show(); } /** * Equivalent to showOutcomeDialog(titleId, msg, false). * * @see #showOutcomeDialog(int, String, boolean) * @param titleId * the resource ID of the title of the dialog window * @param msg * the message to display */ private void showOutcomeDialog(int titleId, String msg) { showOutcomeDialog(titleId, msg, false); } /** * Creates and displays a Dialog with the indicated title and body. If * kill is true, the Dialog calls finish() on the hosting Activity and * restarts it with an identical Intent. This effectively restarts or * refreshes the Activity, so that it can reload whatever data it was * displaying. * * @param titleId * the resource ID of the title of the dialog window * @param msg * the message to display */ private void showOutcomeDialog(int titleId, String msg, final boolean kill) { new AlertDialog.Builder(mContext).setCancelable(false) .setTitle(mContext.getResources().getString(titleId)) .setMessage(msg) .setPositiveButton(R.string.export_dismiss_button, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { if (kill) { // restart the Activity w/ same // Intent Intent intent = mContext .getIntent(); mContext.finish(); mContext.startActivity(intent); } } }).create().show(); } /** * Exports notes to the SD card. Displays Dialogs as appropriate (using * the Activity provided in the constructor as a Context) to inform the * user as to what is going on. */ public void exportNotes() { // first see if an SD card is even present; abort if not if (!Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_missing_sd)); return; } // do a query for all records Cursor c = mContext.managedQuery(WikiNote.Notes.ALL_NOTES_URI, WikiNote.WIKI_EXPORT_PROJECTION, null, null, WikiNote.Notes.DEFAULT_SORT_ORDER); // iterate over all Notes, building up an XML StringBuffer along the // way boolean dataAvailable = c.moveToFirst(); StringBuffer sb = new StringBuffer(); String title, body, created, modified; int cnt = 0; sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<wiki-notes>"); while (dataAvailable) { title = c.getString(c.getColumnIndexOrThrow("title")); body = c.getString(c.getColumnIndexOrThrow("body")); modified = c.getString(c.getColumnIndexOrThrow("modified")); created = c.getString(c.getColumnIndexOrThrow("created")); // do a quick sanity check to make sure the note is worth saving if (!"".equals(title) && !"".equals(body) && title != null && body != null) { sb.append("\n").append("<note>\n\t<title><![CDATA[") .append(title).append("]]></title>\n\t<body><![CDATA["); sb.append(body).append("]]></body>\n\t<created>") .append(created).append("</created>\n\t"); sb.append("<modified>").append(modified) .append("</modified>\n</note>"); cnt++; } dataAvailable = c.moveToNext(); } sb.append("\n</wiki-notes>\n"); // open a file on the SD card under some useful name, and write out // XML FileWriter fw = null; File f = null; try { f = new File(Environment.getExternalStorageDirectory() + "/" + EXPORT_DIR); f.mkdirs(); // EXPORT_FILENAME includes current date+time, for user benefit String fileName = String.format(EXPORT_FILENAME, Calendar .getInstance()); f = new File(Environment.getExternalStorageDirectory() + "/" + EXPORT_DIR + "/" + fileName); if (!f.createNewFile()) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources() .getString(R.string.export_failure_io_error)); return; } fw = new FileWriter(f); fw.write(sb.toString()); } catch (IOException e) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_io_error)); return; } finally { if (fw != null) { try { fw.close(); } catch (IOException ex) { } } } if (f == null) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_io_error)); return; } // Victory! Tell the user and display the filename just written. showOutcomeDialog(R.string.export_success_title, String .format(mContext.getResources() .getString(R.string.export_success), cnt, f.getName())); } /** * Imports records from SD card. Note that this is a destructive * operation: all existing records are destroyed. Displays confirmation * and outcome Dialogs before erasing data and after loading data. * * Note that this is the method that actually does the work; * {@link #importNotes()} is the method that should be called to kick * things off. * * @see #importNotes() */ public void doImport() { // first see if an SD card is even present; abort if not if (!Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.export_failure_missing_sd)); return; } int cnt = 0; FileReader fr = null; ArrayList<StringBuffer[]> records = new ArrayList<StringBuffer[]>(); try { // first, find the file to load fr = new FileReader(new File(Environment .getExternalStorageDirectory() + "/" + IMPORT_FILENAME)); // don't destroy data until AFTER we find a file to import! mContext.getContentResolver() .delete(WikiNote.Notes.ALL_NOTES_URI, null, null); // next, parse that sucker XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(false); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(fr); int eventType = xpp.getEventType(); StringBuffer[] cur = new StringBuffer[4]; int curIdx = -1; while (eventType != XmlPullParser.END_DOCUMENT) { // save the previous note data-holder when we end a <note> tag if (eventType == XmlPullParser.END_TAG && "note".equals(xpp.getName())) { if (cur[0] != null && cur[1] != null && !"".equals(cur[0]) && !"".equals(cur[1])) { records.add(cur); } cur = new StringBuffer[4]; curIdx = -1; } else if (eventType == XmlPullParser.START_TAG && "title".equals(xpp.getName())) { curIdx = 0; } else if (eventType == XmlPullParser.START_TAG && "body".equals(xpp.getName())) { curIdx = 1; } else if (eventType == XmlPullParser.START_TAG && "created".equals(xpp.getName())) { curIdx = 2; } else if (eventType == XmlPullParser.START_TAG && "modified".equals(xpp.getName())) { curIdx = 3; } else if (eventType == XmlPullParser.TEXT && curIdx > -1) { if (cur[curIdx] == null) { cur[curIdx] = new StringBuffer(); } cur[curIdx].append(xpp.getText()); } eventType = xpp.next(); } // we stored data in a stringbuffer so we can skip empty records; // now process the successful records & save to Provider for (StringBuffer[] record : records) { Uri uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, record[0].toString()); ContentValues values = new ContentValues(); values.put("title", record[0].toString().trim()); values.put("body", record[1].toString().trim()); values.put("created", Long.parseLong(record[2].toString() .trim())); values.put("modified", Long.parseLong(record[3].toString() .trim())); if (mContext.getContentResolver().insert(uri, values) != null) { cnt++; } } } catch (FileNotFoundException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_nofile)); return; } catch (XmlPullParserException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_corrupt)); return; } catch (IOException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_io)); return; } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { } } } // Victory! Inform the user. showOutcomeDialog(R.string.import_success_title, String .format(mContext.getResources() .getString(R.string.import_success), cnt), true); } /** * Starts a note import. Essentially this method just displays a Dialog * requesting confirmation from the user for the destructive operation. If * the user confirms, {@link #doImport()} is called. * * @see #doImport() */ public void importNotes() { new AlertDialog.Builder(mContext).setCancelable(true) .setTitle( mContext.getResources() .getString(R.string.import_confirm_title)) .setMessage(R.string.import_confirm_body) .setPositiveButton(R.string.import_confirm_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { doImport(); } }) .setNegativeButton(R.string.import_cancel_button, null).create() .show(); } /** * Launches the email system client to send a mail with the current * message. */ public void mailNote(final Cursor cursor) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_SUBJECT, cursor.getString(cursor .getColumnIndexOrThrow("title"))); String body = String.format(mContext.getResources() .getString(R.string.email_leader), cursor.getString(cursor .getColumnIndexOrThrow("body"))); intent.putExtra(Intent.EXTRA_TEXT, body); mContext.startActivity(Intent.createChooser(intent, "Title:")); } /* Some constants for filename structures. Could conceivably go into * strings.xml, but these don't need to be internationalized, so... */ private static final String EXPORT_DIR = "WikiNotes"; private static final String EXPORT_FILENAME = "WikiNotes_%1$tY-%1$tm-%1$td_%1$tH-%1$tM-%1$tS.xml"; private static final String IMPORT_FILENAME = "WikiNotes-import.xml"; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes.db; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import java.util.HashMap; /** * The Wikinotes Content Provider is the guts of the wikinotes application. It * handles Content URLs to list all wiki notes, retrieve a note by name, or * return a list of matching notes based on text in the body or the title of * the note. It also handles all set up of the database, and reports back MIME * types for the individual notes or lists of notes to help Android route the * data to activities that can display that data (in this case either the * WikiNotes activity itself, or the WikiNotesList activity to list multiple * notes). */ public class WikiNotesProvider extends ContentProvider { private DatabaseHelper dbHelper; private static final String TAG = "WikiNotesProvider"; private static final String DATABASE_NAME = "wikinotes.db"; private static final int DATABASE_VERSION = 2; private static HashMap<String, String> NOTES_LIST_PROJECTION_MAP; private static final int NOTES = 1; private static final int NOTE_NAME = 2; private static final int NOTE_SEARCH = 3; private static final UriMatcher URI_MATCHER; /** * This inner DatabaseHelper class defines methods to create and upgrade * the database from previous versions. */ private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE wikinotes (_id INTEGER PRIMARY KEY," + "title TEXT COLLATE LOCALIZED NOT NULL," + "body TEXT," + "created INTEGER," + "modified INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS wikinotes"); onCreate(db); } } @Override public boolean onCreate() { // On the creation of the content provider, open the database, // the Database helper will create a new version of the database // if needed through the functionality in SQLiteOpenHelper dbHelper = new DatabaseHelper(getContext()); return true; } /** * Figure out which query to run based on the URL requested and any other * parameters provided. */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) { // Query the database using the arguments provided SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String[] whereArgs = null; // What type of query are we going to use - the URL_MATCHER // defined at the bottom of this class is used to pattern-match // the URL and select the right query from the switch statement switch (URI_MATCHER.match(uri)) { case NOTES: // this match lists all notes qb.setTables("wikinotes"); qb.setProjectionMap(NOTES_LIST_PROJECTION_MAP); break; case NOTE_SEARCH: // this match searches for a text match in the body of notes qb.setTables("wikinotes"); qb.setProjectionMap(NOTES_LIST_PROJECTION_MAP); qb.appendWhere("body like ? or title like ?"); whereArgs = new String[2]; whereArgs[0] = whereArgs[1] = "%" + uri.getLastPathSegment() + "%"; break; case NOTE_NAME: // this match searches for an exact match for a specific note name qb.setTables("wikinotes"); qb.appendWhere("title=?"); whereArgs = new String[] { uri.getLastPathSegment() }; break; default: // anything else is considered and illegal request throw new IllegalArgumentException("Unknown URL " + uri); } // If no sort order is specified use the default String orderBy; if (TextUtils.isEmpty(sort)) { orderBy = WikiNote.Notes.DEFAULT_SORT_ORDER; } else { orderBy = sort; } // Run the query and return the results as a Cursor SQLiteDatabase mDb = dbHelper.getReadableDatabase(); Cursor c = qb.query(mDb, projection, null, whereArgs, null, null, orderBy); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } /** * For a given URL, return a MIME type for the data that will be returned * from that URL. This will help Android decide what to do with the data * it gets back. */ @Override public String getType(Uri uri) { switch (URI_MATCHER.match(uri)) { case NOTES: case NOTE_SEARCH: // for a notes list, or search results, return a mimetype // indicating // a directory of wikinotes return "vnd.android.cursor.dir/vnd.google.wikinote"; case NOTE_NAME: // for a specific note name, return a mimetype indicating a single // item representing a wikinote return "vnd.android.cursor.item/vnd.google.wikinote"; default: // any other kind of URL is illegal throw new IllegalArgumentException("Unknown URL " + uri); } } /** * For a URL and a list of initial values, insert a row using those values * into the database. */ @Override public Uri insert(Uri uri, ContentValues initialValues) { long rowID; ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } // We can only insert a note, no other URLs make sense here if (URI_MATCHER.match(uri) != NOTE_NAME) { throw new IllegalArgumentException("Unknown URL " + uri); } // Update the modified time of the record Long now = Long.valueOf(System.currentTimeMillis()); // Make sure that the fields are all set if (values.containsKey(WikiNote.Notes.CREATED_DATE) == false) { values.put(WikiNote.Notes.CREATED_DATE, now); } if (values.containsKey(WikiNote.Notes.MODIFIED_DATE) == false) { values.put(WikiNote.Notes.MODIFIED_DATE, now); } if (values.containsKey(WikiNote.Notes.TITLE) == false) { values.put(WikiNote.Notes.TITLE, uri.getLastPathSegment()); } if (values.containsKey(WikiNote.Notes.BODY) == false) { values.put(WikiNote.Notes.BODY, ""); } SQLiteDatabase db = dbHelper.getWritableDatabase(); rowID = db.insert("wikinotes", "body", values); if (rowID > 0) { Uri newUri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, uri.getLastPathSegment()); getContext().getContentResolver().notifyChange(newUri, null); return newUri; } throw new SQLException("Failed to insert row into " + uri); } /** * Delete rows matching the where clause and args for the supplied URL. * The URL can be either the all notes URL (in which case all notes * matching the where clause will be deleted), or the note name, in which * case it will delete the note with the exactly matching title. Any of * the other URLs will be rejected as invalid. For deleting notes by title * we use ReST style arguments from the URI and don't support where clause * and args. */ @Override public int delete(Uri uri, String where, String[] whereArgs) { /* This is kind of dangerous: it deletes all records with a single Intent. It might make sense to make this ContentProvider non-public, since this is kind of over-powerful and the provider isn't generally intended to be public. But for now it's still public. */ if (WikiNote.Notes.ALL_NOTES_URI.equals(uri)) { return dbHelper.getWritableDatabase().delete("wikinotes", null, null); } int count; SQLiteDatabase db = dbHelper.getWritableDatabase(); switch (URI_MATCHER.match(uri)) { case NOTES: count = db.delete("wikinotes", where, whereArgs); break; case NOTE_NAME: if (!TextUtils.isEmpty(where) || (whereArgs != null)) { throw new UnsupportedOperationException( "Cannot update note using where clause"); } String noteId = uri.getPathSegments().get(1); count = db.delete("wikinotes", "_id=?", new String[] { noteId }); break; default: throw new IllegalArgumentException("Unknown URL " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /** * The update method, which will allow either a mass update using a where * clause, or an update targeted to a specific note name (the latter will * be more common). Other matched URLs will be rejected as invalid. For * updating notes by title we use ReST style arguments from the URI and do * not support using the where clause or args. */ @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { int count; SQLiteDatabase db = dbHelper.getWritableDatabase(); switch (URI_MATCHER.match(uri)) { case NOTES: count = db.update("wikinotes", values, where, whereArgs); break; case NOTE_NAME: values.put(WikiNote.Notes.MODIFIED_DATE, System .currentTimeMillis()); count = db.update("wikinotes", values, where, whereArgs); break; default: throw new IllegalArgumentException("Unknown URL " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /* * This static block sets up the pattern matches for the various URIs that * this content provider can handle. It also sets up the default projection * block (which defines what columns are returned from the database for the * results of a query). */ static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wikinotes", NOTES); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wikinotes/*", NOTE_NAME); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wiki/search/*", NOTE_SEARCH); NOTES_LIST_PROJECTION_MAP = new HashMap<String, String>(); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes._ID, "_id"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.TITLE, "title"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.BODY, "body"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.CREATED_DATE, "created"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.MODIFIED_DATE, "modified"); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.wikinotes.db; import android.net.Uri; import android.provider.BaseColumns; /** * This class defines columns and URIs used in the wikinotes application */ public class WikiNote { /** * Notes table */ public static final class Notes implements BaseColumns { /** * The content:// style URI for this table - this to see all notes or * append a note name to see just the matching note. */ public static final Uri ALL_NOTES_URI = Uri .parse("content://com.google.android.wikinotes.db.wikinotes/wikinotes"); /** * This URI can be used to search the bodies of notes for an appended * search term. */ public static final Uri SEARCH_URI = Uri .parse("content://com.google.android.wikinotes.db.wikinotes/wiki/search"); /** * The default sort order for this table - most recently modified first */ public static final String DEFAULT_SORT_ORDER = "modified DESC"; /** * The title of the note * <P> * Type: TEXT * </P> */ public static final String TITLE = "title"; /** * The note body * <P> * Type: TEXT * </P> */ public static final String BODY = "body"; /** * The timestamp for when the note was created * <P> * Type: INTEGER (long) * </P> */ public static final String CREATED_DATE = "created"; /** * The timestamp for when the note was last modified * <P> * Type: INTEGER (long) * </P> */ public static final String MODIFIED_DATE = "modified"; } /** * Convenience definition for the projection we will use to retrieve columns * from the wikinotes */ public static final String[] WIKI_NOTES_PROJECTION = {Notes._ID, Notes.TITLE, Notes.BODY, Notes.MODIFIED_DATE}; public static final String[] WIKI_EXPORT_PROJECTION = {Notes.TITLE, Notes.BODY, Notes.CREATED_DATE, Notes.MODIFIED_DATE}; /** * The root authority for the WikiNotesProvider */ public static final String WIKINOTES_AUTHORITY = "com.google.android.wikinotes.db.wikinotes"; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes; import android.app.ListActivity; import android.app.SearchManager; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import com.google.android.wikinotes.db.WikiNote; /** * Activity to list wikinotes. By default, the notes are listed in the order * of most recently modified to least recently modified. This activity can * handle requests to either show all notes, or the results of a title or body * search performed by the content provider. */ public class WikiNotesList extends ListActivity { /** * A key to store/retrieve the search criteria in a bundle */ public static final String SEARCH_CRITERIA_KEY = "SearchCriteria"; /** * The projection to use (columns to retrieve) for a query of wikinotes */ public static final String[] PROJECTION = { WikiNote.Notes._ID, WikiNote.Notes.TITLE, WikiNote.Notes.MODIFIED_DATE }; private Cursor mCursor; private WikiActivityHelper mHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Uri uri = null; String query = null; // locate a query string; prefer a fresh search Intent over saved // state if (Intent.ACTION_SEARCH.equals(intent.getAction())) { query = intent.getStringExtra(SearchManager.QUERY); } else if (savedInstanceState != null) { query = savedInstanceState.getString(SearchManager.QUERY); } if (query != null && query.length() > 0) { uri = Uri.withAppendedPath(WikiNote.Notes.SEARCH_URI, Uri .encode(query)); } if (uri == null) { // somehow we got called w/o a query so fall back to a reasonable // default (all notes) uri = WikiNote.Notes.ALL_NOTES_URI; } // Do the query Cursor c = managedQuery(uri, PROJECTION, null, null, WikiNote.Notes.DEFAULT_SORT_ORDER); mCursor = c; mHelper = new WikiActivityHelper(this); // Bind the results of the search into the list ListAdapter adapter = new SimpleCursorAdapter( this, android.R.layout.simple_list_item_1, mCursor, new String[] { WikiNote.Notes.TITLE }, new int[] { android.R.id.text1 }); setListAdapter(adapter); // use the menu shortcut keys as default key bindings for the entire // activity setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); } /** * Override the onListItemClick to open the wiki note to view when it is * selected from the list. */ @Override protected void onListItemClick(ListView list, View view, int position, long id) { Cursor c = mCursor; c.moveToPosition(position); String title = c.getString(c .getColumnIndexOrThrow(WikiNote.Notes.TITLE)); // Create the URI of the note we want to view based on the title Uri uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, title); Intent i = new Intent(Intent.ACTION_VIEW, uri); startActivity(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, WikiNotes.HOME_ID, 0, R.string.menu_start) .setShortcut('4', 'h').setIcon(R.drawable.icon_start); menu.add(0, WikiNotes.LIST_ID, 0, R.string.menu_recent) .setShortcut('3', 'r').setIcon(R.drawable.icon_recent); menu.add(0, WikiNotes.ABOUT_ID, 0, R.string.menu_about) .setShortcut('5', 'a').setIcon(android.R.drawable.ic_dialog_info); menu.add(0, WikiNotes.EXPORT_ID, 0, R.string.menu_export) .setShortcut('6', 'x').setIcon(android.R.drawable.ic_dialog_info); menu.add(0, WikiNotes.IMPORT_ID, 0, R.string.menu_import) .setShortcut('7', 'm').setIcon(android.R.drawable.ic_dialog_info); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case WikiNotes.HOME_ID: mHelper.goHome(); return true; case WikiNotes.LIST_ID: mHelper.listNotes(); return true; case WikiNotes.ABOUT_ID: Eula.showEula(this); return true; case WikiNotes.EXPORT_ID: mHelper.exportNotes(); return true; case WikiNotes.IMPORT_ID: mHelper.importNotes(); return true; default: return false; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.wikinotes; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.google.android.wikinotes.db.WikiNote; /** * Wikinote editor activity. This is a very simple activity that allows the user * to edit a wikinote using a text editor and confirm or cancel the changes. The * title and body for the wikinote to edit are passed in using the extras bundle * and the onFreeze() method provisions for those values to be stored in the * icicle on a lifecycle event, so that the user retains control over whether * the changes are committed to the database. */ public class WikiNoteEditor extends Activity { protected static final String ACTIVITY_RESULT = "com.google.android.wikinotes.EDIT"; private EditText mNoteEdit; private String mWikiNoteTitle; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.wiki_note_edit); mNoteEdit = (EditText) findViewById(R.id.noteEdit); // Check to see if the icicle has body and title values to restore String wikiNoteText = icicle == null ? null : icicle.getString(WikiNote.Notes.BODY); String wikiNoteTitle = icicle == null ? null : icicle.getString(WikiNote.Notes.TITLE); // If not, check to see if the extras bundle has these values passed in if (wikiNoteTitle == null) { Bundle extras = getIntent().getExtras(); wikiNoteText = extras == null ? null : extras .getString(WikiNote.Notes.BODY); wikiNoteTitle = extras == null ? null : extras .getString(WikiNote.Notes.TITLE); } // If we have no title information, this is an invalid intent request if (TextUtils.isEmpty(wikiNoteTitle)) { // no note title - bail setResult(RESULT_CANCELED); finish(); return; } mWikiNoteTitle = wikiNoteTitle; // but if the body is null, just set it to empty - first edit of this // note wikiNoteText = wikiNoteText == null ? "" : wikiNoteText; // set the title so we know which note we are editing setTitle(getString(R.string.wiki_editing, wikiNoteTitle)); // set the note body to edit mNoteEdit.setText(wikiNoteText); // set listeners for the confirm and cancel buttons ((Button) findViewById(R.id.confirmButton)) .setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent i = new Intent(); i.putExtra(ACTIVITY_RESULT, mNoteEdit.getText() .toString()); setResult(RESULT_OK, i); finish(); } }); ((Button) findViewById(R.id.cancelButton)) .setOnClickListener(new OnClickListener() { public void onClick(View view) { setResult(RESULT_CANCELED); finish(); } }); if (!getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE) .getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) { Eula.showEula(this); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(WikiNote.Notes.TITLE, mWikiNoteTitle); outState.putString(WikiNote.Notes.BODY, mNoteEdit.getText().toString()); } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.wikinotes; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; /** * Displays an EULA ("End User License Agreement") that the user has to accept * before using the application. Your application should call * {@link Eula#showEula(android.app.Activity)} in the onCreate() method of the * first activity. If the user accepts the EULA, it will never be shown again. * If the user refuses, {@link android.app.Activity#finish()} is invoked on your * activity. */ class Eula { public static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted"; public static final String PREFERENCES_EULA = "eula"; /** * Displays the EULA if necessary. This method should be called from the * onCreate() method of your main Activity. * * @param activity * The Activity to finish if the user rejects the EULA. */ static void showEula(final Activity activity) { final SharedPreferences preferences = activity.getSharedPreferences( PREFERENCES_EULA, Activity.MODE_PRIVATE); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.about_title); builder.setCancelable(false); builder.setPositiveButton(R.string.about_dismiss_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit(); } }); builder.setMessage(R.string.about_body); builder.create().show(); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes; import java.util.regex.Pattern; import android.app.Activity; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.util.Linkify; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.google.android.wikinotes.db.WikiNote; /** * The WikiNotes activity is the default handler for displaying individual * wiki notes. It takes the wiki note name to view from the intent data URL * and defaults to a page name defined in R.strings.start_page if no page name * is given. The lifecycle events store the current content URL being viewed. * It uses Linkify to turn wiki words in the body of the wiki note into * clickable links which in turn call back into the WikiNotes activity from * the Android operating system. If a URL is passed to the WikiNotes activity * for a page that does not yet exist, the WikiNoteEditor activity is * automatically started to place the user into edit mode for a new wiki note * with the given name. */ public class WikiNotes extends Activity { /** * The view URL which is prepended to a matching wikiword in order to fire * the WikiNotes activity again through Linkify */ private static final String KEY_URL = "wikiNotesURL"; public static final int EDIT_ID = Menu.FIRST; public static final int HOME_ID = Menu.FIRST + 1; public static final int LIST_ID = Menu.FIRST + 3; public static final int DELETE_ID = Menu.FIRST + 4; public static final int ABOUT_ID = Menu.FIRST + 5; public static final int EXPORT_ID = Menu.FIRST + 6; public static final int IMPORT_ID = Menu.FIRST + 7; public static final int EMAIL_ID = Menu.FIRST + 8; private TextView mNoteView; Cursor mCursor; private Uri mURI; String mNoteName; private static final Pattern WIKI_WORD_MATCHER; private WikiActivityHelper mHelper; static { // Compile the regular expression pattern that will be used to // match WikiWords in the body of the note WIKI_WORD_MATCHER = Pattern .compile("\\b[A-Z]+[a-z0-9]+[A-Z][A-Za-z0-9]+\\b"); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mNoteView = (TextView) findViewById(R.id.noteview); // get the URL we are being asked to view Uri uri = getIntent().getData(); if ((uri == null) && (icicle != null)) { // perhaps we have the URI in the icicle instead? uri = Uri.parse(icicle.getString(KEY_URL)); } // do we have a correct URI including the note name? if ((uri == null) || (uri.getPathSegments().size() < 2)) { // if not, build one using the default StartPage name uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, getResources() .getString(R.string.start_page)); } // can we find a matching note? Cursor cursor = managedQuery(uri, WikiNote.WIKI_NOTES_PROJECTION, null, null, null); boolean newNote = false; if ((cursor == null) || (cursor.getCount() == 0)) { // no matching wikinote, so create it uri = getContentResolver().insert(uri, null); if (uri == null) { Log.e("WikiNotes", "Failed to insert new wikinote into " + getIntent().getData()); finish(); return; } // make sure that the new note was created successfully, and // select // it cursor = managedQuery(uri, WikiNote.WIKI_NOTES_PROJECTION, null, null, null); if ((cursor == null) || (cursor.getCount() == 0)) { Log.e("WikiNotes", "Failed to open new wikinote: " + getIntent().getData()); finish(); return; } newNote = true; } mURI = uri; mCursor = cursor; cursor.moveToFirst(); mHelper = new WikiActivityHelper(this); // get the note name String noteName = cursor.getString(cursor .getColumnIndexOrThrow(WikiNote.Notes.TITLE)); mNoteName = noteName; // set the title to the name of the page setTitle(getResources().getString(R.string.wiki_title, noteName)); // If a new note was created, jump straight into editing it if (newNote) { mHelper.editNote(noteName, null); } else if (!getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE) .getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) { Eula.showEula(this); } // Set the menu shortcut keys to be default keys for the activity as // well setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Put the URL currently being viewed into the icicle outState.putString(KEY_URL, mURI.toString()); } @Override protected void onResume() { super.onResume(); Cursor c = mCursor; if (c.getCount() < 1) { // if the note can't be found, don't try to load it -- bail out // (probably means it got deleted while we were frozen; // thx to joe.bowbeer for the find) finish(); return; } c.requery(); c.moveToFirst(); showWikiNote(c .getString(c.getColumnIndexOrThrow(WikiNote.Notes.BODY))); } /** * Show the wiki note in the text edit view with both the default Linkify * options and the regular expression for WikiWords matched and turned * into live links. * * @param body * The plain text to linkify and put into the edit view. */ private void showWikiNote(CharSequence body) { TextView noteView = mNoteView; noteView.setText(body); // Add default links first - phone numbers, URLs, etc. Linkify.addLinks(noteView, Linkify.ALL); // Now add in the custom linkify match for WikiWords Linkify.addLinks(noteView, WIKI_WORD_MATCHER, WikiNote.Notes.ALL_NOTES_URI.toString() + "/"); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, EDIT_ID, 0, R.string.menu_edit).setShortcut('1', 'e') .setIcon(R.drawable.icon_delete); menu.add(0, HOME_ID, 0, R.string.menu_start).setShortcut('4', 'h') .setIcon(R.drawable.icon_start); menu.add(0, LIST_ID, 0, R.string.menu_recent).setShortcut('3', 'r') .setIcon(R.drawable.icon_recent); menu.add(0, DELETE_ID, 0, R.string.menu_delete).setShortcut('2', 'd') .setIcon(R.drawable.icon_delete); menu.add(0, ABOUT_ID, 0, R.string.menu_about).setShortcut('5', 'a') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, EXPORT_ID, 0, R.string.menu_export).setShortcut('7', 'x') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, IMPORT_ID, 0, R.string.menu_import).setShortcut('8', 'm') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, EMAIL_ID, 0, R.string.menu_email).setShortcut('6', 'm') .setIcon(android.R.drawable.ic_dialog_info); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case EDIT_ID: mHelper.editNote(mNoteName, mCursor); return true; case HOME_ID: mHelper.goHome(); return true; case DELETE_ID: mHelper.deleteNote(mCursor); return true; case LIST_ID: mHelper.listNotes(); return true; case WikiNotes.ABOUT_ID: Eula.showEula(this); return true; case WikiNotes.EXPORT_ID: mHelper.exportNotes(); return true; case WikiNotes.IMPORT_ID: mHelper.importNotes(); return true; case WikiNotes.EMAIL_ID: mHelper.mailNote(mCursor); return true; default: return false; } } /** * If the note was edited and not canceled, commit the update to the * database and then refresh the current view of the linkified note. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent result) { super.onActivityResult(requestCode, resultCode, result); if ((requestCode == WikiActivityHelper.ACTIVITY_EDIT) && (resultCode == RESULT_OK)) { // edit was confirmed - store the update Cursor c = mCursor; c.requery(); c.moveToFirst(); Uri noteUri = ContentUris .withAppendedId(WikiNote.Notes.ALL_NOTES_URI, c.getInt(0)); ContentValues values = new ContentValues(); values.put(WikiNote.Notes.BODY, result .getStringExtra(WikiNoteEditor.ACTIVITY_RESULT)); values.put(WikiNote.Notes.MODIFIED_DATE, System .currentTimeMillis()); getContentResolver().update(noteUri, values, "_id = " + c.getInt(0), null); showWikiNote(c.getString(c .getColumnIndexOrThrow(WikiNote.Notes.BODY))); } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import java.util.Arrays; import java.util.List; /** * Model of a "ball" object used by the demo app. */ public class Demo_Ball { public enum BOUNCE_TYPE { TOPLEFT, TOP, TOPRIGHT, LEFT, RIGHT, BOTTOMLEFT, BOTTOM, BOTTOMRIGHT } private final float radius = 20; private final float pxPerM = 2; // Let 2 pixels represent 1 meter private final float reboundEnergyFactor = 0.6f; // Amount of energy returned // when rebounding private float xPos = 160; private float yPos = 240; private float xMax = 320; private float yMax = 410; private float xAcceleration = 0; private float yAcceleration = 0; private float xVelocity = 0; private float yVelocity = 0; private float reboundXPos = 0; private float reboundYPos = 0; private float reboundXVelocity = 0; private float reboundYVelocity = 0; private long lastUpdate; private boolean onScreen; public Demo_Ball(boolean visible) { onScreen = visible; lastUpdate = System.currentTimeMillis(); } public Demo_Ball(boolean visible, int screenSizeX, int screenSizeY) { onScreen = visible; lastUpdate = System.currentTimeMillis(); xMax = screenSizeX; yMax = screenSizeY; } public float getRadius() { return radius; } public float getXVelocity() { return xVelocity; } public float getX() { if (!onScreen) { return -1; } return xPos; } public float getY() { if (!onScreen) { return -1; } return yPos; } public void putOnScreen(float x, float y, float ax, float ay, float vx, float vy, int startingSide) { xPos = x; yPos = y; xVelocity = vx; yVelocity = vy; xAcceleration = ax; yAcceleration = ay; lastUpdate = System.currentTimeMillis(); if (startingSide == Demo_Multiscreen.RIGHT) { xPos = xMax - radius - 2; } else if (startingSide == Demo_Multiscreen.LEFT) { xPos = radius + 2; } else if (startingSide == Demo_Multiscreen.UP) { yPos = radius + 2; } else if (startingSide == Demo_Multiscreen.DOWN) { yPos = yMax - radius - 2; } else if (startingSide == AirHockey.FLIPTOP) { yPos = radius + 2; xPos = xMax - x; if (xPos < 0){ xPos = 0; } yVelocity = -vy; yAcceleration = -ay; } onScreen = true; } public void setAcceleration(float ax, float ay) { if (!onScreen) { return; } xAcceleration = ax; yAcceleration = ay; } public boolean isOnScreen(){ return onScreen; } public int update() { if (!onScreen) { return 0; } long currentTime = System.currentTimeMillis(); long elapsed = currentTime - lastUpdate; lastUpdate = currentTime; xVelocity += ((elapsed * xAcceleration) / 1000) * pxPerM; yVelocity += ((elapsed * yAcceleration) / 1000) * pxPerM; xPos += ((xVelocity * elapsed) / 1000) * pxPerM; yPos += ((yVelocity * elapsed) / 1000) * pxPerM; // Handle rebounding if (yPos - radius < 0) { reboundXPos = xPos; reboundYPos = radius; reboundXVelocity = xVelocity; reboundYVelocity = -yVelocity * reboundEnergyFactor; onScreen = false; return Demo_Multiscreen.UP; } else if (yPos + radius > yMax) { reboundXPos = xPos; reboundYPos = yMax - radius; reboundXVelocity = xVelocity; reboundYVelocity = -yVelocity * reboundEnergyFactor; onScreen = false; return Demo_Multiscreen.DOWN; } if (xPos - radius < 0) { reboundXPos = radius; reboundYPos = yPos; reboundXVelocity = -xVelocity * reboundEnergyFactor; reboundYVelocity = yVelocity; onScreen = false; return Demo_Multiscreen.LEFT; } else if (xPos + radius > xMax) { reboundXPos = xMax - radius; reboundYPos = yPos; reboundXVelocity = -xVelocity * reboundEnergyFactor; reboundYVelocity = yVelocity; onScreen = false; return Demo_Multiscreen.RIGHT; } return Demo_Multiscreen.CENTER; } public void doRebound() { xPos = reboundXPos; yPos = reboundYPos; xVelocity = reboundXVelocity; yVelocity = reboundYVelocity; onScreen = true; } public String getState() { String state = ""; state = xPos + "|" + yPos + "|" + xAcceleration + "|" + yAcceleration + "|" + xVelocity + "|" + yVelocity; return state; } public void restoreState(String state) { List<String> stateInfo = Arrays.asList(state.split("\\|")); putOnScreen(Float.parseFloat(stateInfo.get(0)), Float.parseFloat(stateInfo.get(1)), Float .parseFloat(stateInfo.get(2)), Float.parseFloat(stateInfo.get(3)), Float .parseFloat(stateInfo.get(4)), Float.parseFloat(stateInfo.get(5)), Integer .parseInt(stateInfo.get(6))); } public void doBounce(BOUNCE_TYPE bounceType, float vX, float vY){ switch (bounceType){ case TOPLEFT: if (xVelocity > 0){ xVelocity = -xVelocity * reboundEnergyFactor; } if (yVelocity > 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; case TOP: if (yVelocity > 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; case TOPRIGHT: if (xVelocity < 0){ xVelocity = -xVelocity * reboundEnergyFactor; } if (yVelocity > 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; case LEFT: if (xVelocity > 0){ xVelocity = -xVelocity * reboundEnergyFactor; } break; case RIGHT: if (xVelocity < 0){ xVelocity = -xVelocity * reboundEnergyFactor; } break; case BOTTOMLEFT: if (xVelocity > 0){ xVelocity = -xVelocity * reboundEnergyFactor; } if (yVelocity < 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; case BOTTOM: if (yVelocity < 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; case BOTTOMRIGHT: if (xVelocity < 0){ xVelocity = -xVelocity * reboundEnergyFactor; } if (yVelocity < 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; } xVelocity = xVelocity + (vX * 500); yVelocity = yVelocity + (vY * 150); } }
Java
package net.clc.bt; import net.clc.bt.Connection.OnConnectionLostListener; import net.clc.bt.Connection.OnConnectionServiceReadyListener; import net.clc.bt.Connection.OnIncomingConnectionListener; import net.clc.bt.Connection.OnMaxConnectionsReachedListener; import net.clc.bt.Connection.OnMessageReceivedListener; import net.clc.bt.Demo_Ball.BOUNCE_TYPE; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.WindowManager; import android.view.SurfaceHolder.Callback; import android.view.WindowManager.BadTokenException; import android.widget.Toast; import java.util.ArrayList; public class AirHockey extends Activity implements Callback { public static final String TAG = "AirHockey"; private static final int SERVER_LIST_RESULT_CODE = 42; public static final int UP = 3; public static final int DOWN = 4; public static final int FLIPTOP = 5; private AirHockey self; private int mType; // 0 = server, 1 = client private SurfaceView mSurface; private SurfaceHolder mHolder; private Paint bgPaint; private Paint goalPaint; private Paint ballPaint; private Paint paddlePaint; private PhysicsLoop pLoop; private ArrayList<Point> mPaddlePoints; private ArrayList<Long> mPaddleTimes; private int mPaddlePointWindowSize = 5; private int mPaddleRadius = 55; private Bitmap mPaddleBmp; private Demo_Ball mBall; private int mBallRadius = 40; private Connection mConnection; private String rivalDevice = ""; private SoundPool mSoundPool; private int tockSound = 0; private MediaPlayer mPlayer; private int hostScore = 0; private int clientScore = 0; private OnMessageReceivedListener dataReceivedListener = new OnMessageReceivedListener() { public void OnMessageReceived(String device, String message) { if (message.indexOf("SCORE") == 0) { String[] scoreMessageSplit = message.split(":"); hostScore = Integer.parseInt(scoreMessageSplit[1]); clientScore = Integer.parseInt(scoreMessageSplit[2]); showScore(); } else { mBall.restoreState(message); } } }; private OnMaxConnectionsReachedListener maxConnectionsListener = new OnMaxConnectionsReachedListener() { public void OnMaxConnectionsReached() { } }; private OnIncomingConnectionListener connectedListener = new OnIncomingConnectionListener() { public void OnIncomingConnection(String device) { rivalDevice = device; WindowManager w = getWindowManager(); Display d = w.getDefaultDisplay(); int width = d.getWidth(); int height = d.getHeight(); mBall = new Demo_Ball(true, width, height - 60); mBall.putOnScreen(width / 2, (height / 2 + (int) (height * .05)), 0, 0, 0, 0, 0); } }; private OnConnectionLostListener disconnectedListener = new OnConnectionLostListener() { public void OnConnectionLost(String device) { class displayConnectionLostAlert implements Runnable { public void run() { Builder connectionLostAlert = new Builder(self); connectionLostAlert.setTitle("Connection lost"); connectionLostAlert .setMessage("Your connection with the other player has been lost."); connectionLostAlert.setPositiveButton("Ok", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); connectionLostAlert.setCancelable(false); try { connectionLostAlert.show(); } catch (BadTokenException e){ // Something really bad happened here; // seems like the Activity itself went away before // the runnable finished. // Bail out gracefully here and do nothing. } } } self.runOnUiThread(new displayConnectionLostAlert()); } }; private OnConnectionServiceReadyListener serviceReadyListener = new OnConnectionServiceReadyListener() { public void OnConnectionServiceReady() { if (mType == 0) { mConnection.startServer(1, connectedListener, maxConnectionsListener, dataReceivedListener, disconnectedListener); self.setTitle("Air Hockey: " + mConnection.getName() + "-" + mConnection.getAddress()); } else { WindowManager w = getWindowManager(); Display d = w.getDefaultDisplay(); int width = d.getWidth(); int height = d.getHeight(); mBall = new Demo_Ball(false, width, height - 60); Intent serverListIntent = new Intent(self, ServerListActivity.class); startActivityForResult(serverListIntent, SERVER_LIST_RESULT_CODE); } } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); self = this; mPaddleBmp = BitmapFactory.decodeResource(getResources(), R.drawable.paddlelarge); mPaddlePoints = new ArrayList<Point>(); mPaddleTimes = new ArrayList<Long>(); Intent startingIntent = getIntent(); mType = startingIntent.getIntExtra("TYPE", 0); setContentView(R.layout.main); mSurface = (SurfaceView) findViewById(R.id.surface); mHolder = mSurface.getHolder(); bgPaint = new Paint(); bgPaint.setColor(Color.BLACK); goalPaint = new Paint(); goalPaint.setColor(Color.RED); ballPaint = new Paint(); ballPaint.setColor(Color.GREEN); ballPaint.setAntiAlias(true); paddlePaint = new Paint(); paddlePaint.setColor(Color.BLUE); paddlePaint.setAntiAlias(true); mPlayer = MediaPlayer.create(this, R.raw.collision); mConnection = new Connection(this, serviceReadyListener); mHolder.addCallback(self); } @Override protected void onDestroy() { if (mConnection != null) { mConnection.shutdown(); } if (mPlayer != null) { mPlayer.release(); } super.onDestroy(); } public void surfaceCreated(SurfaceHolder holder) { pLoop = new PhysicsLoop(); pLoop.start(); } private void draw() { Canvas canvas = null; try { canvas = mHolder.lockCanvas(); if (canvas != null) { doDraw(canvas); } } finally { if (canvas != null) { mHolder.unlockCanvasAndPost(canvas); } } } private void doDraw(Canvas c) { c.drawRect(0, 0, c.getWidth(), c.getHeight(), bgPaint); c.drawRect(0, c.getHeight() - (int) (c.getHeight() * 0.02), c.getWidth(), c.getHeight(), goalPaint); if (mPaddleTimes.size() > 0) { Point p = mPaddlePoints.get(mPaddlePoints.size() - 1); // Debug circle // Point debugPaddleCircle = getPaddleCenter(); // c.drawCircle(debugPaddleCircle.x, debugPaddleCircle.y, // mPaddleRadius, ballPaint); if (p != null) { c.drawBitmap(mPaddleBmp, p.x - 60, p.y - 200, new Paint()); } } if ((mBall == null) || !mBall.isOnScreen()) { return; } float x = mBall.getX(); float y = mBall.getY(); if ((x != -1) && (y != -1)) { float xv = mBall.getXVelocity(); Bitmap bmp = BitmapFactory .decodeResource(this.getResources(), R.drawable.android_right); if (xv < 0) { bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.android_left); } // Debug circle Point debugBallCircle = getBallCenter(); // c.drawCircle(debugBallCircle.x, debugBallCircle.y, mBallRadius, // ballPaint); c.drawBitmap(bmp, x - 17, y - 23, new Paint()); } } public void surfaceDestroyed(SurfaceHolder holder) { try { pLoop.safeStop(); } finally { pLoop = null; } } private class PhysicsLoop extends Thread { private volatile boolean running = true; @Override public void run() { while (running) { try { Thread.sleep(5); draw(); if (mBall != null) { handleCollision(); int position = mBall.update(); mBall.setAcceleration(0, 0); if (position != 0) { if ((position == UP) && (rivalDevice.length() > 1)) { mConnection.sendMessage(rivalDevice, mBall.getState() + "|" + FLIPTOP); } else if (position == DOWN) { if (mType == 0) { clientScore = clientScore + 1; } else { hostScore = hostScore + 1; } mConnection.sendMessage(rivalDevice, "SCORE:" + hostScore + ":" + clientScore); showScore(); WindowManager w = getWindowManager(); Display d = w.getDefaultDisplay(); int width = d.getWidth(); int height = d.getHeight(); mBall.putOnScreen(width / 2, (height / 2 + (int) (height * .05)), 0, 0, 0, 0, 0); } else { mBall.doRebound(); } } } } catch (InterruptedException ie) { running = false; } } } public void safeStop() { running = false; interrupt(); } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if ((resultCode == Activity.RESULT_OK) && (requestCode == SERVER_LIST_RESULT_CODE)) { String device = data.getStringExtra(ServerListActivity.EXTRA_SELECTED_ADDRESS); int connectionStatus = mConnection.connect(device, dataReceivedListener, disconnectedListener); if (connectionStatus != Connection.SUCCESS) { Toast.makeText(self, "Unable to connect; please try again.", 1).show(); } else { rivalDevice = device; } return; } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { Point p = new Point((int) event.getX(), (int) event.getY()); mPaddlePoints.add(p); mPaddleTimes.add(System.currentTimeMillis()); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { Point p = new Point((int) event.getX(), (int) event.getY()); mPaddlePoints.add(p); mPaddleTimes.add(System.currentTimeMillis()); if (mPaddleTimes.size() > mPaddlePointWindowSize) { mPaddleTimes.remove(0); mPaddlePoints.remove(0); } } else { mPaddleTimes = new ArrayList<Long>(); mPaddlePoints = new ArrayList<Point>(); } return false; } // TODO: Scale this for G1 sized screens public Point getBallCenter() { if (mBall == null) { return new Point(-1, -1); } int x = (int) mBall.getX(); int y = (int) mBall.getY(); return new Point(x + 10, y + 12); } // TODO: Scale this for G1 sized screens public Point getPaddleCenter() { if (mPaddleTimes.size() > 0) { Point p = mPaddlePoints.get(mPaddlePoints.size() - 1); int x = p.x + 10; int y = p.y - 130; return new Point(x, y); } else { return new Point(-1, -1); } } private void showScore() { class showScoreRunnable implements Runnable { public void run() { String scoreString = ""; if (mType == 0) { scoreString = hostScore + " - " + clientScore; } else { scoreString = clientScore + " - " + hostScore; } Toast.makeText(self, scoreString, 0).show(); } } self.runOnUiThread(new showScoreRunnable()); } private void handleCollision() { // TODO: Handle multiball case if (mBall == null) { return; } if (mPaddleTimes.size() < 1) { return; } Point ballCenter = getBallCenter(); Point paddleCenter = getPaddleCenter(); final int dy = ballCenter.y - paddleCenter.y; final int dx = ballCenter.x - paddleCenter.x; final float distance = dy * dy + dx * dx; if (distance < ((2 * mBallRadius) * (2 * mPaddleRadius))) { // Get paddle velocity float vX = 0; float vY = 0; Point endPoint = new Point(-1, -1); Point startPoint = new Point(-1, -1); long timeDiff = 0; try { endPoint = mPaddlePoints.get(mPaddlePoints.size() - 1); startPoint = mPaddlePoints.get(0); timeDiff = mPaddleTimes.get(mPaddleTimes.size() - 1) - mPaddleTimes.get(0); } catch (IndexOutOfBoundsException e) { // Paddle points were removed at the last moment return; } if (timeDiff > 0) { vX = ((float) (endPoint.x - startPoint.x)) / timeDiff; vY = ((float) (endPoint.y - startPoint.y)) / timeDiff; } // Determine the bounce type BOUNCE_TYPE bounceType = BOUNCE_TYPE.TOP; if ((ballCenter.x < (paddleCenter.x - mPaddleRadius / 2)) && (ballCenter.y < (paddleCenter.y - mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.TOPLEFT; } else if ((ballCenter.x > (paddleCenter.x + mPaddleRadius / 2)) && (ballCenter.y < (paddleCenter.y - mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.TOPRIGHT; } else if ((ballCenter.x < (paddleCenter.x - mPaddleRadius / 2)) && (ballCenter.y > (paddleCenter.y + mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.BOTTOMLEFT; } else if ((ballCenter.x > (paddleCenter.x + mPaddleRadius / 2)) && (ballCenter.y > (paddleCenter.y + mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.BOTTOMRIGHT; } else if ((ballCenter.x < paddleCenter.x) && (ballCenter.y > (paddleCenter.y - mPaddleRadius / 2)) && (ballCenter.y < (paddleCenter.y + mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.LEFT; } else if ((ballCenter.x > paddleCenter.x) && (ballCenter.y > (paddleCenter.y - mPaddleRadius / 2)) && (ballCenter.y < (paddleCenter.y + mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.RIGHT; } else if ((ballCenter.x > (paddleCenter.x - mPaddleRadius / 2)) && (ballCenter.x < (paddleCenter.x + mPaddleRadius / 2)) && (ballCenter.y > paddleCenter.y)) { bounceType = BOUNCE_TYPE.RIGHT; } mBall.doBounce(bounceType, vX, vY); if (!mPlayer.isPlaying()) { mPlayer.release(); mPlayer = MediaPlayer.create(this, R.raw.collision); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.start(); } } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import net.clc.bt.IConnection; import net.clc.bt.IConnectionCallback; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * API for the Bluetooth Click, Link, Compete library. This library simplifies * the process of establishing Bluetooth connections and sending data in a way * that is geared towards multi-player games. */ public class Connection { public static final String TAG = "net.clc.bt.Connection"; public static final int SUCCESS = 0; public static final int FAILURE = 1; public static final int MAX_SUPPORTED = 7; public interface OnConnectionServiceReadyListener { public void OnConnectionServiceReady(); } public interface OnIncomingConnectionListener { public void OnIncomingConnection(String device); } public interface OnMaxConnectionsReachedListener { public void OnMaxConnectionsReached(); } public interface OnMessageReceivedListener { public void OnMessageReceived(String device, String message); } public interface OnConnectionLostListener { public void OnConnectionLost(String device); } private OnConnectionServiceReadyListener mOnConnectionServiceReadyListener; private OnIncomingConnectionListener mOnIncomingConnectionListener; private OnMaxConnectionsReachedListener mOnMaxConnectionsReachedListener; private OnMessageReceivedListener mOnMessageReceivedListener; private OnConnectionLostListener mOnConnectionLostListener; private ServiceConnection mServiceConnection; private Context mContext; private String mPackageName = ""; private boolean mStarted = false; private final Object mStartLock = new Object(); private IConnection mIconnection; private IConnectionCallback mIccb = new IConnectionCallback.Stub() { public void incomingConnection(String device) throws RemoteException { if (mOnIncomingConnectionListener != null) { mOnIncomingConnectionListener.OnIncomingConnection(device); } } public void connectionLost(String device) throws RemoteException { if (mOnConnectionLostListener != null) { mOnConnectionLostListener.OnConnectionLost(device); } } public void maxConnectionsReached() throws RemoteException { if (mOnMaxConnectionsReachedListener != null) { mOnMaxConnectionsReachedListener.OnMaxConnectionsReached(); } } public void messageReceived(String device, String message) throws RemoteException { if (mOnMessageReceivedListener != null) { mOnMessageReceivedListener.OnMessageReceived(device, message); } } }; // TODO: Add a check to autodownload this service from Market if the user // does not have it already. public Connection(Context ctx, OnConnectionServiceReadyListener ocsrListener) { mOnConnectionServiceReadyListener = ocsrListener; mContext = ctx; mPackageName = ctx.getPackageName(); mServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder service) { synchronized (mStartLock) { mIconnection = IConnection.Stub.asInterface(service); mStarted = true; if (mOnConnectionServiceReadyListener != null) { mOnConnectionServiceReadyListener.OnConnectionServiceReady(); } } } public void onServiceDisconnected(ComponentName name) { synchronized (mStartLock) { try { mStarted = false; mIconnection.unregisterCallback(mPackageName); mIconnection.shutdown(mPackageName); } catch (RemoteException e) { Log.e(TAG, "RemoteException in onServiceDisconnected", e); } mIconnection = null; } } }; Intent intent = new Intent("com.google.intent.action.BT_ClickLinkCompete_SERVICE"); intent.addCategory("com.google.intent.category.BT_ClickLinkCompete"); mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); } public int startServer(final int maxConnections, OnIncomingConnectionListener oicListener, OnMaxConnectionsReachedListener omcrListener, OnMessageReceivedListener omrListener, OnConnectionLostListener oclListener) { if (!mStarted) { return Connection.FAILURE; } if (maxConnections > MAX_SUPPORTED) { Log.e(TAG, "The maximum number of allowed connections is " + MAX_SUPPORTED); return Connection.FAILURE; } mOnIncomingConnectionListener = oicListener; mOnMaxConnectionsReachedListener = omcrListener; mOnMessageReceivedListener = omrListener; mOnConnectionLostListener = oclListener; try { int result = mIconnection.startServer(mPackageName, maxConnections); mIconnection.registerCallback(mPackageName, mIccb); return result; } catch (RemoteException e) { Log.e(TAG, "RemoteException in startServer", e); } return Connection.FAILURE; } public int connect(String device, OnMessageReceivedListener omrListener, OnConnectionLostListener oclListener) { if (!mStarted) { return Connection.FAILURE; } mOnMessageReceivedListener = omrListener; mOnConnectionLostListener = oclListener; try { int result = mIconnection.connect(mPackageName, device); mIconnection.registerCallback(mPackageName, mIccb); return result; } catch (RemoteException e) { Log.e(TAG, "RemoteException in connect", e); } return Connection.FAILURE; } public int sendMessage(String device, String message) { if (!mStarted) { return Connection.FAILURE; } try { return mIconnection.sendMessage(mPackageName, device, message); } catch (RemoteException e) { Log.e(TAG, "RemoteException in sendMessage", e); } return Connection.FAILURE; } public int broadcastMessage(String message) { if (!mStarted) { return Connection.FAILURE; } try { return mIconnection.broadcastMessage(mPackageName, message); } catch (RemoteException e) { Log.e(TAG, "RemoteException in broadcastMessage", e); } return Connection.FAILURE; } public String getConnections() { if (!mStarted) { return ""; } try { return mIconnection.getConnections(mPackageName); } catch (RemoteException e) { Log.e(TAG, "RemoteException in getConnections", e); } return ""; } public int getVersion() { if (!mStarted) { return Connection.FAILURE; } try { return mIconnection.getVersion(); } catch (RemoteException e) { Log.e(TAG, "RemoteException in getVersion", e); } return Connection.FAILURE; } public String getAddress() { if (!mStarted) { return ""; } try { return mIconnection.getAddress(); } catch (RemoteException e) { Log.e(TAG, "RemoteException in getAddress", e); } return ""; } public String getName() { if (!mStarted) { return ""; } try { return mIconnection.getName(); } catch (RemoteException e) { Log.e(TAG, "RemoteException in getVersion", e); } return ""; } public void shutdown() { try { mStarted = false; if (mIconnection != null) { mIconnection.shutdown(mPackageName); } mContext.unbindService(mServiceConnection); } catch (RemoteException e) { Log.e(TAG, "RemoteException in shutdown", e); } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import android.app.Activity; import android.app.ListActivity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; /** * A simple list activity that displays Bluetooth devices that are in * discoverable mode. This can be used as a gamelobby where players can see * available servers and pick the one they wish to connect to. */ public class ServerListActivity extends ListActivity { public static String EXTRA_SELECTED_ADDRESS = "btaddress"; private BluetoothAdapter myBt; private ServerListActivity self; private ArrayAdapter<String> arrayAdapter; private BroadcastReceiver myReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Parcelable btParcel = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); BluetoothDevice btDevice = (BluetoothDevice) btParcel; arrayAdapter.add(btDevice.getName() + " - " + btDevice.getAddress()); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); self = this; arrayAdapter = new ArrayAdapter<String>(self, R.layout.text); ListView lv = self.getListView(); lv.setAdapter(arrayAdapter); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { myBt.cancelDiscovery(); // Cancel BT discovery explicitly so // that connections can go through String btDeviceInfo = ((TextView) arg1).getText().toString(); String btHardwareAddress = btDeviceInfo.substring(btDeviceInfo.length() - 17); Intent i = new Intent(); i.putExtra(EXTRA_SELECTED_ADDRESS, btHardwareAddress); self.setResult(Activity.RESULT_OK, i); finish(); } }); myBt = BluetoothAdapter.getDefaultAdapter(); myBt.startDiscovery(); self.setResult(Activity.RESULT_CANCELED); } @Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(myReceiver, filter); } @Override protected void onPause() { super.onPause(); this.unregisterReceiver(myReceiver); } @Override protected void onDestroy() { super.onDestroy(); if (myBt != null) { myBt.cancelDiscovery(); // Ensure that we don't leave discovery // running by accident } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import net.clc.bt.IConnection; import net.clc.bt.IConnectionCallback; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.UUID; /** * Service for simplifying the process of establishing Bluetooth connections and * sending data in a way that is geared towards multi-player games. */ public class ConnectionService extends Service { public static final String TAG = "net.clc.bt.ConnectionService"; private ArrayList<UUID> mUuid; private ConnectionService mSelf; private String mApp; // Assume only one app can use this at a time; may // change this later private IConnectionCallback mCallback; private ArrayList<String> mBtDeviceAddresses; private HashMap<String, BluetoothSocket> mBtSockets; private HashMap<String, Thread> mBtStreamWatcherThreads; private BluetoothAdapter mBtAdapter; public ConnectionService() { mSelf = this; mBtAdapter = BluetoothAdapter.getDefaultAdapter(); mApp = ""; mBtSockets = new HashMap<String, BluetoothSocket>(); mBtDeviceAddresses = new ArrayList<String>(); mBtStreamWatcherThreads = new HashMap<String, Thread>(); mUuid = new ArrayList<UUID>(); // Allow up to 7 devices to connect to the server mUuid.add(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666")); mUuid.add(UUID.fromString("503c7430-bc23-11de-8a39-0800200c9a66")); mUuid.add(UUID.fromString("503c7431-bc23-11de-8a39-0800200c9a66")); mUuid.add(UUID.fromString("503c7432-bc23-11de-8a39-0800200c9a66")); mUuid.add(UUID.fromString("503c7433-bc23-11de-8a39-0800200c9a66")); mUuid.add(UUID.fromString("503c7434-bc23-11de-8a39-0800200c9a66")); mUuid.add(UUID.fromString("503c7435-bc23-11de-8a39-0800200c9a66")); } @Override public IBinder onBind(Intent arg0) { return mBinder; } private class BtStreamWatcher implements Runnable { private String address; public BtStreamWatcher(String deviceAddress) { address = deviceAddress; } public void run() { int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; BluetoothSocket bSock = mBtSockets.get(address); try { InputStream instream = bSock.getInputStream(); int bytesRead = -1; String message = ""; while (true) { message = ""; bytesRead = instream.read(buffer); if (bytesRead != -1) { while ((bytesRead == bufferSize) && (buffer[bufferSize - 1] != 0)) { message = message + new String(buffer, 0, bytesRead); bytesRead = instream.read(buffer); } message = message + new String(buffer, 0, bytesRead - 1); // Remove // the // stop // marker mCallback.messageReceived(address, message); } } } catch (IOException e) { Log.i(TAG, "IOException in BtStreamWatcher - probably caused by normal disconnection", e); } catch (RemoteException e) { Log.e(TAG, "RemoteException in BtStreamWatcher while reading data", e); } // Getting out of the while loop means the connection is dead. try { mBtDeviceAddresses.remove(address); mBtSockets.remove(address); mBtStreamWatcherThreads.remove(address); mCallback.connectionLost(address); } catch (RemoteException e) { Log.e(TAG, "RemoteException in BtStreamWatcher while disconnecting", e); } } } private class ConnectionWaiter implements Runnable { private String srcApp; private int maxConnections; public ConnectionWaiter(String theApp, int connections) { srcApp = theApp; maxConnections = connections; } public void run() { try { for (int i = 0; i < Connection.MAX_SUPPORTED && maxConnections > 0; i++) { BluetoothServerSocket myServerSocket = mBtAdapter .listenUsingRfcommWithServiceRecord(srcApp, mUuid.get(i)); BluetoothSocket myBSock = myServerSocket.accept(); myServerSocket.close(); // Close the socket now that the // connection has been made. String address = myBSock.getRemoteDevice().getAddress(); mBtSockets.put(address, myBSock); mBtDeviceAddresses.add(address); Thread mBtStreamWatcherThread = new Thread(new BtStreamWatcher(address)); mBtStreamWatcherThread.start(); mBtStreamWatcherThreads.put(address, mBtStreamWatcherThread); maxConnections = maxConnections - 1; if (mCallback != null) { mCallback.incomingConnection(address); } } if (mCallback != null) { mCallback.maxConnectionsReached(); } } catch (IOException e) { Log.i(TAG, "IOException in ConnectionService:ConnectionWaiter", e); } catch (RemoteException e) { Log.e(TAG, "RemoteException in ConnectionService:ConnectionWaiter", e); } } } private BluetoothSocket getConnectedSocket(BluetoothDevice myBtServer, UUID uuidToTry) { BluetoothSocket myBSock; try { myBSock = myBtServer.createRfcommSocketToServiceRecord(uuidToTry); myBSock.connect(); return myBSock; } catch (IOException e) { Log.i(TAG, "IOException in getConnectedSocket", e); } return null; } private final IConnection.Stub mBinder = new IConnection.Stub() { public int startServer(String srcApp, int maxConnections) throws RemoteException { if (mApp.length() > 0) { return Connection.FAILURE; } mApp = srcApp; (new Thread(new ConnectionWaiter(srcApp, maxConnections))).start(); Intent i = new Intent(); i.setClass(mSelf, StartDiscoverableModeActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); return Connection.SUCCESS; } public int connect(String srcApp, String device) throws RemoteException { if (mApp.length() > 0) { return Connection.FAILURE; } mApp = srcApp; BluetoothDevice myBtServer = mBtAdapter.getRemoteDevice(device); BluetoothSocket myBSock = null; for (int i = 0; i < Connection.MAX_SUPPORTED && myBSock == null; i++) { for (int j = 0; j < 3 && myBSock == null; j++) { myBSock = getConnectedSocket(myBtServer, mUuid.get(i)); if (myBSock == null) { try { Thread.sleep(200); } catch (InterruptedException e) { Log.e(TAG, "InterruptedException in connect", e); } } } } if (myBSock == null) { return Connection.FAILURE; } mBtSockets.put(device, myBSock); mBtDeviceAddresses.add(device); Thread mBtStreamWatcherThread = new Thread(new BtStreamWatcher(device)); mBtStreamWatcherThread.start(); mBtStreamWatcherThreads.put(device, mBtStreamWatcherThread); return Connection.SUCCESS; } public int broadcastMessage(String srcApp, String message) throws RemoteException { if (!mApp.equals(srcApp)) { return Connection.FAILURE; } for (int i = 0; i < mBtDeviceAddresses.size(); i++) { sendMessage(srcApp, mBtDeviceAddresses.get(i), message); } return Connection.SUCCESS; } public String getConnections(String srcApp) throws RemoteException { if (!mApp.equals(srcApp)) { return ""; } String connections = ""; for (int i = 0; i < mBtDeviceAddresses.size(); i++) { connections = connections + mBtDeviceAddresses.get(i) + ","; } return connections; } public int getVersion() throws RemoteException { try { PackageManager pm = mSelf.getPackageManager(); PackageInfo pInfo = pm.getPackageInfo(mSelf.getPackageName(), 0); return pInfo.versionCode; } catch (NameNotFoundException e) { Log.e(TAG, "NameNotFoundException in getVersion", e); } return 0; } public int registerCallback(String srcApp, IConnectionCallback cb) throws RemoteException { if (!mApp.equals(srcApp)) { return Connection.FAILURE; } mCallback = cb; return Connection.SUCCESS; } public int sendMessage(String srcApp, String destination, String message) throws RemoteException { if (!mApp.equals(srcApp)) { return Connection.FAILURE; } try { BluetoothSocket myBsock = mBtSockets.get(destination); if (myBsock != null) { OutputStream outStream = myBsock.getOutputStream(); byte[] stringAsBytes = (message + " ").getBytes(); stringAsBytes[stringAsBytes.length - 1] = 0; // Add a stop // marker outStream.write(stringAsBytes); return Connection.SUCCESS; } } catch (IOException e) { Log.i(TAG, "IOException in sendMessage - Dest:" + destination + ", Msg:" + message, e); } return Connection.FAILURE; } public void shutdown(String srcApp) throws RemoteException { try { for (int i = 0; i < mBtDeviceAddresses.size(); i++) { BluetoothSocket myBsock = mBtSockets.get(mBtDeviceAddresses.get(i)); myBsock.close(); } mBtSockets = new HashMap<String, BluetoothSocket>(); mBtStreamWatcherThreads = new HashMap<String, Thread>(); mBtDeviceAddresses = new ArrayList<String>(); mApp = ""; } catch (IOException e) { Log.i(TAG, "IOException in shutdown", e); } } public int unregisterCallback(String srcApp) throws RemoteException { if (!mApp.equals(srcApp)) { return Connection.FAILURE; } mCallback = null; return Connection.SUCCESS; } public String getAddress() throws RemoteException { return mBtAdapter.getAddress(); } public String getName() throws RemoteException { return mBtAdapter.getName(); } }; }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import android.app.Activity; import android.app.AlertDialog.Builder; import android.bluetooth.BluetoothAdapter; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.widget.Toast; /** * A simple activity that displays a prompt telling users to enable discoverable * mode for Bluetooth. */ public class StartDiscoverableModeActivity extends Activity { public static final int REQUEST_DISCOVERABLE_CODE = 42; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent i = new Intent(); i.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(i, REQUEST_DISCOVERABLE_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_DISCOVERABLE_CODE) { // Bluetooth Discoverable Mode does not return the standard // Activity result codes. // Instead, the result code is the duration (seconds) of // discoverability or a negative number if the user answered "NO". if (resultCode < 0) { showWarning(); } else { Toast.makeText(this, "Discoverable mode enabled.", 1).show(); finish(); } } } private void showWarning() { Builder warningDialog = new Builder(this); final Activity self = this; warningDialog.setTitle(R.string.DISCOVERABLE_MODE_NOT_ENABLED); warningDialog.setMessage(R.string.WARNING_MESSAGE); warningDialog.setPositiveButton("Yes", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); i.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(i, REQUEST_DISCOVERABLE_CODE); } }); warningDialog.setNegativeButton("No", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Toast.makeText(self, "Discoverable mode NOT enabled.", 1).show(); finish(); } }); warningDialog.setCancelable(false); warningDialog.show(); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * A simple configuration screen that displays the user's current Bluetooth * information along with buttons for entering the Bluetooth settings menu and * for starting a demo app. This is work in progress and only the demo app * buttons are currently available. */ public class ConfigActivity extends Activity { private ConfigActivity self; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); self = this; setContentView(R.layout.config); Button startServer = (Button) findViewById(R.id.start_hockey_server); startServer.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Intent serverIntent = new Intent(self, Demo_Multiscreen.class); Intent serverIntent = new Intent(self, AirHockey.class); serverIntent.putExtra("TYPE", 0); startActivity(serverIntent); } }); Button startClient = (Button) findViewById(R.id.start_hockey_client); startClient.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Intent clientIntent = new Intent(self, Demo_Multiscreen.class); Intent clientIntent = new Intent(self, AirHockey.class); clientIntent.putExtra("TYPE", 1); startActivity(clientIntent); } }); Button startMultiScreenServer = (Button) findViewById(R.id.start_demo_server); startMultiScreenServer.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Intent serverIntent = new Intent(self, Demo_Multiscreen.class); Intent serverIntent = new Intent(self, Demo_Multiscreen.class); serverIntent.putExtra("TYPE", 0); startActivity(serverIntent); } }); Button startMultiScreenClient = (Button) findViewById(R.id.start_demo_client); startMultiScreenClient.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Intent clientIntent = new Intent(self, Demo_Multiscreen.class); Intent clientIntent = new Intent(self, Demo_Multiscreen.class); clientIntent.putExtra("TYPE", 1); startActivity(clientIntent); } }); Button startVideoServer = (Button) findViewById(R.id.start_video_server); startVideoServer.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent serverIntent = new Intent(self, MultiScreenVideo.class); serverIntent.putExtra("isMaster", true); startActivity(serverIntent); } }); Button startVideoClient = (Button) findViewById(R.id.start_video_client); startVideoClient.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent clientIntent = new Intent(self, MultiScreenVideo.class); clientIntent.putExtra("isMaster", false); startActivity(clientIntent); } }); Button gotoWeb = (Button) findViewById(R.id.goto_website); gotoWeb.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://apps-for-android.googlecode.com/svn/trunk/BTClickLinkCompete/docs/index.html"); i.setData(uri); self.startActivity(i); } }); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import net.clc.bt.Connection.OnConnectionLostListener; import net.clc.bt.Connection.OnConnectionServiceReadyListener; import net.clc.bt.Connection.OnIncomingConnectionListener; import net.clc.bt.Connection.OnMaxConnectionsReachedListener; import net.clc.bt.Connection.OnMessageReceivedListener; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.SurfaceHolder.Callback; import android.widget.Toast; /** * Demo application that allows multiple Androids to be linked together as if * they were one large screen. The center screen is the server, and it can link * to 4 other devices: right, left, up, and down. */ public class Demo_Multiscreen extends Activity implements Callback { public static final String TAG = "Demo_Multiscreen"; public static final int CENTER = 0; public static final int RIGHT = 1; public static final int LEFT = 2; public static final int UP = 3; public static final int DOWN = 4; private static final int SERVER_LIST_RESULT_CODE = 42; private Demo_Multiscreen self; private long lastTouchedTime = 0; private int mType; // 0 = server, 1 = client private int mPosition; // The device that has the ball private SurfaceView mSurface; private SurfaceHolder mHolder; private Demo_Ball mBall; private Paint bgPaint; private Paint ballPaint; private Connection mConnection; private String rightDevice = ""; private String leftDevice = ""; private String upDevice = ""; private String downDevice = ""; private OnMessageReceivedListener dataReceivedListener = new OnMessageReceivedListener() { public void OnMessageReceived(String device, String message) { if (message.startsWith("ASSIGNMENT:")) { if (message.equals("ASSIGNMENT:RIGHT")) { leftDevice = device; } else if (message.equals("ASSIGNMENT:LEFT")) { rightDevice = device; } else if (message.equals("ASSIGNMENT:UP")) { downDevice = device; } else if (message.equals("ASSIGNMENT:DOWN")) { upDevice = device; } } else { mPosition = CENTER; mBall.restoreState(message); } } }; private OnMaxConnectionsReachedListener maxConnectionsListener = new OnMaxConnectionsReachedListener() { public void OnMaxConnectionsReached() { Log.e(TAG, "Max connections reached!"); } }; private OnIncomingConnectionListener connectedListener = new OnIncomingConnectionListener() { public void OnIncomingConnection(String device) { if (rightDevice.length() < 1) { mConnection.sendMessage(device, "ASSIGNMENT:RIGHT"); rightDevice = device; } else if (leftDevice.length() < 1) { mConnection.sendMessage(device, "ASSIGNMENT:LEFT"); leftDevice = device; } else if (upDevice.length() < 1) { mConnection.sendMessage(device, "ASSIGNMENT:UP"); upDevice = device; } else if (downDevice.length() < 1) { mConnection.sendMessage(device, "ASSIGNMENT:DOWN"); downDevice = device; } } }; private OnConnectionLostListener disconnectedListener = new OnConnectionLostListener() { public void OnConnectionLost(String device) { if (rightDevice.equals(device)) { rightDevice = ""; if (mPosition == RIGHT) { mBall = new Demo_Ball(true); } } else if (leftDevice.equals(device)) { leftDevice = ""; if (mPosition == LEFT) { mBall = new Demo_Ball(true); } } else if (upDevice.equals(device)) { upDevice = ""; if (mPosition == UP) { mBall = new Demo_Ball(true); } } else if (downDevice.equals(device)) { downDevice = ""; if (mPosition == DOWN) { mBall = new Demo_Ball(true); } } } }; private OnConnectionServiceReadyListener serviceReadyListener = new OnConnectionServiceReadyListener() { public void OnConnectionServiceReady() { if (mType == 0) { mBall = new Demo_Ball(true); mConnection.startServer(4, connectedListener, maxConnectionsListener, dataReceivedListener, disconnectedListener); self.setTitle("MultiScreen: " + mConnection.getName() + "-" + mConnection.getAddress()); } else { mBall = new Demo_Ball(false); Intent serverListIntent = new Intent(self, ServerListActivity.class); startActivityForResult(serverListIntent, SERVER_LIST_RESULT_CODE); } } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); self = this; Intent startingIntent = getIntent(); mType = startingIntent.getIntExtra("TYPE", 0); setContentView(R.layout.main); mSurface = (SurfaceView) findViewById(R.id.surface); mHolder = mSurface.getHolder(); bgPaint = new Paint(); bgPaint.setColor(Color.BLACK); ballPaint = new Paint(); ballPaint.setColor(Color.GREEN); ballPaint.setAntiAlias(true); mConnection = new Connection(this, serviceReadyListener); mHolder.addCallback(self); } private PhysicsLoop pLoop; @Override protected void onDestroy() { if (mConnection != null) { mConnection.shutdown(); } super.onDestroy(); } public void surfaceCreated(SurfaceHolder holder) { pLoop = new PhysicsLoop(); pLoop.start(); } private void draw() { Canvas canvas = null; try { canvas = mHolder.lockCanvas(); if (canvas != null) { doDraw(canvas); } } finally { if (canvas != null) { mHolder.unlockCanvasAndPost(canvas); } } } private void doDraw(Canvas c) { c.drawRect(0, 0, c.getWidth(), c.getHeight(), bgPaint); if (mBall == null) { return; } float x = mBall.getX(); float y = mBall.getY(); if ((x != -1) && (y != -1)) { float xv = mBall.getXVelocity(); Bitmap bmp = BitmapFactory .decodeResource(this.getResources(), R.drawable.android_right); if (xv < 0) { bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.android_left); } c.drawBitmap(bmp, x - 17, y - 23, new Paint()); } } public void surfaceDestroyed(SurfaceHolder holder) { try { pLoop.safeStop(); } finally { pLoop = null; } } private class PhysicsLoop extends Thread { private volatile boolean running = true; @Override public void run() { while (running) { try { Thread.sleep(5); draw(); if (mBall != null) { int position = mBall.update(); mBall.setAcceleration(0, 0); if (position == RIGHT) { if ((rightDevice.length() > 1) && (mConnection.sendMessage(rightDevice, mBall.getState() + "|" + LEFT) == Connection.SUCCESS)) { mPosition = RIGHT; } else { mBall.doRebound(); } } else if (position == LEFT) { if ((leftDevice.length() > 1) && (mConnection.sendMessage(leftDevice, mBall.getState() + "|" + RIGHT) == Connection.SUCCESS)) { mPosition = LEFT; } else { mBall.doRebound(); } } else if (position == UP) { if ((upDevice.length() > 1) && (mConnection.sendMessage(upDevice, mBall.getState() + "|" + DOWN) == Connection.SUCCESS)) { mPosition = UP; } else { mBall.doRebound(); } } else if (position == DOWN) { if ((downDevice.length() > 1) && (mConnection.sendMessage(downDevice, mBall.getState() + "|" + UP) == Connection.SUCCESS)) { mPosition = DOWN; } else { mBall.doRebound(); } } } } catch (InterruptedException ie) { running = false; } } } public void safeStop() { running = false; interrupt(); } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if ((resultCode == Activity.RESULT_OK) && (requestCode == SERVER_LIST_RESULT_CODE)) { String device = data.getStringExtra(ServerListActivity.EXTRA_SELECTED_ADDRESS); int connectionStatus = mConnection.connect(device, dataReceivedListener, disconnectedListener); if (connectionStatus != Connection.SUCCESS) { Toast.makeText(self, "Unable to connect; please try again.", 1).show(); } return; } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { lastTouchedTime = System.currentTimeMillis(); } else if (event.getAction() == MotionEvent.ACTION_UP) { float startX = event.getHistoricalX(0); float startY = event.getHistoricalY(0); float endX = event.getX(); float endY = event.getY(); long timeMs = (System.currentTimeMillis() - lastTouchedTime); float time = timeMs / 1000.0f; float aX = 2 * (endX - startX) / (time * time * 5); float aY = 2 * (endY - startY) / (time * time * 5); // Log.e("Physics debug", startX + " : " + startY + " : " + endX + // " : " + endY + " : " + time + " : " + aX + " : " + aY); float dampeningFudgeFactor = (float) 0.3; if (mBall != null) { mBall.setAcceleration(aX * dampeningFudgeFactor, aY * dampeningFudgeFactor); } return true; } return false; } }
Java
package net.clc.bt; import net.clc.bt.Connection.OnConnectionLostListener; import net.clc.bt.Connection.OnConnectionServiceReadyListener; import net.clc.bt.Connection.OnIncomingConnectionListener; import net.clc.bt.Connection.OnMaxConnectionsReachedListener; import net.clc.bt.Connection.OnMessageReceivedListener; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.media.MediaPlayer; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.SurfaceView; import android.view.WindowManager; import android.view.WindowManager.BadTokenException; import android.widget.LinearLayout; import android.widget.Toast; import android.widget.VideoView; import java.util.ArrayList; public class MultiScreenVideo extends Activity { private class MultiScreenVideoView extends VideoView { public static final int POSITION_LEFT = 0; public static final int POSITION_RIGHT = 1; private int pos; public MultiScreenVideoView(Context context, int position) { super(context); pos = position; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { widthMeasureSpec = MeasureSpec.makeMeasureSpec(960, MeasureSpec.EXACTLY); heightMeasureSpec = MeasureSpec.makeMeasureSpec(640, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } private boolean canSend = true; private class PositionSyncerThread implements Runnable { public void run() { while (mVideo != null) { if (canSend) { canSend = false; mConnection.sendMessage(connectedDevice, "SYNC:" + mVideo.getCurrentPosition()); } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private static final int SERVER_LIST_RESULT_CODE = 42; private MultiScreenVideo self; private MultiScreenVideoView mVideo; private Connection mConnection; private String connectedDevice = ""; private boolean isMaster = false; private int lastSynced = 0; private OnMessageReceivedListener dataReceivedListener = new OnMessageReceivedListener() { public void OnMessageReceived(String device, String message) { if (message.indexOf("SYNC") == 0) { try { String[] syncMessageSplit = message.split(":"); int diff = Integer.parseInt(syncMessageSplit[1]) - mVideo.getCurrentPosition(); Log.e("master - slave diff", Integer.parseInt(syncMessageSplit[1]) - mVideo.getCurrentPosition() + ""); if ((Math.abs(diff) > 100) && (mVideo.getCurrentPosition() - lastSynced > 1000)) { mVideo.seekTo(mVideo.getCurrentPosition() + diff + 300); lastSynced = mVideo.getCurrentPosition() + diff + 300; } } catch (IllegalStateException e) { // Do nothing; this can happen as you are quitting the app // mid video } mConnection.sendMessage(connectedDevice, "ACK"); } else if (message.indexOf("START") == 0) { Log.e("received start", "0"); mVideo.start(); } else if (message.indexOf("ACK") == 0) { canSend = true; } } }; private OnMaxConnectionsReachedListener maxConnectionsListener = new OnMaxConnectionsReachedListener() { public void OnMaxConnectionsReached() { } }; private OnIncomingConnectionListener connectedListener = new OnIncomingConnectionListener() { public void OnIncomingConnection(String device) { connectedDevice = device; if (isMaster) { Log.e("device connected", connectedDevice); mConnection.sendMessage(connectedDevice, "START"); new Thread(new PositionSyncerThread()).start(); try { Thread.sleep(400); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } mVideo.start(); } } }; private OnConnectionLostListener disconnectedListener = new OnConnectionLostListener() { public void OnConnectionLost(String device) { class displayConnectionLostAlert implements Runnable { public void run() { Builder connectionLostAlert = new Builder(self); connectionLostAlert.setTitle("Connection lost"); connectionLostAlert .setMessage("Your connection with the other Android has been lost."); connectionLostAlert.setPositiveButton("Ok", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); connectionLostAlert.setCancelable(false); try { connectionLostAlert.show(); } catch (BadTokenException e) { // Something really bad happened here; // seems like the Activity itself went away before // the runnable finished. // Bail out gracefully here and do nothing. } } } self.runOnUiThread(new displayConnectionLostAlert()); } }; private OnConnectionServiceReadyListener serviceReadyListener = new OnConnectionServiceReadyListener() { public void OnConnectionServiceReady() { if (isMaster) { mConnection.startServer(1, connectedListener, maxConnectionsListener, dataReceivedListener, disconnectedListener); self.setTitle("MultiScreen Video: " + mConnection.getName() + "-" + mConnection.getAddress()); } else { Intent serverListIntent = new Intent(self, ServerListActivity.class); startActivityForResult(serverListIntent, SERVER_LIST_RESULT_CODE); } } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); self = this; Intent startingIntent = getIntent(); isMaster = startingIntent.getBooleanExtra("isMaster", false); int pos = MultiScreenVideoView.POSITION_LEFT; if (!isMaster) { pos = MultiScreenVideoView.POSITION_RIGHT; } mVideo = new MultiScreenVideoView(this, pos); mVideo.setVideoPath("/sdcard/android.mp4"); LinearLayout mLinearLayout = new LinearLayout(this); if (!isMaster) { mLinearLayout.setOrientation(LinearLayout.HORIZONTAL); mLinearLayout.setGravity(Gravity.RIGHT); mLinearLayout.setPadding(0, 0, 120, 0); } mLinearLayout.addView(mVideo); setContentView(mLinearLayout); mConnection = new Connection(this, serviceReadyListener); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if ((resultCode == Activity.RESULT_OK) && (requestCode == SERVER_LIST_RESULT_CODE)) { String device = data.getStringExtra(ServerListActivity.EXTRA_SELECTED_ADDRESS); int connectionStatus = mConnection.connect(device, dataReceivedListener, disconnectedListener); if (connectionStatus != Connection.SUCCESS) { Toast.makeText(self, "Unable to connect; please try again.", 1).show(); } else { connectedDevice = device; } return; } } @Override protected void onDestroy() { super.onDestroy(); if (mConnection != null) { mConnection.shutdown(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.lang.ref.WeakReference; /** * A ball region is a rectangular region that contains bouncing * balls, and possibly one animating line. In its {@link #update(long)} method, * it will update all of its balls, the moving line. It detects collisions * between the balls and the moving line, and when the line is complete, handles * splitting off a new region. */ public class BallRegion extends Shape2d { private float mLeft; private float mRight; private float mTop; private float mBottom; private List<Ball> mBalls; private AnimatingLine mAnimatingLine; private boolean mShrinkingToFit = false; private long mLastUpdate = 0; private static final float PIXELS_PER_SECOND = 25.0f; private static final float SHRINK_TO_FIT_AREA_THRESH = 10000.0f; private static final float SHRINK_TO_FIT_AREA_THRESH_ONE_BALL = 20000.0f; private static final float SHRINK_TO_FIT_AREA = 1000f; private static final float MIN_EDGE = 30f; private boolean mDoneShrinking = false; private WeakReference<BallEngine.BallEventCallBack> mCallBack; /* * @param left The minimum x component * @param right The maximum x component * @param top The minimum y component * @param bottom The maximum y component * @param balls the balls of the region */ public BallRegion(long now, float left, float right, float top, float bottom, ArrayList<Ball> balls) { mLastUpdate = now; mLeft = left; mRight = right; mTop = top; mBottom = bottom; mBalls = balls; final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setRegion(this); } checkShrinkToFit(); } public void setCallBack(BallEngine.BallEventCallBack callBack) { this.mCallBack = new WeakReference<BallEngine.BallEventCallBack>(callBack); } private void checkShrinkToFit() { final float area = getArea(); if (area < SHRINK_TO_FIT_AREA_THRESH) { mShrinkingToFit = true; } else if (area < SHRINK_TO_FIT_AREA_THRESH_ONE_BALL && mBalls.size() == 1) { mShrinkingToFit = true; } } public float getLeft() { return mLeft; } public float getRight() { return mRight; } public float getTop() { return mTop; } public float getBottom() { return mBottom; } public List<Ball> getBalls() { return mBalls; } public AnimatingLine getAnimatingLine() { return mAnimatingLine; } public boolean consumeDoneShrinking() { if (mDoneShrinking) { mDoneShrinking = false; return true; } return false; } public void setNow(long now) { mLastUpdate = now; // update the balls final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setNow(now); } if (mAnimatingLine != null) { mAnimatingLine.setNow(now); } } /** * Update the balls an (if it exists) the animating line in this region. * @param now in millis * @return A new region if a split has occured because the animating line * finished. */ public BallRegion update(long now) { // update the animating line final boolean newRegion = (mAnimatingLine != null && mAnimatingLine.update(now)); final int numBalls = mBalls.size(); // move balls, check for collision with animating line for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.update(now); if (mAnimatingLine != null && ball.isIntersecting(mAnimatingLine)) { mAnimatingLine = null; if (mCallBack != null) mCallBack.get().onBallHitsLine(now, ball, mAnimatingLine); } } // update ball to ball collisions for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); for (int j = i + 1; j < numBalls; j++) { Ball other = mBalls.get(j); if (ball.isCircleOverlapping(other)) { Ball.adjustForCollision(ball, other); break; } } } handleShrinkToFit(now); // no collsion, new region means we need to split out the apropriate // balls into a new region if (newRegion && mAnimatingLine != null) { BallRegion otherRegion = splitRegion( now, mAnimatingLine.getDirection(), mAnimatingLine.getPerpAxisOffset()); mAnimatingLine = null; return otherRegion; } else { return null; } } private void handleShrinkToFit(long now) { // update shrinking to fit if (mShrinkingToFit && mAnimatingLine == null) { if (now == mLastUpdate) return; float delta = (now - mLastUpdate) * PIXELS_PER_SECOND; delta = delta / 1000; if (getHeight() > MIN_EDGE) { mTop += delta; mBottom -= delta; } if (getWidth() > MIN_EDGE) { mLeft += delta; mRight -= delta; } final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setRegion(this); } if (getArea() <= SHRINK_TO_FIT_AREA) { mShrinkingToFit = false; mDoneShrinking = true; } } mLastUpdate = now; } /** * Return whether this region can start a line at a certain point. */ public boolean canStartLineAt(float x, float y) { return !mShrinkingToFit && mAnimatingLine == null && isPointWithin(x, y); } /** * Start a horizontal line at a point. * @param now What 'now' is. * @param x The x coordinate. * @param y The y coordinate. */ public void startHorizontalLine(long now, float x, float y) { if (!canStartLineAt(x, y)) { throw new IllegalArgumentException( "can't start line with point (" + x + "," + y + ")"); } mAnimatingLine = new AnimatingLine(Direction.Horizontal, now, y, x, mLeft, mRight); } /** * Start a vertical line at a point. * @param now What 'now' is. * @param x The x coordinate. * @param y The y coordinate. */ public void startVerticalLine(long now, float x, float y) { if (!canStartLineAt(x, y)) { throw new IllegalArgumentException( "can't start line with point (" + x + "," + y + ")"); } mAnimatingLine = new AnimatingLine(Direction.Vertical, now, x, y, mTop, mBottom); } /** * Splits this region at a certain offset, shrinking this one down and returning * the other region that makes up the rest. * @param direction The direction of the line. * @param perpAxisOffset The offset of the perpendicular axis of the line. * @return A new region containing a portion of the balls. */ private BallRegion splitRegion(long now, Direction direction, float perpAxisOffset) { ArrayList<Ball> splitBalls = new ArrayList<Ball>(); if (direction == Direction.Horizontal) { Iterator<Ball> it = mBalls.iterator(); while (it.hasNext()) { Ball ball = it.next(); if (ball.getY() > perpAxisOffset) { it.remove(); splitBalls.add(ball); } } float oldBottom = mBottom; mBottom = perpAxisOffset; checkShrinkToFit(); final BallRegion region = new BallRegion(now, mLeft, mRight, perpAxisOffset, oldBottom, splitBalls); region.setCallBack(mCallBack.get()); return region; } else { assert(direction == Direction.Vertical); Iterator<Ball> it = mBalls.iterator(); while (it.hasNext()) { Ball ball = it.next(); if (ball.getX() > perpAxisOffset) { it.remove(); splitBalls.add(ball); } } float oldRight = mRight; mRight = perpAxisOffset; checkShrinkToFit(); final BallRegion region = new BallRegion(now, perpAxisOffset, oldRight, mTop, mBottom, splitBalls); region.setCallBack(mCallBack.get()); return region; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * A ball has a current location, a trajectory angle, a speed in pixels per * second, and a last update time. It is capable of updating itself based on * its trajectory and speed. * * It also knows its boundaries, and will 'bounce' off them when it reaches them. */ public class Ball extends Shape2d { private long mLastUpdate; private float mX; private float mY; private double mAngle; private final float mPixelsPerSecond; private final float mRadiusPixels; private Shape2d mRegion; private Ball(long now, float pixelsPerSecond, float x, float y, double angle, float radiusPixels) { mLastUpdate = now; mPixelsPerSecond = pixelsPerSecond; mX = x; mY = y; mAngle = angle; mRadiusPixels = radiusPixels; } public float getX() { return mX; } public float getY() { return mY; } public float getLeft() { return mX - mRadiusPixels; } public float getRight() { return mX + mRadiusPixels; } public float getTop() { return mY - mRadiusPixels; } public float getBottom() { return mY + mRadiusPixels; } public float getRadiusPixels() { return mRadiusPixels; } public double getAngle() { return mAngle; } /** * Get the region the ball is contained in. */ public Shape2d getRegion() { return mRegion; } /** * Set the region that the ball is contained in. * @param region The region. */ public void setRegion(Shape2d region) { if (mX < region.getLeft()) { mX = region.getLeft(); bounceOffLeft(); } else if (mX > region.getRight()) { mX = region.getRight(); bounceOffRight(); } if (mY < region.getTop()) { mY = region.getTop(); bounceOffTop(); } else if (mY > region.getBottom()) { mY = region.getBottom(); bounceOffBottom(); } mRegion = region; } public void setNow(long now) { mLastUpdate = now; } public boolean isCircleOverlapping(Ball otherBall) { final float dy = otherBall.mY - mY; final float dx = otherBall.mX - mX; final float distance = dy * dy + dx * dx; return (distance < ((2 * mRadiusPixels) * (2 *mRadiusPixels))) // avoid jittery collisions && !movingAwayFromEachother(this, otherBall); } private boolean movingAwayFromEachother(Ball ballA, Ball ballB) { double collA = Math.atan2(ballB.mY - ballA.mY, ballB.mX - ballA.mX); double collB = Math.atan2(ballA.mY - ballB.mY, ballA.mX - ballB.mX); double ax = Math.cos(ballA.mAngle - collA); double bx = Math.cos(ballB.mAngle - collB); return ax + bx < 0; } public void update(long now) { if (now <= mLastUpdate) return; // bounce when at walls if (mX <= mRegion.getLeft() + mRadiusPixels) { // we're at left wall mX = mRegion.getLeft() + mRadiusPixels; bounceOffLeft(); } else if (mY <= mRegion.getTop() + mRadiusPixels) { // at top wall mY = mRegion.getTop() + mRadiusPixels; bounceOffTop(); } else if (mX >= mRegion.getRight() - mRadiusPixels) { // at right wall mX = mRegion.getRight() - mRadiusPixels; bounceOffRight(); } else if (mY >= mRegion.getBottom() - mRadiusPixels) { // at bottom wall mY = mRegion.getBottom() - mRadiusPixels; bounceOffBottom(); } float delta = (now - mLastUpdate) * mPixelsPerSecond; delta = delta / 1000f; mX += (delta * Math.cos(mAngle)); mY += (delta * Math.sin(mAngle)); mLastUpdate = now; } private void bounceOffBottom() { if (mAngle < 0.5*Math.PI) { // going right mAngle = -mAngle; } else { // going left mAngle += (Math.PI - mAngle) * 2; } } private void bounceOffRight() { if (mAngle > 1.5*Math.PI) { // going up mAngle -= (mAngle - 1.5*Math.PI) * 2; } else { // going down mAngle += (.5*Math.PI - mAngle) * 2; } } private void bounceOffTop() { if (mAngle < 1.5 * Math.PI) { // going left mAngle -= (mAngle - Math.PI) * 2; } else { // going right mAngle += (2*Math.PI - mAngle) * 2; mAngle -= 2*Math.PI; } } private void bounceOffLeft() { if (mAngle < Math.PI) { // going down mAngle -= ((mAngle - (Math.PI / 2)) * 2); } else { // going up mAngle += (((1.5 * Math.PI) - mAngle) * 2); } } /** * Given that ball a and b have collided, adjust their angles to reflect their state * after the collision. * * This method works based on the conservation of energy and momentum in an elastic * collision. Because the balls have equal mass and speed, it ends up being that they * simply swap velocities along the axis of the collision, keeping the velocities tangent * to the collision constant. * * @param ballA The first ball in a collision * @param ballB The second ball in a collision */ public static void adjustForCollision(Ball ballA, Ball ballB) { final double collA = Math.atan2(ballB.mY - ballA.mY, ballB.mX - ballA.mX); final double collB = Math.atan2(ballA.mY - ballB.mY, ballA.mX - ballB.mX); final double ax = Math.cos(ballA.mAngle - collA); final double ay = Math.sin(ballA.mAngle - collA); final double bx = Math.cos(ballB.mAngle - collB); final double by = Math.cos(ballB.mAngle - collB); final double diffA = Math.atan2(ay, -bx); final double diffB = Math.atan2(by, -ax); ballA.mAngle = collA + diffA; ballB.mAngle = collB + diffB; } @Override public String toString() { return String.format( "Ball(x=%f, y=%f, angle=%f)", mX, mY, Math.toDegrees(mAngle)); } /** * A more readable way to create balls than using a 5 param * constructor of all numbers. */ public static class Builder { private long mNow = -1; private float mX = -1; private float mY = -1; private double mAngle = -1; private float mRadiusPixels = -1; private float mPixelsPerSecond = 45f; public Ball create() { if (mNow < 0) { throw new IllegalStateException("must set 'now'"); } if (mX < 0) { throw new IllegalStateException("X must be set"); } if (mY < 0) { throw new IllegalStateException("Y must be stet"); } if (mAngle < 0) { throw new IllegalStateException("angle must be set"); } if (mAngle > 2 * Math.PI) { throw new IllegalStateException("angle must be less that 2Pi"); } if (mRadiusPixels <= 0) { throw new IllegalStateException("radius must be set"); } return new Ball(mNow, mPixelsPerSecond, mX, mY, mAngle, mRadiusPixels); } public Builder setNow(long now) { mNow = now; return this; } public Builder setPixelsPerSecond(float pixelsPerSecond) { mPixelsPerSecond = pixelsPerSecond; return this; } public Builder setX(float x) { mX = x; return this; } public Builder setY(float y) { mY = y; return this; } public Builder setAngle(double angle) { mAngle = angle; return this; } public Builder setRadiusPixels(float pixels) { mRadiusPixels = pixels; return this; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.app.Dialog; import android.view.View; import android.content.Context; import android.os.Bundle; public class GameOverDialog extends Dialog implements View.OnClickListener { private View mNewGame; private final NewGameCallback mCallback; private View mQuit; public GameOverDialog(Context context, NewGameCallback callback) { super(context); mCallback = callback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.game_over); setContentView(R.layout.game_over_dialog); mNewGame = findViewById(R.id.newGame); mNewGame.setOnClickListener(this); mQuit = findViewById(R.id.quit); mQuit.setOnClickListener(this); } /** {@inheritDoc} */ public void onClick(View v) { if (v == mNewGame) { mCallback.onNewGame(); dismiss(); } else if (v == mQuit) { cancel(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * To specify a dividing line, a user hits the screen and drags in a * certain direction. Once the line has been drawn long enough and mostly * in a particular direction (vertical, or horizontal), we can decide we * know what they mean. Otherwise, it is unknown. * * This is also nice because if the user decides they don't want to send * a dividing line, they can just drag their finger back to where they first * touched and let go, cancelling. */ public class DirectionPoint { enum AmbiguousDirection { Vertical, Horizonal, Unknown } private float mX; private float mY; private float endLineX; private float endLineY; public DirectionPoint(float x, float y) { mX = x; mY = y; endLineX = x; endLineY = y; } public void updateEndPoint(float x, float y) { endLineX = x; endLineY = y; } public float getX() { return mX; } public float getY() { return mY; } /** * We know the direction when the line is at leat 20 pixels long, * and the angle is no more than PI / 6 away from a definitive direction. */ public AmbiguousDirection getDirection() { float dx = endLineX - mX; double distance = Math.hypot(dx, endLineY - mY); if (distance < 10) { return AmbiguousDirection.Unknown; } double angle = Math.acos(dx / distance); double thresh = Math.PI / 6; if ((angle < thresh || (angle > (Math.PI - thresh)))) { return AmbiguousDirection.Horizonal; } if ((angle > 2 * thresh) && angle < 4*thresh) { return AmbiguousDirection.Vertical; } return AmbiguousDirection.Unknown; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.os.Bundle; import android.preference.*; import android.content.Context; import android.content.SharedPreferences; /** * Holds preferences for the game */ public class Preferences extends PreferenceActivity { public static final String KEY_VIBRATE = "key_vibrate"; public static final String KEY_DIFFICULTY = "key_difficulty"; public enum Difficulty { Easy(5), Medium(3), Hard(1); private final int mLivesToStart; Difficulty(int livesToStart) { mLivesToStart = livesToStart; } public int getLivesToStart() { return mLivesToStart; } } public static Difficulty getCurrentDifficulty(Context context) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); final String diffic = preferences .getString(KEY_DIFFICULTY, DEFAULT_DIFFICULTY.toString()); return Difficulty.valueOf(diffic); } public static final Difficulty DEFAULT_DIFFICULTY = Difficulty.Medium; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPreferenceScreen(createPreferenceHierarchy()); } private PreferenceScreen createPreferenceHierarchy() { // Root PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this); // vibrate on/off CheckBoxPreference vibratePref = new CheckBoxPreference(this); vibratePref.setDefaultValue(true); vibratePref.setKey(KEY_VIBRATE); vibratePref.setTitle(R.string.settings_vibrate); vibratePref.setSummary(R.string.settings_vibrate_summary); root.addPreference(vibratePref); // difficulty level ListPreference difficultyPref = new ListPreference(this); difficultyPref.setEntries(new String[] { getString(R.string.settings_five_lives), getString(R.string.settings_three_lives), getString(R.string.settings_one_life)}); difficultyPref.setEntryValues(new String[] { Difficulty.Easy.toString(), Difficulty.Medium.toString(), Difficulty.Hard.toString()}); difficultyPref.setKey(KEY_DIFFICULTY); difficultyPref.setTitle(R.string.settings_difficulty); difficultyPref.setSummary(R.string.settings_difficulty_summary); final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); if (!sharedPrefs.contains(KEY_DIFFICULTY)) { difficultyPref.setValue(DEFAULT_DIFFICULTY.toString()); } root.addPreference(difficultyPref); return root; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * Either vertical or horizontal. Used by animating lines and * ball regions. */ public enum Direction { Vertical, Horizontal }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; /** * When the game starts, the user is welcomed with a message, and buttons for * starting a new game, or getting instructions about the game. */ public class WelcomeDialog extends Dialog implements View.OnClickListener { private final NewGameCallback mCallback; private View mNewGame; public WelcomeDialog(Context context, NewGameCallback callback) { super(context); mCallback = callback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.app_name); setContentView(R.layout.welcome_dialog); mNewGame = findViewById(R.id.newGame); mNewGame.setOnClickListener(this); } /** {@inheritDoc} */ public void onClick(View v) { if (v == mNewGame) { mCallback.onNewGame(); dismiss(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.content.Context; import android.content.res.Resources; import android.graphics.*; import android.graphics.drawable.GradientDrawable; import android.os.Debug; import android.os.SystemClock; import android.util.AttributeSet; import android.util.TypedValue; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import java.util.List; import java.util.ArrayList; /** * Handles the visual display and touch input for the game. */ public class DivideAndConquerView extends View implements BallEngine.BallEventCallBack { static final int BORDER_WIDTH = 10; // this needs to match size of ball drawable static final float BALL_RADIUS = 5f; static final float BALL_SPEED = 80f; // if true, will profile the drawing code during each animating line and export // the result to a file named 'BallsDrawing.trace' on the sd card // this file can be pulled off and profiled with traceview // $ adb pull /sdcard/BallsDrawing.trace . // traceview BallsDrawing.trace private static final boolean PROFILE_DRAWING = false; private boolean mDrawingProfilingStarted = false; private final Paint mPaint; private BallEngine mEngine; private Mode mMode = Mode.Paused; private BallEngineCallBack mCallback; // interface for starting a line private DirectionPoint mDirectionPoint = null; private Bitmap mBallBitmap; private float mBallBitmapRadius; private final Bitmap mExplosion1; private final Bitmap mExplosion2; private final Bitmap mExplosion3; /** * Callback notifying of events related to the ball engine. */ static interface BallEngineCallBack { /** * The engine has its dimensions and is ready to go. * @param ballEngine The ball engine. */ void onEngineReady(BallEngine ballEngine); /** * A ball has hit a moving line. * @param ballEngine The engine. * @param x The x coordinate of the ball. * @param y The y coordinate of the ball. */ void onBallHitsMovingLine(BallEngine ballEngine, float x, float y); /** * A line made it to the edges of its region, splitting off a new region. * @param ballEngine The engine. */ void onAreaChange(BallEngine ballEngine); } /** * @return The ball engine associated with the game. */ public BallEngine getEngine() { return mEngine; } /** * Keeps track of the mode of this view. */ enum Mode { /** * The balls are bouncing around. */ Bouncing, /** * The animation has stopped and the balls won't move around. The user * may not unpause it; this is used to temporarily stop games between * levels, or when the game is over and the activity places a dialog up. */ Paused, /** * Same as {@link #Paused}, but paints the word 'touch to unpause' on * the screen, so the user knows he/she can unpause the game. */ PausedByUser } public DivideAndConquerView(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStrokeWidth(2); mPaint.setColor(Color.BLACK); // so we can see the back key setFocusableInTouchMode(true); drawBackgroundGradient(); mBallBitmap = BitmapFactory.decodeResource( context.getResources(), R.drawable.ball); mBallBitmapRadius = ((float) mBallBitmap.getWidth()) / 2f; mExplosion1 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion1); mExplosion2 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion2); mExplosion3 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion3); } final GradientDrawable mBackgroundGradient = new GradientDrawable( GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.RED, Color.YELLOW}); void drawBackgroundGradient() { setBackgroundDrawable(mBackgroundGradient); } /** * Set the callback that will be notified of events related to the ball * engine. * @param callback The callback. */ public void setCallback(BallEngineCallBack callback) { mCallback = callback; } @Override protected void onSizeChanged(int i, int i1, int i2, int i3) { super.onSizeChanged(i, i1, i2, i3); // this should only happen once when the activity is first launched. // we could be smarter about saving / restoring across activity // lifecycles, but for now, this is good enough to handle in game play, // and most cases of navigating away with the home key and coming back. mEngine = new BallEngine( BORDER_WIDTH, getWidth() - BORDER_WIDTH, BORDER_WIDTH, getHeight() - BORDER_WIDTH, BALL_SPEED, BALL_RADIUS); mEngine.setCallBack(this); mCallback.onEngineReady(mEngine); } /** * @return the current mode of operation. */ public Mode getMode() { return mMode; } /** * Set the mode of operation. * @param mode The mode. */ public void setMode(Mode mode) { mMode = mode; if (mMode == Mode.Bouncing && mEngine != null) { // when starting up again, the engine needs to know what 'now' is. final long now = SystemClock.elapsedRealtime(); mEngine.setNow(now); mExplosions.clear(); invalidate(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // the first time the user hits back while the balls are moving, // we'll pause the game. but if they hit back again, we'll do the usual // (exit the activity) if (keyCode == KeyEvent.KEYCODE_BACK && mMode == Mode.Bouncing) { setMode(Mode.PausedByUser); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onTouchEvent(MotionEvent motionEvent) { if (mMode == Mode.PausedByUser) { // touching unpauses when the game was paused by the user. setMode(Mode.Bouncing); return true; } else if (mMode == Mode.Paused) { return false; } final float x = motionEvent.getX(); final float y = motionEvent.getY(); switch(motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: if (mEngine.canStartLineAt(x, y)) { mDirectionPoint = new DirectionPoint(x, y); } return true; case MotionEvent.ACTION_MOVE: if (mDirectionPoint != null) { mDirectionPoint.updateEndPoint(x, y); } else if (mEngine.canStartLineAt(x, y)) { mDirectionPoint = new DirectionPoint(x, y); } return true; case MotionEvent.ACTION_UP: if (mDirectionPoint != null) { switch (mDirectionPoint.getDirection()) { case Unknown: // do nothing break; case Horizonal: mEngine.startHorizontalLine(SystemClock.elapsedRealtime(), mDirectionPoint.getX(), mDirectionPoint.getY()); if (PROFILE_DRAWING) { if (!mDrawingProfilingStarted) { Debug.startMethodTracing("BallsDrawing"); mDrawingProfilingStarted = true; } } break; case Vertical: mEngine.startVerticalLine(SystemClock.elapsedRealtime(), mDirectionPoint.getX(), mDirectionPoint.getY()); if (PROFILE_DRAWING) { if (!mDrawingProfilingStarted) { Debug.startMethodTracing("BallsDrawing"); mDrawingProfilingStarted = true; } } break; } } mDirectionPoint = null; return true; case MotionEvent.ACTION_CANCEL: mDirectionPoint = null; return true; } return false; } /** {@inheritDoc} */ public void onBallHitsBall(Ball ballA, Ball ballB) { } /** {@inheritDoc} */ public void onBallHitsLine(long when, Ball ball, AnimatingLine animatingLine) { mCallback.onBallHitsMovingLine(mEngine, ball.getX(), ball.getY()); mExplosions.add( new Explosion( when, ball.getX(), ball.getY(), mExplosion1, mExplosion2, mExplosion3)); } static class Explosion { private long mLastUpdate; private long mProgress = 0; private final float mX; private final float mY; private final Bitmap mExplosion1; private final Bitmap mExplosion2; private final Bitmap mExplosion3; private final float mRadius; Explosion(long mLastUpdate, float mX, float mY, Bitmap explosion1, Bitmap explosion2, Bitmap explosion3) { this.mLastUpdate = mLastUpdate; this.mX = mX; this.mY = mY; this.mExplosion1 = explosion1; this.mExplosion2 = explosion2; this.mExplosion3 = explosion3; mRadius = ((float) mExplosion1.getWidth()) / 2f; } public void update(long now) { mProgress += (now - mLastUpdate); mLastUpdate = now; } public void setNow(long now) { mLastUpdate = now; } public void draw(Canvas canvas, Paint paint) { if (mProgress < 80L) { canvas.drawBitmap(mExplosion1, mX - mRadius, mY - mRadius, paint); } else if (mProgress < 160L) { canvas.drawBitmap(mExplosion2, mX - mRadius, mY - mRadius, paint); } else if (mProgress < 400L) { canvas.drawBitmap(mExplosion3, mX - mRadius, mY - mRadius, paint); } } public boolean done() { return mProgress > 700L; } } private ArrayList<Explosion> mExplosions = new ArrayList<Explosion>(); @Override protected void onDraw(Canvas canvas) { boolean newRegion = false; if (mMode == Mode.Bouncing) { // handle the ball engine final long now = SystemClock.elapsedRealtime(); newRegion = mEngine.update(now); if (newRegion) { mCallback.onAreaChange(mEngine); // reset back to full alpha bg color drawBackgroundGradient(); } if (PROFILE_DRAWING) { if (newRegion && mDrawingProfilingStarted) { mDrawingProfilingStarted = false; Debug.stopMethodTracing(); } } // the X-plosions for (int i = 0; i < mExplosions.size(); i++) { final Explosion explosion = mExplosions.get(i); explosion.update(now); } } for (int i = 0; i < mEngine.getRegions().size(); i++) { BallRegion region = mEngine.getRegions().get(i); drawRegion(canvas, region); } for (int i = 0; i < mExplosions.size(); i++) { final Explosion explosion = mExplosions.get(i); explosion.draw(canvas, mPaint); // TODO prune explosions that are done } if (mMode == Mode.PausedByUser) { drawPausedText(canvas); } else if (mMode == Mode.Bouncing) { // keep em' bouncing! invalidate(); } } /** * Pain the text instructing the user how to unpause the game. */ private void drawPausedText(Canvas canvas) { mPaint.setColor(Color.BLACK); mPaint.setAntiAlias(true); mPaint.setTextSize( TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics())); final String unpauseInstructions = getContext().getString(R.string.unpause_instructions); canvas.drawText(unpauseInstructions, getWidth() / 5, getHeight() / 2, mPaint); mPaint.setAntiAlias(false); } private RectF mRectF = new RectF(); /** * Draw a ball region. */ private void drawRegion(Canvas canvas, BallRegion region) { // draw fill rect to offset against background mPaint.setColor(Color.LTGRAY); mRectF.set(region.getLeft(), region.getTop(), region.getRight(), region.getBottom()); canvas.drawRect(mRectF, mPaint); //draw an outline mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.WHITE); canvas.drawRect(mRectF, mPaint); mPaint.setStyle(Paint.Style.FILL); // restore style // draw each ball for (Ball ball : region.getBalls()) { // canvas.drawCircle(ball.getX(), ball.getY(), BALL_RADIUS, mPaint); canvas.drawBitmap( mBallBitmap, ball.getX() - mBallBitmapRadius, ball.getY() - mBallBitmapRadius, mPaint); } // draw the animating line final AnimatingLine al = region.getAnimatingLine(); if (al != null) { drawAnimatingLine(canvas, al); } } private static int scaleToBlack(int component, float percentage) { // return (int) ((1f - percentage*0.4f) * component); return (int) (percentage * 0.6f * (0xFF - component) + component); } /** * Draw an animating line. */ private void drawAnimatingLine(Canvas canvas, AnimatingLine al) { final float perc = al.getPercentageDone(); final int color = Color.RED; mPaint.setColor(Color.argb( 0xFF, scaleToBlack(Color.red(color), perc), scaleToBlack(Color.green(color), perc), scaleToBlack(Color.blue(color), perc) )); switch (al.getDirection()) { case Horizontal: canvas.drawLine( al.getStart(), al.getPerpAxisOffset(), al.getEnd(), al.getPerpAxisOffset(), mPaint); break; case Vertical: canvas.drawLine( al.getPerpAxisOffset(), al.getStart(), al.getPerpAxisOffset(), al.getEnd(), mPaint); break; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * Keeps the state for the line that extends in two directions until it hits its boundaries. This is triggered * by the user gesture in a horizontal or vertical direction. */ public class AnimatingLine extends Shape2d { private Direction mDirection; // for vertical lines, the y offset // for horizontal, the x offset float mPerpAxisOffset; float mStart; float mEnd; float mMin; float mMax; private long mLastUpdate = 0; private float mPixelsPerSecond = 101.0f; /** * @param direction The direction of the line * @param now What 'now' is * @param axisStart Where on the perpindicular axis the line is extending from * @param start The point the line is extending from on the parallel axis * @param min The lower bound for the line (i.e the left most point) * @param max The upper bound for the line (i.e the right most point) */ public AnimatingLine( Direction direction, long now, float axisStart, float start, float min, float max) { mDirection = direction; mLastUpdate = now; mPerpAxisOffset = axisStart; mStart = mEnd = start; mMin = min; mMax = max; } public Direction getDirection() { return mDirection; } public float getPerpAxisOffset() { return mPerpAxisOffset; } public float getStart() { return mStart; } public float getEnd() { return mEnd; } public float getMin() { return mMin; } public float getMax() { return mMax; } public float getLeft() { return mDirection == Direction.Horizontal ? mStart : mPerpAxisOffset; } public float getRight() { return mDirection == Direction.Horizontal ? mEnd : mPerpAxisOffset; } public float getTop() { return mDirection == Direction.Vertical ? mStart : mPerpAxisOffset; } public float getBottom() { return mDirection == Direction.Vertical ? mEnd : mPerpAxisOffset; } public float getPercentageDone() { return (mEnd - mStart) / (mMax - mMin); } /** * Extend the line according to the animation. * @return whether the line has reached its end. */ public boolean update(long time) { if (time == mLastUpdate) return false; float delta = (time - mLastUpdate) * mPixelsPerSecond; delta = delta / 1000; mLastUpdate = time; mStart -= delta; mEnd += delta; if (mStart < mMin) mStart = mMin; if (mEnd > mMax) mEnd = mMax; return mStart == mMin && mEnd == mMax; } public void setNow(long now) { mLastUpdate = now; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * Used by dialogs to tell the activity the user wants a new game. */ public interface NewGameCallback { /** * The user wants to start a new game. */ void onNewGame(); }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.os.Vibrator; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.Gravity; import android.widget.TextView; import android.widget.Toast; import android.graphics.Color; import java.util.Stack; /** * The activity for the game. Listens for callbacks from the game engine, and * response appropriately, such as bringing up a 'game over' dialog when a ball * hits a moving line and there is only one life left. */ public class DivideAndConquerActivity extends Activity implements DivideAndConquerView.BallEngineCallBack, NewGameCallback, DialogInterface.OnCancelListener { private static final int NEW_GAME_NUM_BALLS = 1; private static final double LEVEL_UP_THRESHOLD = 0.8; private static final int COLLISION_VIBRATE_MILLIS = 50; private boolean mVibrateOn; private int mNumBalls = NEW_GAME_NUM_BALLS; private DivideAndConquerView mBallsView; private static final int WELCOME_DIALOG = 20; private static final int GAME_OVER_DIALOG = 21; private WelcomeDialog mWelcomeDialog; private GameOverDialog mGameOverDialog; private TextView mLivesLeft; private TextView mPercentContained; private int mNumLives; private Vibrator mVibrator; private TextView mLevelInfo; private int mNumLivesStart = 5; private Toast mCurrentToast; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Turn off the title bar requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); mBallsView = (DivideAndConquerView) findViewById(R.id.ballsView); mBallsView.setCallback(this); mPercentContained = (TextView) findViewById(R.id.percentContained); mLevelInfo = (TextView) findViewById(R.id.levelInfo); mLivesLeft = (TextView) findViewById(R.id.livesLeft); // we'll vibrate when the ball hits the moving line mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); } /** {@inheritDoc} */ public void onEngineReady(BallEngine ballEngine) { // display 10 balls bouncing around for visual effect ballEngine.reset(SystemClock.elapsedRealtime(), 10); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); // show the welcome dialog showDialog(WELCOME_DIALOG); } @Override protected Dialog onCreateDialog(int id) { if (id == WELCOME_DIALOG) { mWelcomeDialog = new WelcomeDialog(this, this); mWelcomeDialog.setOnCancelListener(this); return mWelcomeDialog; } else if (id == GAME_OVER_DIALOG) { mGameOverDialog = new GameOverDialog(this, this); mGameOverDialog.setOnCancelListener(this); return mGameOverDialog; } return null; } @Override protected void onPause() { super.onPause(); mBallsView.setMode(DivideAndConquerView.Mode.PausedByUser); } @Override protected void onResume() { super.onResume(); mVibrateOn = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(Preferences.KEY_VIBRATE, true); mNumLivesStart = Preferences.getCurrentDifficulty(this).getLivesToStart(); } private static final int MENU_NEW_GAME = Menu.FIRST; private static final int MENU_SETTINGS = Menu.FIRST + 1; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_NEW_GAME, MENU_NEW_GAME, "New Game"); menu.add(0, MENU_SETTINGS, MENU_SETTINGS, "Settings"); return true; } /** * We pause the game while the menu is open; this remembers what it was * so we can restore when the menu closes */ Stack<DivideAndConquerView.Mode> mRestoreMode = new Stack<DivideAndConquerView.Mode>(); @Override public boolean onMenuOpened(int featureId, Menu menu) { saveMode(); mBallsView.setMode(DivideAndConquerView.Mode.Paused); return super.onMenuOpened(featureId, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_NEW_GAME: cancelToasts(); onNewGame(); break; case MENU_SETTINGS: final Intent intent = new Intent(); intent.setClass(this, Preferences.class); startActivity(intent); break; } mRestoreMode.pop(); // don't want to restore when an action was taken return true; } @Override public void onOptionsMenuClosed(Menu menu) { super.onOptionsMenuClosed(menu); restoreMode(); } private void saveMode() { // don't want to restore to a state where user can't resume game. final DivideAndConquerView.Mode mode = mBallsView.getMode(); final DivideAndConquerView.Mode toRestore = (mode == DivideAndConquerView.Mode.Paused) ? DivideAndConquerView.Mode.PausedByUser : mode; mRestoreMode.push(toRestore); } private void restoreMode() { if (!mRestoreMode.isEmpty()) { mBallsView.setMode(mRestoreMode.pop()); } } /** {@inheritDoc} */ public void onBallHitsMovingLine(final BallEngine ballEngine, float x, float y) { if (--mNumLives == 0) { saveMode(); mBallsView.setMode(DivideAndConquerView.Mode.Paused); // vibrate three times if (mVibrateOn) { mVibrator.vibrate( new long[]{0l, COLLISION_VIBRATE_MILLIS, 50l, COLLISION_VIBRATE_MILLIS, 50l, COLLISION_VIBRATE_MILLIS}, -1); } showDialog(GAME_OVER_DIALOG); } else { if (mVibrateOn) { mVibrator.vibrate(COLLISION_VIBRATE_MILLIS); } updateLivesDisplay(mNumLives); if (mNumLives <= 1) { mBallsView.postDelayed(mOneLifeToastRunnable, 700); } else { mBallsView.postDelayed(mLivesBlinkRedRunnable, 700); } } } private Runnable mOneLifeToastRunnable = new Runnable() { public void run() { showToast("1 life left!"); } }; private Runnable mLivesBlinkRedRunnable = new Runnable() { public void run() { mLivesLeft.setTextColor(Color.RED); mLivesLeft.postDelayed(mLivesTextWhiteRunnable, 2000); } }; /** {@inheritDoc} */ public void onAreaChange(final BallEngine ballEngine) { final float percentageFilled = ballEngine.getPercentageFilled(); updatePercentDisplay(percentageFilled); if (percentageFilled > LEVEL_UP_THRESHOLD) { levelUp(ballEngine); } } /** * Go to the next level * @param ballEngine The ball engine. */ private void levelUp(final BallEngine ballEngine) { mNumBalls++; updatePercentDisplay(0); updateLevelDisplay(mNumBalls); ballEngine.reset(SystemClock.elapsedRealtime(), mNumBalls); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); if (mNumBalls % 4 == 0) { mNumLives++; updateLivesDisplay(mNumLives); showToast("bonus life!"); } if (mNumBalls == 10) { showToast("Level 10? You ROCK!"); } else if (mNumBalls == 15) { showToast("BALLS TO THE WALL!"); } } private Runnable mLivesTextWhiteRunnable = new Runnable() { public void run() { mLivesLeft.setTextColor(Color.WHITE); } }; private void showToast(String text) { cancelToasts(); mCurrentToast = Toast.makeText(this, text, Toast.LENGTH_SHORT); mCurrentToast.show(); } private void cancelToasts() { if (mCurrentToast != null) { mCurrentToast.cancel(); mCurrentToast = null; } } /** * Update the header that displays how much of the space has been contained. * @param amountFilled The fraction, between 0 and 1, that is filled. */ private void updatePercentDisplay(float amountFilled) { final int prettyPercent = (int) (amountFilled *100); mPercentContained.setText( getString(R.string.percent_contained, prettyPercent)); } /** {@inheritDoc} */ public void onNewGame() { mNumBalls = NEW_GAME_NUM_BALLS; mNumLives = mNumLivesStart; updatePercentDisplay(0); updateLivesDisplay(mNumLives); updateLevelDisplay(mNumBalls); mBallsView.getEngine().reset(SystemClock.elapsedRealtime(), mNumBalls); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); } /** * Update the header displaying the current level */ private void updateLevelDisplay(int numBalls) { mLevelInfo.setText(getString(R.string.level, numBalls)); } /** * Update the display showing the number of lives left. * @param numLives The number of lives left. */ void updateLivesDisplay(int numLives) { String text = (numLives == 1) ? getString(R.string.one_life_left) : getString(R.string.lives_left, numLives); mLivesLeft.setText(text); } /** {@inheritDoc} */ public void onCancel(DialogInterface dialog) { if (dialog == mWelcomeDialog || dialog == mGameOverDialog) { // user hit back, they're done finish(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.util.Log; import android.content.Context; import android.widget.Toast; import java.util.List; import java.util.ArrayList; import java.util.Iterator; /** * Keeps track of the current state of balls bouncing around within a a set of * regions. * * Note: 'now' is the elapsed time in milliseconds since some consistent point in time. * As long as the reference point stays consistent, the engine will be happy, though * typically this is {@link android.os.SystemClock#elapsedRealtime()} */ public class BallEngine { static public interface BallEventCallBack { void onBallHitsBall(Ball ballA, Ball ballB); void onBallHitsLine(long when, Ball ball, AnimatingLine animatingLine); } private final float mMinX; private final float mMaxX; private final float mMinY; private final float mMaxY; private float mBallSpeed; private float mBallRadius; private BallEventCallBack mCallBack; /** * Holds onto new regions during a split */ private List<BallRegion> mNewRegions = new ArrayList<BallRegion>(8); private List<BallRegion> mRegions = new ArrayList<BallRegion>(8); public BallEngine(float minX, float maxX, float minY, float maxY, float ballSpeed, float ballRadius) { mMinX = minX; mMaxX = maxX; mMinY = minY; mMaxY = maxY; mBallSpeed = ballSpeed; mBallRadius = ballRadius; } public void setCallBack(BallEventCallBack mCallBack) { this.mCallBack = mCallBack; } /** * Update the notion of 'now' in milliseconds. This can be usefull * when unpausing for instance. * @param now Milliseconds since some consistent point in time. */ public void setNow(long now) { for (int i = 0; i < mRegions.size(); i++) { final BallRegion region = mRegions.get(i); region.setNow(now); } } /** * Rest the engine back to a single region with a certain number of balls * that will be placed randomly and sent in random directions. * @param now milliseconds since some consistent point in time. * @param numBalls */ public void reset(long now, int numBalls) { mRegions.clear(); ArrayList<Ball> balls = new ArrayList<Ball>(numBalls); for (int i = 0; i < numBalls; i++) { Ball ball = new Ball.Builder() .setNow(now) .setPixelsPerSecond(mBallSpeed) .setAngle(Math.random() * 2 * Math.PI) .setX((float) Math.random() * (mMaxX - mMinX) + mMinX) .setY((float) Math.random() * (mMaxY - mMinY) + mMinY) .setRadiusPixels(mBallRadius) .create(); balls.add(ball); } BallRegion region = new BallRegion(now, mMinX, mMaxX, mMinY, mMaxY, balls); region.setCallBack(mCallBack); mRegions.add(region); } public List<BallRegion> getRegions() { return mRegions; } public float getPercentageFilled() { float total = 0f; for (int i = 0; i < mRegions.size(); i++) { BallRegion region = mRegions.get(i); total += region.getArea(); Log.d("Balls", "total now " + total); } return 1f - (total / getArea()); } /** * @return the area in the region in pixel*pixel */ public float getArea() { return (mMaxX - mMinX) * (mMaxY - mMinY); } /** * Can any of the regions within start a line at this point? * @param x The x coordinate. * @param y The y coordinate * @return Whether a region can start a line. */ public boolean canStartLineAt(float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { return true; } } return false; } /** * Start a horizontal line at a certain point. * @throws IllegalArgumentException if there is no region that can start a * line at the point. */ public void startHorizontalLine(long now, float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { region.startHorizontalLine(now, x, y); return; } } throw new IllegalArgumentException("no region can start a new line at " + x + ", " + y + "."); } /** * Start a vertical line at a certain point. * @throws IllegalArgumentException if there is no region that can start a * line at the point. */ public void startVerticalLine(long now, float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { region.startVerticalLine(now, x, y); return; } } throw new IllegalArgumentException("no region can start a new line at " + x + ", " + y + "."); } /** * @param now The latest notion of 'now' * @return whether any new regions were added by the update. */ public boolean update(long now) { boolean regionChange = false; Iterator<BallRegion> it = mRegions.iterator(); while (it.hasNext()) { final BallRegion region = it.next(); final BallRegion newRegion = region.update(now); if (newRegion != null) { regionChange = true; if (!newRegion.getBalls().isEmpty()) { mNewRegions.add(newRegion); } // current region may not have any balls left if (region.getBalls().isEmpty()) { it.remove(); } } else if (region.consumeDoneShrinking()) { regionChange = true; } } mRegions.addAll(mNewRegions); mNewRegions.clear(); return regionChange; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * A 2d shape has left, right, top and bottom dimensions. * */ public abstract class Shape2d { public abstract float getLeft(); public abstract float getRight(); public abstract float getTop(); public abstract float getBottom(); /** * @param other Another 2d shape * @return Whether this shape is intersecting with the other. */ public boolean isIntersecting(Shape2d other) { return getLeft() <= other.getRight() && getRight() >= other.getLeft() && getTop() <= other.getBottom() && getBottom() >= other.getTop(); } /** * @param x An x coordinate * @param y A y coordinate * @return Whether the point is within this shape */ public boolean isPointWithin(float x, float y) { return (x > getLeft() && x < getRight() && y > getTop() && y < getBottom()); } public float getArea() { return getHeight() * getWidth(); } public float getHeight() { return getBottom() - getTop(); } public float getWidth () { return getRight() - getLeft(); } }
Java
package com.example.android.rings_extended; import android.app.ListActivity; import android.content.AsyncQueryHandler; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.CharArrayBuffer; import android.database.Cursor; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.provider.MediaStore; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.ListView; import android.widget.RadioButton; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import java.io.IOException; import java.text.Collator; import java.util.Formatter; import java.util.Locale; /** * Activity allowing the user to select a music track on the device, and * return it to its caller. The music picker user interface is fairly * extensive, providing information about each track like the music * application (title, author, album, duration), as well as the ability to * previous tracks and sort them in different orders. * * <p>This class also illustrates how you can load data from a content * provider asynchronously, providing a good UI while doing so, perform * indexing of the content for use inside of a {@link FastScrollView}, and * perform filtering of the data as the user presses keys. */ public class MusicPicker extends ListActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener { static final boolean DBG = false; static final String TAG = "MusicPicker"; /** Holds the previous state of the list, to restore after the async * query has completed. */ static final String LIST_STATE_KEY = "liststate"; /** Remember whether the list last had focus for restoring its state. */ static final String FOCUS_KEY = "focused"; /** Remember the last ordering mode for restoring state. */ static final String SORT_MODE_KEY = "sortMode"; /** Arbitrary number, doesn't matter since we only do one query type. */ final int MY_QUERY_TOKEN = 42; /** Menu item to sort the music list by track title. */ static final int TRACK_MENU = Menu.FIRST; /** Menu item to sort the music list by album title. */ static final int ALBUM_MENU = Menu.FIRST+1; /** Menu item to sort the music list by artist name. */ static final int ARTIST_MENU = Menu.FIRST+2; /** These are the columns in the music cursor that we are interested in. */ static final String[] CURSOR_COLS = new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.TITLE_KEY, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.TRACK }; /** Formatting optimization to avoid creating many temporary objects. */ static StringBuilder sFormatBuilder = new StringBuilder(); /** Formatting optimization to avoid creating many temporary objects. */ static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault()); /** Formatting optimization to avoid creating many temporary objects. */ static final Object[] sTimeArgs = new Object[5]; /** Uri to the directory of all music being displayed. */ Uri mBaseUri; /** This is the adapter used to display all of the tracks. */ TrackListAdapter mAdapter; /** Our instance of QueryHandler used to perform async background queries. */ QueryHandler mQueryHandler; /** Used to keep track of the last scroll state of the list. */ Parcelable mListState = null; /** Used to keep track of whether the list last had focus. */ boolean mListHasFocus; /** The current cursor on the music that is being displayed. */ Cursor mCursor; /** The actual sort order the user has selected. */ int mSortMode = -1; /** SQL order by string describing the currently selected sort order. */ String mSortOrder; /** Container of the in-screen progress indicator, to be able to hide it * when done loading the initial cursor. */ View mProgressContainer; /** Container of the list view hierarchy, to be able to show it when done * loading the initial cursor. */ View mListContainer; /** Set to true when the list view has been shown for the first time. */ boolean mListShown; /** View holding the okay button. */ View mOkayButton; /** View holding the cancel button. */ View mCancelButton; /** Which track row ID the user has last selected. */ long mSelectedId = -1; /** Completel Uri that the user has last selected. */ Uri mSelectedUri; /** If >= 0, we are currently playing a track for preview, and this is its * row ID. */ long mPlayingId = -1; /** This is used for playing previews of the music files. */ MediaPlayer mMediaPlayer; /** * A special implementation of SimpleCursorAdapter that knows how to bind * our cursor data to our list item structure, and takes care of other * advanced features such as indexing and filtering. */ class TrackListAdapter extends SimpleCursorAdapter implements FastScrollView.SectionIndexer { final ListView mListView; private final StringBuilder mBuilder = new StringBuilder(); private final String mUnknownArtist; private final String mUnknownAlbum; private int mIdIdx; private int mTitleIdx; private int mArtistIdx; private int mAlbumIdx; private int mDurationIdx; private int mAudioIdIdx; private int mTrackIdx; private boolean mLoading = true; private String [] mAlphabet; private int mIndexerSortMode; private boolean mIndexerOutOfDate; private AlphabetIndexer mIndexer; class ViewHolder { TextView line1; TextView line2; TextView duration; RadioButton radio; ImageView play_indicator; CharArrayBuffer buffer1; char [] buffer2; } TrackListAdapter(Context context, ListView listView, int layout, String[] from, int[] to) { super(context, layout, null, from, to); mListView = listView; mUnknownArtist = context.getString(R.string.unknownArtistName); mUnknownAlbum = context.getString(R.string.unknownAlbumName); getAlphabet(context); } /** * The mLoading flag is set while we are performing a background * query, to avoid displaying the "No music" empty view during * this time. */ public void setLoading(boolean loading) { mLoading = loading; } @Override public boolean isEmpty() { if (mLoading) { // We don't want the empty state to show when loading. return false; } else { return super.isEmpty(); } } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View v = super.newView(context, cursor, parent); ViewHolder vh = new ViewHolder(); vh.line1 = (TextView) v.findViewById(R.id.line1); vh.line2 = (TextView) v.findViewById(R.id.line2); vh.duration = (TextView) v.findViewById(R.id.duration); vh.radio = (RadioButton) v.findViewById(R.id.radio); vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator); vh.buffer1 = new CharArrayBuffer(100); vh.buffer2 = new char[200]; v.setTag(vh); return v; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder vh = (ViewHolder) view.getTag(); cursor.copyStringToBuffer(mTitleIdx, vh.buffer1); vh.line1.setText(vh.buffer1.data, 0, vh.buffer1.sizeCopied); int secs = cursor.getInt(mDurationIdx) / 1000; if (secs == 0) { vh.duration.setText(""); } else { vh.duration.setText(makeTimeString(context, secs)); } final StringBuilder builder = mBuilder; builder.delete(0, builder.length()); String name = cursor.getString(mAlbumIdx); if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) { builder.append(mUnknownAlbum); } else { builder.append(name); } builder.append('\n'); name = cursor.getString(mArtistIdx); if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) { builder.append(mUnknownArtist); } else { builder.append(name); } int len = builder.length(); if (vh.buffer2.length < len) { vh.buffer2 = new char[len]; } builder.getChars(0, len, vh.buffer2, 0); vh.line2.setText(vh.buffer2, 0, len); // Update the checkbox of the item, based on which the user last // selected. Note that doing it this way means we must have the // list view update all of its items when the selected item // changes. final long id = cursor.getLong(mIdIdx); vh.radio.setChecked(id == mSelectedId); if (DBG) Log.v(TAG, "Binding id=" + id + " sel=" + mSelectedId + " playing=" + mPlayingId + " cursor=" + cursor); // Likewise, display the "now playing" icon if this item is // currently being previewed for the user. ImageView iv = vh.play_indicator; if (id == mPlayingId) { iv.setImageResource(R.drawable.now_playing); iv.setVisibility(View.VISIBLE); } else { iv.setVisibility(View.GONE); } } /** * This method is called whenever we receive a new cursor due to * an async query, and must take care of plugging the new one in * to the adapter. */ @Override public void changeCursor(Cursor cursor) { super.changeCursor(cursor); if (DBG) Log.v(TAG, "Setting cursor to: " + cursor + " from: " + MusicPicker.this.mCursor); MusicPicker.this.mCursor = cursor; if (cursor != null) { // Retrieve indices of the various columns we are interested in. mIdIdx = cursor.getColumnIndex(MediaStore.Audio.Media._ID); mTitleIdx = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE); mArtistIdx = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST); mAlbumIdx = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM); mDurationIdx = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION); int audioIdIdx = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID); if (audioIdIdx < 0) { audioIdIdx = cursor.getColumnIndex(MediaStore.Audio.Media._ID); } mAudioIdIdx = audioIdIdx; mTrackIdx = cursor.getColumnIndex(MediaStore.Audio.Media.TRACK); } // The next time the indexer is needed, we will need to rebind it // to this cursor. mIndexerOutOfDate = true; // Ensure that the list is shown (and initial progress indicator // hidden) in case this is the first cursor we have gotten. makeListShown(); } /** * This method is called from a background thread by the list view * when the user has typed a letter that should result in a filtering * of the displayed items. It returns a Cursor, when will then be * handed to changeCursor. */ @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { if (DBG) Log.v(TAG, "Getting new cursor..."); return doQuery(true, constraint.toString()); } /** * Build a list of alphabetic characters appropriate for the * current locale. */ private void getAlphabet(Context context) { String alphabetString = context.getResources().getString(R.string.alphabet); mAlphabet = new String[alphabetString.length()]; for (int i = 0; i < mAlphabet.length; i++) { mAlphabet[i] = String.valueOf(alphabetString.charAt(i)); } } public int getPositionForSection(int section) { Cursor cursor = getCursor(); if (cursor == null) { // No cursor, the section doesn't exist so just return 0 return 0; } // If the sort mode has changed, or we haven't yet created an // indexer one, then create a new one that is indexing the // appropriate column based on the sort mode. if (mIndexerSortMode != mSortMode || mIndexer == null) { mIndexerSortMode = mSortMode; int idx = mTitleIdx; switch (mIndexerSortMode) { case ARTIST_MENU: idx = mArtistIdx; break; case ALBUM_MENU: idx = mAlbumIdx; break; } mIndexer = new AlphabetIndexer(cursor, idx, mAlphabet); // If we have a valid indexer, but the cursor has changed since // its last use, then point it to the current cursor. } else if (mIndexerOutOfDate) { mIndexer.setCursor(cursor); } mIndexerOutOfDate = false; return mIndexer.indexOf(section); } public int getSectionForPosition(int position) { return 0; } public Object[] getSections() { return mAlphabet; } } /** * This is our specialization of AsyncQueryHandler applies new cursors * to our state as they become available. */ private final class QueryHandler extends AsyncQueryHandler { public QueryHandler(Context context) { super(context.getContentResolver()); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { if (!isFinishing()) { // Update the adapter: we are no longer loading, and have // a new cursor for it. mAdapter.setLoading(false); mAdapter.changeCursor(cursor); setProgressBarIndeterminateVisibility(false); // Now that the cursor is populated again, it's possible to restore the list state if (mListState != null) { getListView().onRestoreInstanceState(mListState); if (mListHasFocus) { getListView().requestFocus(); } mListHasFocus = false; mListState = null; } } else { cursor.close(); } } } public static String makeTimeString(Context context, long secs) { String durationformat = context.getString(R.string.durationformat); /* Provide multiple arguments so the format can be changed easily * by modifying the xml. */ sFormatBuilder.setLength(0); final Object[] timeArgs = sTimeArgs; timeArgs[0] = secs / 3600; timeArgs[1] = secs / 60; timeArgs[2] = (secs / 60) % 60; timeArgs[3] = secs; timeArgs[4] = secs % 60; return sFormatter.format(durationformat, timeArgs).toString(); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setTitle(R.string.musicPickerTitle); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); int sortMode = TRACK_MENU; if (icicle == null) { mSelectedUri = getIntent().getParcelableExtra( RingtoneManager.EXTRA_RINGTONE_EXISTING_URI); } else { mSelectedUri = (Uri)icicle.getParcelable( RingtoneManager.EXTRA_RINGTONE_EXISTING_URI); // Retrieve list state. This will be applied after the // QueryHandler has run mListState = icicle.getParcelable(LIST_STATE_KEY); mListHasFocus = icicle.getBoolean(FOCUS_KEY); sortMode = icicle.getInt(SORT_MODE_KEY, sortMode); } if (Intent.ACTION_GET_CONTENT.equals(getIntent().getAction())) { mBaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } else { mBaseUri = getIntent().getData(); if (mBaseUri == null) { Log.w("MusicPicker", "No data URI given to PICK action"); finish(); return; } } setContentView(R.layout.music_picker); mSortOrder = MediaStore.Audio.Media.TITLE_KEY; final ListView listView = getListView(); listView.setItemsCanFocus(false); mAdapter = new TrackListAdapter(this, listView, R.layout.track_list_item, new String[] {}, new int[] {}); setListAdapter(mAdapter); listView.setTextFilterEnabled(true); // We manually save/restore the listview state listView.setSaveEnabled(false); mQueryHandler = new QueryHandler(this); mProgressContainer = findViewById(R.id.progressContainer); mListContainer = findViewById(R.id.listContainer); mOkayButton = findViewById(R.id.okayButton); mOkayButton.setOnClickListener(this); mCancelButton = findViewById(R.id.cancelButton); mCancelButton.setOnClickListener(this); // If there is a currently selected Uri, then try to determine who // it is. if (mSelectedUri != null) { Uri.Builder builder = mSelectedUri.buildUpon(); String path = mSelectedUri.getEncodedPath(); int idx = path.lastIndexOf('/'); if (idx >= 0) { path = path.substring(0, idx); } builder.encodedPath(path); Uri baseSelectedUri = builder.build(); if (DBG) Log.v(TAG, "Selected Uri: " + mSelectedUri); if (DBG) Log.v(TAG, "Selected base Uri: " + baseSelectedUri); if (DBG) Log.v(TAG, "Base Uri: " + mBaseUri); if (baseSelectedUri.equals(mBaseUri)) { // If the base Uri of the selected Uri is the same as our // content's base Uri, then use the selection! mSelectedId = ContentUris.parseId(mSelectedUri); } } setSortMode(sortMode); } @Override public void onRestart() { super.onRestart(); doQuery(false, null); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (setSortMode(item.getItemId())) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, TRACK_MENU, Menu.NONE, R.string.sortByTrack); menu.add(Menu.NONE, ALBUM_MENU, Menu.NONE, R.string.sortByAlbum); menu.add(Menu.NONE, ARTIST_MENU, Menu.NONE, R.string.sortByArtist); return true; } @Override protected void onSaveInstanceState(Bundle icicle) { super.onSaveInstanceState(icicle); // Save list state in the bundle so we can restore it after the // QueryHandler has run icicle.putParcelable(LIST_STATE_KEY, getListView().onSaveInstanceState()); icicle.putBoolean(FOCUS_KEY, getListView().hasFocus()); icicle.putInt(SORT_MODE_KEY, mSortMode); } @Override public void onPause() { super.onPause(); stopMediaPlayer(); } @Override public void onStop() { super.onStop(); // We don't want the list to display the empty state, since when we // resume it will still be there and show up while the new query is // happening. After the async query finishes in response to onResume() // setLoading(false) will be called. mAdapter.setLoading(true); mAdapter.changeCursor(null); } /** * Changes the current sort order, building the appropriate query string * for the selected order. */ boolean setSortMode(int sortMode) { if (sortMode != mSortMode) { switch (sortMode) { case TRACK_MENU: mSortMode = sortMode; mSortOrder = MediaStore.Audio.Media.TITLE_KEY; doQuery(false, null); return true; case ALBUM_MENU: mSortMode = sortMode; mSortOrder = MediaStore.Audio.Media.ALBUM_KEY + " ASC, " + MediaStore.Audio.Media.TRACK + " ASC, " + MediaStore.Audio.Media.TITLE_KEY + " ASC"; doQuery(false, null); return true; case ARTIST_MENU: mSortMode = sortMode; mSortOrder = MediaStore.Audio.Media.ARTIST_KEY + " ASC, " + MediaStore.Audio.Media.ALBUM_KEY + " ASC, " + MediaStore.Audio.Media.TRACK + " ASC, " + MediaStore.Audio.Media.TITLE_KEY + " ASC"; doQuery(false, null); return true; } } return false; } /** * The first time this is called, we hide the large progress indicator * and show the list view, doing fade animations between them. */ void makeListShown() { if (!mListShown) { mListShown = true; mProgressContainer.startAnimation(AnimationUtils.loadAnimation( this, android.R.anim.fade_out)); mProgressContainer.setVisibility(View.GONE); mListContainer.startAnimation(AnimationUtils.loadAnimation( this, android.R.anim.fade_in)); mListContainer.setVisibility(View.VISIBLE); } } /** * Common method for performing a query of the music database, called for * both top-level queries and filtering. * * @param sync If true, this query should be done synchronously and the * resulting cursor returned. If false, it will be done asynchronously and * null returned. * @param filterstring If non-null, this is a filter to apply to the query. */ Cursor doQuery(boolean sync, String filterstring) { // Cancel any pending queries mQueryHandler.cancelOperation(MY_QUERY_TOKEN); StringBuilder where = new StringBuilder(); where.append(MediaStore.Audio.Media.TITLE + " != ''"); // Add in the filtering constraints String [] keywords = null; if (filterstring != null) { String [] searchWords = filterstring.split(" "); keywords = new String[searchWords.length]; Collator col = Collator.getInstance(); col.setStrength(Collator.PRIMARY); for (int i = 0; i < searchWords.length; i++) { keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%'; } for (int i = 0; i < searchWords.length; i++) { where.append(" AND "); where.append(MediaStore.Audio.Media.ARTIST_KEY + "||"); where.append(MediaStore.Audio.Media.ALBUM_KEY + "||"); where.append(MediaStore.Audio.Media.TITLE_KEY + " LIKE ?"); } } // We want to show all audio files, even recordings. Enforcing the // following condition would hide recordings. //where.append(" AND " + MediaStore.Audio.Media.IS_MUSIC + "=1"); if (sync) { try { return getContentResolver().query(mBaseUri, CURSOR_COLS, where.toString(), keywords, mSortOrder); } catch (UnsupportedOperationException ex) { } } else { mAdapter.setLoading(true); setProgressBarIndeterminateVisibility(true); mQueryHandler.startQuery(MY_QUERY_TOKEN, null, mBaseUri, CURSOR_COLS, where.toString(), keywords, mSortOrder); } return null; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { mCursor.moveToPosition(position); if (DBG) Log.v(TAG, "Click on " + position + " (id=" + id + ", cursid=" + mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID)) + ") in cursor " + mCursor + " adapter=" + l.getAdapter()); setSelected(mCursor); } void setSelected(Cursor c) { Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; long newId = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID)); mSelectedUri = ContentUris.withAppendedId(uri, newId); mSelectedId = newId; if (newId != mPlayingId || mMediaPlayer == null) { stopMediaPlayer(); mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(this, mSelectedUri); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING); mMediaPlayer.prepare(); mMediaPlayer.start(); mPlayingId = newId; getListView().invalidateViews(); } catch (IOException e) { Log.w("MusicPicker", "Unable to play track", e); } } else if (mMediaPlayer != null) { stopMediaPlayer(); getListView().invalidateViews(); } } public void onCompletion(MediaPlayer mp) { if (mMediaPlayer == mp) { mp.stop(); mp.release(); mMediaPlayer = null; mPlayingId = -1; getListView().invalidateViews(); } } void stopMediaPlayer() { if (mMediaPlayer != null) { mMediaPlayer.stop(); mMediaPlayer.release(); mMediaPlayer = null; mPlayingId = -1; } } public void onClick(View v) { switch (v.getId()) { case R.id.okayButton: if (mSelectedId >= 0) { setResult(RESULT_OK, new Intent().setData(mSelectedUri)); finish(); } break; case R.id.cancelButton: finish(); break; } } }
Java
package com.example.android.rings_extended; import android.app.ListActivity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.util.Config; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RadioButton; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * The RingsExtended application, implementing an advanced ringtone picker. * This is a ListActivity display an adapter of dynamic state built by the * activity: at the top are simple options the user can be picked, next an * item to run the built-in ringtone picker, and next are any other activities * that can supply music Uris. */ public class RingsExtended extends ListActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener { static final boolean DBG = false; static final String TAG = "RingsExtended"; /** * Request code when we are launching an activity to handle our same * original Intent, meaning we can propagate its result back to our caller * as-is. */ static final int REQUEST_ORIGINAL = 2; /** * Request code when launching an activity that returns an audio Uri, * meaning we need to translate its result into one that our caller * expects. */ static final int REQUEST_SOUND = 1; Adapter mAdapter; private View mOkayButton; private View mCancelButton; /** Where the silent option item is in the list, or -1 if there is none. */ private int mSilentItemIdx = -1; /** The Uri to play when the 'Default' item is clicked. */ private Uri mUriForDefaultItem; /** Where the default option item is in the list, or -1 if there is none. */ private int mDefaultItemIdx = -1; /** The Uri to place a checkmark next to. */ private Uri mExistingUri; /** Where the existing option item is in the list. */ private int mExistingItemIdx; /** Currently selected options in the radio buttons, if any. */ private long mSelectedItem = -1; /** Loaded ringtone for the existing URI. */ private Ringtone mExistingRingtone; /** Id of option that is currently playing. */ private long mPlayingId = -1; /** Used for playing previews of ring tones. */ private MediaPlayer mMediaPlayer; /** * Information about one static item in the list. This is used for items * that are added and handled manually, which don't have an Intent * associated with them. */ final static class ItemInfo { final CharSequence name; final CharSequence subtitle; final Drawable icon; ItemInfo(CharSequence _name, CharSequence _subtitle, Drawable _icon) { name = _name; subtitle = _subtitle; icon = _icon; } } /** * Our special adapter implementation, merging the various kinds of items * that we will display into one list. There are two sections to the * list of items: * (1) First are any fixed items as described by ItemInfo objects. * (2) Next are any activities that do the same thing as our own. * (3) Finally are any activities that can execute a different Intent. */ private final class Adapter extends BaseAdapter { private final List<ItemInfo> mInitialItems; private final Intent mIntent; private final Intent mOrigIntent; private final LayoutInflater mInflater; private List<ResolveInfo> mList; private int mRealListStart = 0; class ViewHolder { ImageView icon; RadioButton radio; TextView textSingle; TextView textDouble1; TextView textDouble2; ImageView more; } /** * Create a new adapter with the items to be displayed. * * @param context The Context we are running in. * @param initialItems A fixed set of items that appear at the * top of the list. * @param origIntent The original Intent that was used to launch this * activity, used to find all activities that can do the same thing. * @param excludeOrigIntent Our component name, to exclude from the * origIntent list since that is what the user is already running! * @param intent An Intent used to query for additional items to * appear in the rest of the list. */ public Adapter(Context context, List<ItemInfo> initialItems, Intent origIntent, ComponentName excludeOrigIntent, Intent intent) { mInitialItems = initialItems; mIntent = new Intent(intent); mIntent.setComponent(null); mIntent.setFlags(0); if (origIntent != null) { mOrigIntent = new Intent(origIntent); mOrigIntent.setComponent(null); mOrigIntent.setFlags(0); } else { mOrigIntent = null; } mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mList = getActivities(context, mIntent, null); if (origIntent != null) { List<ResolveInfo> orig = getActivities(context, mOrigIntent, excludeOrigIntent); if (orig != null && orig.size() > 0) { mRealListStart = orig.size(); orig.addAll(mList); mList = orig; } } } /** * If the position is within the range of initial items, return the * corresponding index into that array. Otherwise return -1. */ public int initialItemForPosition(int position) { if (position >= getIntentStartIndex()) { return -1; } return position; } /** * Returns true if the given position is for one of the * "original intent" items. */ public boolean isOrigIntentPosition(int position) { position -= getIntentStartIndex(); return position >= 0 && position < mRealListStart; } /** * Returns the ResolveInfo corresponding to the given position, or null * if that position is not an Intent item (that is if it is one * of the static list items). */ public ResolveInfo resolveInfoForPosition(int position) { position -= getIntentStartIndex(); if (mList == null || position < 0) { return null; } return mList.get(position); } /** * Returns the Intent corresponding to the given position, or null * if that position is not an Intent item (that is if it is one * of the static list items). */ public Intent intentForPosition(int position) { position -= getIntentStartIndex(); if (mList == null || position < 0) { return null; } Intent intent = new Intent( position >= mRealListStart ? mIntent : mOrigIntent); ActivityInfo ai = mList.get(position).activityInfo; intent.setComponent(new ComponentName( ai.applicationInfo.packageName, ai.name)); return intent; } public int getCount() { return getIntentStartIndex() + (mList != null ? mList.size() : 0); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.list_item, parent, false); ViewHolder vh = new ViewHolder(); vh.icon = (ImageView)view.findViewById(R.id.icon); vh.radio = (RadioButton)view.findViewById(R.id.radio); vh.textSingle = (TextView)view.findViewById(R.id.textSingle); vh.textDouble1 = (TextView)view.findViewById(R.id.textDouble1); vh.textDouble2 = (TextView)view.findViewById(R.id.textDouble2); vh.more = (ImageView)view.findViewById(R.id.more); view.setTag(vh); } else { view = convertView; } int intentStart = getIntentStartIndex(); if (position < intentStart) { bindView(view, position, mInitialItems.get(position)); } else { bindView(view, mList.get(position-intentStart)); } return view; } private final int getIntentStartIndex() { return mInitialItems != null ? mInitialItems.size() : 0; } private final void bindView(View view, ResolveInfo info) { PackageManager pm = getPackageManager(); ViewHolder vh = (ViewHolder)view.getTag(); CharSequence label = info.loadLabel(pm); if (label == null) label = info.activityInfo.name; bindTextViews(vh, label, null); vh.icon.setImageDrawable(info.loadIcon(pm)); vh.icon.setVisibility(View.VISIBLE); vh.radio.setVisibility(View.GONE); vh.more.setImageResource(R.drawable.icon_more); vh.more.setVisibility(View.VISIBLE); } private final void bindTextViews(ViewHolder vh, CharSequence txt1, CharSequence txt2) { if (txt2 == null) { vh.textSingle.setText(txt1); vh.textSingle.setVisibility(View.VISIBLE); vh.textDouble1.setVisibility(View.INVISIBLE); vh.textDouble2.setVisibility(View.INVISIBLE); } else { vh.textDouble1.setText(txt1); vh.textDouble1.setVisibility(View.VISIBLE); vh.textDouble2.setText(txt2); vh.textDouble2.setVisibility(View.VISIBLE); vh.textSingle.setVisibility(View.INVISIBLE); } } private final void bindView(View view, int position, ItemInfo inf) { ViewHolder vh = (ViewHolder)view.getTag(); bindTextViews(vh, inf.name, inf.subtitle); // Set the standard icon and radio button. When the radio button // is displayed, we mark it if this is the currently selected row, // meaning we need to invalidate the view list whenever the // selection changes. if (inf.icon != null) { vh.icon.setImageDrawable(inf.icon); vh.icon.setVisibility(View.VISIBLE); vh.radio.setVisibility(View.GONE); } else { vh.icon.setVisibility(View.GONE); vh.radio.setVisibility(View.VISIBLE); vh.radio.setChecked(position == mSelectedItem); } // Show the "now playing" icon if this item is playing. Doing this // means that we need to invalidate the displayed views when the // playing state changes. if (mPlayingId == position) { vh.more.setImageResource(R.drawable.now_playing); vh.more.setVisibility(View.VISIBLE); } else { vh.more.setVisibility(View.GONE); } } } /** * Retrieve a list of all of the activities that can handle the given Intent, * optionally excluding the explicit component 'exclude'. The returned list * is sorted by the label for reach resolved activity. */ static final List<ResolveInfo> getActivities(Context context, Intent intent, ComponentName exclude) { PackageManager pm = context.getPackageManager(); List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (list != null) { int N = list.size(); if (exclude != null) { for (int i=0; i<N; i++) { ResolveInfo ri = list.get(i); if (ri.activityInfo.packageName.equals(exclude.getPackageName()) || ri.activityInfo.name.equals(exclude.getClassName())) { list.remove(i); N--; } } } if (N > 1) { // Only display the first matches that are either of equal // priority or have asked to be default options. ResolveInfo r0 = list.get(0); for (int i=1; i<N; i++) { ResolveInfo ri = list.get(i); if (Config.LOGV) Log.v( "ResolveListActivity", r0.activityInfo.name + "=" + r0.priority + "/" + r0.isDefault + " vs " + ri.activityInfo.name + "=" + ri.priority + "/" + ri.isDefault); if (r0.priority != ri.priority || r0.isDefault != ri.isDefault) { while (i < N) { list.remove(i); N--; } } } Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm)); } } return list; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.rings_extended); mOkayButton = findViewById(R.id.okayButton); mOkayButton.setOnClickListener(this); mCancelButton = findViewById(R.id.cancelButton); mCancelButton.setOnClickListener(this); Intent intent = getIntent(); /* * Get whether to show the 'Default' item, and the URI to play when the * default is clicked */ mUriForDefaultItem = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI); if (mUriForDefaultItem == null) { mUriForDefaultItem = Settings.System.DEFAULT_RINGTONE_URI; } // Get the URI whose list item should have a checkmark mExistingUri = intent .getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI); // We are now going to build the set of static items. ArrayList<ItemInfo> initialItems = new ArrayList<ItemInfo>(); // If the caller has asked to allow the user to select "silent", then // show an option for that. if (intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true)) { mSilentItemIdx = initialItems.size(); initialItems.add(new ItemInfo(getText(R.string.silentLabel), null, null)); } // If the caller has asked to allow the user to select "default", then // show an option for that. if (intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)) { mDefaultItemIdx = initialItems.size(); Ringtone defRing = RingtoneManager.getRingtone(this, mUriForDefaultItem); initialItems.add(new ItemInfo(getText(R.string.defaultRingtoneLabel), defRing.getTitle(this), null)); } // If the caller has supplied a currently selected Uri, then show an // open for keeping that. if (mExistingUri != null) { mExistingRingtone = RingtoneManager.getRingtone(this, mExistingUri); mExistingItemIdx = initialItems.size(); initialItems.add(new ItemInfo(getText(R.string.existingRingtoneLabel), mExistingRingtone.getTitle(this), null)); } if (DBG) { Log.v(TAG, "default=" + mUriForDefaultItem); Log.v(TAG, "existing=" + mExistingUri); } // Figure out which of the static items should start out with its // radio button checked. if (mExistingUri == null) { if (mSilentItemIdx >= 0) { mSelectedItem = mSilentItemIdx; } } else if (mDefaultItemIdx >= 0 && mExistingUri.equals(mUriForDefaultItem)) { mSelectedItem = mDefaultItemIdx; } else { mSelectedItem = mExistingItemIdx; } if (mSelectedItem >= 0) { mOkayButton.setEnabled(true); } mAdapter = new Adapter(this, initialItems, getIntent(), getComponentName(), new Intent(Intent.ACTION_GET_CONTENT).setType("audio/mp3") .addCategory(Intent.CATEGORY_OPENABLE)); this.setListAdapter(mAdapter); } @Override public void onPause() { super.onPause(); stopMediaPlayer(); } public void onCompletion(MediaPlayer mp) { if (mMediaPlayer == mp) { mp.stop(); mp.release(); mMediaPlayer = null; mPlayingId = -1; getListView().invalidateViews(); } } private void stopMediaPlayer() { if (mMediaPlayer != null) { mMediaPlayer.stop(); mMediaPlayer.release(); mMediaPlayer = null; mPlayingId = -1; } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { int initialItem = mAdapter.initialItemForPosition((int)id); if (initialItem >= 0) { // If the selected item is from our static list, then take // care of handling it. mSelectedItem = initialItem; Uri uri = getSelectedUri(); // If a new item has been selected, then play it for the user. if (uri != null && (id != mPlayingId || mMediaPlayer == null)) { stopMediaPlayer(); mMediaPlayer = new MediaPlayer(); try { if (DBG) Log.v(TAG, "Playing: " + uri); mMediaPlayer.setDataSource(this, uri); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING); mMediaPlayer.prepare(); mMediaPlayer.start(); mPlayingId = id; getListView().invalidateViews(); } catch (IOException e) { Log.w("MusicPicker", "Unable to play track", e); } // Otherwise stop any currently playing item. } else if (mMediaPlayer != null) { stopMediaPlayer(); getListView().invalidateViews(); } getListView().invalidateViews(); mOkayButton.setEnabled(true); } else if (mAdapter.isOrigIntentPosition((int)id)) { // If the item is one of the original intent activities, then // launch it with the result code to simply propagate its result // back to our caller. Intent intent = mAdapter.intentForPosition((int)id); startActivityForResult(intent, REQUEST_ORIGINAL); } else { // If the item is one of the music retrieval activities, then launch // it with the result code to transform its result into our caller's // expected result. Intent intent = mAdapter.intentForPosition((int)id); intent.putExtras(getIntent()); startActivityForResult(intent, REQUEST_SOUND); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_SOUND && resultCode == RESULT_OK) { Intent resultIntent = new Intent(); Uri uri = data != null ? data.getData() : null; resultIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, uri); setResult(RESULT_OK, resultIntent); finish(); } else if (requestCode == REQUEST_ORIGINAL && resultCode == RESULT_OK) { setResult(RESULT_OK, data); finish(); } } public void onClick(View v) { switch (v.getId()) { case R.id.okayButton: Intent resultIntent = new Intent(); Uri uri = getSelectedUri(); resultIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, uri); setResult(RESULT_OK, resultIntent); finish(); break; case R.id.cancelButton: finish(); break; } } private Uri getSelectedUri() { if (mSelectedItem == mSilentItemIdx) { // The null uri is silent. return null; } else if (mSelectedItem == mDefaultItemIdx) { return mUriForDefaultItem; } else if (mSelectedItem == mExistingItemIdx) { return mExistingUri; } return null; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.example.android.rings_extended; import android.database.Cursor; import android.database.DataSetObserver; import android.util.SparseIntArray; /** * This class essentially helps in building an index of section boundaries of a * sorted column of a cursor. For instance, if a cursor contains a data set * sorted by first name of a person or the title of a song, this class will * perform a binary search to identify the first row that begins with a * particular letter. The search is case-insensitive. The class caches the index * such that subsequent queries for the same letter will return right away. * * <p>This file was copied from the Contacts application. In the future it * should be provided as a standard part of the Android framework. */ public class AlphabetIndexer extends DataSetObserver { protected Cursor mDataCursor; protected int mColumnIndex; protected Object[] mAlphabetArray; private SparseIntArray mAlphaMap; private java.text.Collator mCollator; /** * Constructs the indexer. * @param cursor the cursor containing the data set * @param columnIndex the column number in the cursor that is sorted * alphabetically * @param sections the array of objects that represent the sections. The * toString() method of each item is called and the first letter of the * String is used as the letter to search for. */ public AlphabetIndexer(Cursor cursor, int columnIndex, Object[] sections) { mDataCursor = cursor; mColumnIndex = columnIndex; mAlphabetArray = sections; mAlphaMap = new SparseIntArray(26 /* Optimize for English */); if (cursor != null) { cursor.registerDataSetObserver(this); } // Get a Collator for the current locale for string comparisons. mCollator = java.text.Collator.getInstance(); mCollator.setStrength(java.text.Collator.PRIMARY); } /** * Sets a new cursor as the data set and resets the cache of indices. * @param cursor the new cursor to use as the data set */ public void setCursor(Cursor cursor) { if (mDataCursor != null) { mDataCursor.unregisterDataSetObserver(this); } mDataCursor = cursor; if (cursor != null) { mDataCursor.registerDataSetObserver(this); } mAlphaMap.clear(); } /** * Performs a binary search or cache lookup to find the first row that * matches a given section's starting letter. * @param sectionIndex the section to search for * @return the row index of the first occurrence, or the nearest next letter. * For instance, if searching for "T" and no "T" is found, then the first * row starting with "U" or any higher letter is returned. If there is no * data following "T" at all, then the list size is returned. */ public int indexOf(int sectionIndex) { final SparseIntArray alphaMap = mAlphaMap; final Cursor cursor = mDataCursor; if (cursor == null || mAlphabetArray == null) { return 0; } // Check bounds if (sectionIndex <= 0) { return 0; } if (sectionIndex >= mAlphabetArray.length) { sectionIndex = mAlphabetArray.length - 1; } int savedCursorPos = cursor.getPosition(); int count = cursor.getCount(); int start = 0; int end = count; int pos; String letter = mAlphabetArray[sectionIndex].toString(); letter = letter.toUpperCase(); int key = letter.charAt(0); // Check map if (Integer.MIN_VALUE != (pos = alphaMap.get(key, Integer.MIN_VALUE))) { // Is it approximate? Using negative value to indicate that it's // an approximation and positive value when it is the accurate // position. if (pos < 0) { pos = -pos; end = pos; } else { // Not approximate, this is the confirmed start of section, return it return pos; } } // Do we have the position of the previous section? if (sectionIndex > 0) { int prevLetter = mAlphabetArray[sectionIndex - 1].toString().charAt(0); int prevLetterPos = alphaMap.get(prevLetter, Integer.MIN_VALUE); if (prevLetterPos != Integer.MIN_VALUE) { start = Math.abs(prevLetterPos); } } // Now that we have a possibly optimized start and end, let's binary search pos = (end + start) / 2; while (pos < end) { // Get letter at pos cursor.moveToPosition(pos); String curName = cursor.getString(mColumnIndex); if (curName == null) { if (pos == 0) { break; } else { pos--; continue; } } int curLetter = Character.toUpperCase(curName.charAt(0)); if (curLetter != key) { // Enter approximation in hash if a better solution doesn't exist int curPos = alphaMap.get(curLetter, Integer.MIN_VALUE); if (curPos == Integer.MIN_VALUE || Math.abs(curPos) > pos) { // Negative pos indicates that it is an approximation alphaMap.put(curLetter, -pos); } if (mCollator.compare(curName, letter) < 0) { start = pos + 1; if (start >= count) { pos = count; break; } } else { end = pos; } } else { // They're the same, but that doesn't mean it's the start if (start == pos) { // This is it break; } else { // Need to go further lower to find the starting row end = pos; } } pos = (start + end) / 2; } alphaMap.put(key, pos); cursor.moveToPosition(savedCursorPos); return pos; } @Override public void onChanged() { super.onChanged(); mAlphaMap.clear(); } @Override public void onInvalidated() { super.onInvalidated(); mAlphaMap.clear(); } }
Java