code
stringlengths
3
1.18M
language
stringclasses
1 value
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * Drupal Editor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.utils; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; /** * {@link BaseAdapter}-Implementation for the {@link MultiChoice} Dialog. * * @author christian * @param <T> * Type this Adapter contains. Should have some useful toString() * implementation. */ public class MultiChoiceListAdapter<T> extends BaseAdapter { private Context ctx; private Collection<T> options; private Collection<T> selection; private List<T> filteredOptions; public MultiChoiceListAdapter(Context context, Collection<T> options, Collection<T> selection) { this.ctx = context; this.options = options; this.selection = selection; this.filteredOptions = new ArrayList<T>(options.size()); setFilter(null); } @Override public int getCount() { return filteredOptions.size(); } @Override public T getItem(int position) { return filteredOptions.get(position); } @Override public long getItemId(int position) { return position; } @Override @SuppressWarnings("unchecked") public View getView(int position, View convertView, ViewGroup parent) { ChoiceView view; T item = getItem(position); boolean selected = selection.contains(item); if (convertView == null) { view = new ChoiceView(ctx, item, selected); } else { view = (ChoiceView) convertView; view.setItem(item, selected); } return view; } public void setFilter(String filter) { if (filter != null) filter = filter.toLowerCase(Locale.getDefault()); filteredOptions.clear(); for (T item : selection) filteredOptions.add(item); for (T item : options) if (!selection.contains(item) && (filter == null || item.toString() .toLowerCase(Locale.getDefault()).contains(filter))) filteredOptions.add(item); } public class ChoiceView extends CheckBox implements OnCheckedChangeListener { private T object; public ChoiceView(Context context, T object, Boolean selected) { super(context); this.object = object; setOnCheckedChangeListener(this); setItem(object, selected); final float scale = context.getResources().getDisplayMetrics().density; int pixels = (int) (48 * scale); setHeight(pixels); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (selection != null) { if (isChecked && !selection.contains(object)) selection.add(object); else if (!isChecked) selection.remove(object); } notifyDataSetChanged(); } public void setItem(T object, Boolean selected) { this.object = object; setChecked(selected); setText(object.toString()); } } }
Java
/** * Copyright (C) 2010 Christian Meyer * This file is part of Drupal Editor. * * Drupal Editor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * Drupal Editor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.utils; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; /** * A dialog that allows the user to select multiple entries. * * @author christian * @param <T> * Type for this dialog. Should have some useful toString() * implementation. */ public class MultiChoice<T> extends Dialog { private ListView listView; private Map<T, Boolean> optionsWithSelection; private Collection<T> options; private Collection<T> selection; public MultiChoice(Context context, Collection<T> options, Collection<T> selection) { super(context); this.options = options; this.selection = selection; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Context ctx = getContext(); LinearLayout layout = new LinearLayout(ctx); layout.setOrientation(LinearLayout.VERTICAL); listView = new ListView(ctx); final MultiChoiceListAdapter<T> adapter; adapter = new MultiChoiceListAdapter<T>(ctx, options, selection); listView.setAdapter(adapter); if (options.size() > 10) { EditText search = new EditText(ctx); search.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER); search.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.setFilter(s.toString()); adapter.notifyDataSetChanged(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); layout.addView(search); } layout.addView(listView); setContentView(layout); } public Map<T, Boolean> getOptionsMap() { return optionsWithSelection; } public Set<T> getSelection() { Set<T> result = new LinkedHashSet<T>(); for (Entry<T, Boolean> e : optionsWithSelection.entrySet()) if (Boolean.TRUE.equals(e.getValue())) result.add(e.getKey()); return result; } }
Java
/** * Copyright (C) 2010 christian * This file is part of Drupal Editor. * * Drupal Editor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * Drupal Editor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Drupal Editor. If not, see <http://www.gnu.org/licenses/>. */ package ch.dissem.android.utils; import android.app.Activity; import android.content.Context; import android.os.Handler; import android.widget.Toast; /** * @author christian * */ public class ThreadingUtils { public static void showToast(Handler handler, final Context context, final int resId, final int duration) { handler.post(new Runnable() { public void run() { Toast.makeText(context, resId, duration).show(); } }); } public static void startProgress(Handler handler, final Activity activity) { handler.post(new Runnable() { public void run() { activity.setProgressBarIndeterminateVisibility(true); } }); } public static void stopProgress(Handler handler, final Activity activity) { handler.post(new Runnable() { public void run() { activity.setProgressBarIndeterminateVisibility(false); } }); } }
Java
/** * */ package distance; /** * @author Josh Clemm * */ public interface Distance { public int getDistance(Object object1, Object object2); }
Java
package distance; /** * http://en.wikipedia.org/wiki/Levenshtein_distance */ public class LevenshteinDistance implements Distance { @Override public int getDistance(Object object1, Object object2) { String string1 = (String) object1; String string2 = (String) object2; int distance[][]; // distance matrix int n; // length of first string int m; // length of second string int i; // iterates through first string int j; // iterates through second string char s_i; // ith character of first string char t_j; // jth character of second string int cost; // cost // Step 1 n = string1.length(); m = string2.length(); if (n == 0) return m; if (m == 0) return n; distance = new int[n+1][m+1]; // Step 2 for (i = 0; i <= n; i++) distance[i][0] = i; for (j = 0; j <= m; j++) distance[0][j] = j; // Step 3 for (i = 1; i <= n; i++) { s_i = string1.charAt (i - 1); // Step 4 for (j = 1; j <= m; j++) { t_j = string2.charAt(j - 1); // Step 5 if (s_i == t_j) cost = 0; else cost = 1; // Step 6 distance[i][j] = findMinimum(distance[i-1][j]+1, distance[i][j-1]+1, distance[i-1][j-1] + cost); } } // Step 7 return distance[n][m]; } private int findMinimum(int a, int b, int c) { int min = a; if (b < min) { min = b; } if (c < min) { min = c; } return min; } }
Java
package bktree; import java.io.IOException; import java.util.HashMap; import distance.LevenshteinDistance; public class TestBKTree { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { String[] wordList = new String[] { "remote", "barn", "book", "glass", "chair", "closet", "skull", "giraffe", "boat", "soda" }; BKTree<String> bkTree = new BKTree<String>(new LevenshteinDistance()); for (String word : wordList) { bkTree.add(word); } HashMap<String, Integer> queryMap = bkTree.query("bark", 2); System.out.println(queryMap); String searchTerm = "temotw"; System.out.println("Best match for search '"+searchTerm+"' = "+bkTree.findBestWordMatchWithDistance(searchTerm)); searchTerm = "garage"; System.out.println("Best match for search '"+searchTerm+"' = "+bkTree.findBestWordMatchWithDistance(searchTerm)); } }
Java
package bktree; import java.util.HashMap; import distance.Distance; /** * This class in an implementation of a Burkhard-Keller tree in Java. * The BK-Tree is a tree structure to quickly finding close matches to * any defined object. * * The BK-Tree was first described in the paper: * "Some Approaches to Best-Match File Searching" by W. A. Burkhard and R. M. Keller * It is available in the ACM archives. * * Another good explanation can be found here: * http://blog.notdot.net/2007/4/Damn-Cool-Algorithms-Part-1-BK-Trees * * Searching the tree yields O(logn), which is a huge upgrade over brute force * * @author Josh Clemm * */ public class BKTree <E> { private Node root; private HashMap<E, Integer> matches; private Distance distance; private E bestTerm; public BKTree(Distance distance) { root = null; this.distance = distance; } public void add(E term) { if(root != null) { root.add(term); } else { root = new Node(term); } } /** * This method will find all the close matching Objects within * a certain threshold. For instance, for search for similar * strings, threshold set to 1 will return all the strings that * are off by 1 edit distance. * @param searchObject * @param threshold * @return */ public HashMap<E, Integer> query(E searchObject, int threshold) { matches = new HashMap<E,Integer>(); root.query(searchObject, threshold, matches); return matches; } /** * Attempts to find the closest match to the search term. * @param term * @return the edit distance of the best match */ public int find(E term) { return root.findBestMatch(term, Integer.MAX_VALUE); } /** * Attempts to find the closest match to the search term. * @param term * @return a match that is within the best edit distance of the search term. */ public E findBestWordMatch(E term) { root.findBestMatch(term, Integer.MAX_VALUE); return root.getBestTerm(); } /** * Attempts to find the closest match to the search term. * @param term * @return a match that is within the best edit distance of the search term. */ public HashMap<E,Integer> findBestWordMatchWithDistance(E term) { int distance = root.findBestMatch(term, Integer.MAX_VALUE); HashMap<E, Integer> returnMap = new HashMap<E, Integer>(); returnMap.put(root.getBestTerm(), distance); return returnMap; } private class Node { E term; HashMap<Integer, Node> children; public Node(E term) { this.term = term; children = new HashMap<Integer, Node>(); } public void add(E term) { int score = distance.getDistance(term, this.term); Node child = children.get(score); if(child != null) { child.add(term); } else { children.put(score, new Node(term)); } } public int findBestMatch(E term, int bestDistance) { int distanceAtNode = distance.getDistance(term, this.term); // System.out.println("term = " + term + ", this.term = " + this.term + ", distance = " + distanceAtNode); // if(distanceAtNode == 1) { // return distanceAtNode; // } if(distanceAtNode < bestDistance) { bestDistance = distanceAtNode; bestTerm = this.term; } int possibleBest = bestDistance; for (Integer score : children.keySet()) { if(score < distanceAtNode + bestDistance ) { possibleBest = children.get(score).findBestMatch(term, bestDistance); if(possibleBest < bestDistance) { bestDistance = possibleBest; } } } return bestDistance; } public E getBestTerm() { return bestTerm; } public void query(E term, int threshold, HashMap<E, Integer> collected) { int distanceAtNode = distance.getDistance(term, this.term); if(distanceAtNode == threshold) { collected.put(this.term, distanceAtNode); return; } if(distanceAtNode < threshold) { collected.put(this.term, distanceAtNode); } for (int score = distanceAtNode-threshold; score <= threshold+distanceAtNode; score++) { Node child = children.get(score); if(child != null) { child.query(term, threshold, collected); } } } } }
Java
package com.test; import android.app.Activity; import android.os.Bundle; public class TxappcActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.main); } }
Java
package cn.anlab.anappframe.service; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import cn.anlab.anappframe.R; import cn.anlab.anappframe.demo.activity.ChatDemoActivity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; public class CoreService extends Service { @Override public IBinder onBind(Intent intent) { Log.i("anlog", "onBind..."); return null; } @Override public void onCreate() { Log.i("anlog", "onCreate..."); super.onCreate(); } @Override public void onStart(Intent intent, int startId) { Log.i("anlog", "onStart..."); super.onStart(intent, startId); ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); executorService.scheduleAtFixedRate(task, 1, 20, TimeUnit.SECONDS); } @Override public void onDestroy() { Log.i("anlog", "onDestroy..."); super.onDestroy(); } private Runnable task = new Runnable() { @Override public void run() { handler.sendEmptyMessage(100); } }; private Handler handler = new Handler(){ public void handleMessage(Message msg) { Log.i("anlog", new Date().toString()); //设置通知显示 int icon = R.drawable.app_icon; String text = "移动互联网开发框架"; //通知到时,在手机顶部显示的该字, long when = System.currentTimeMillis(); //通知行显示的时间 Notification notification = new Notification(icon, text, when); //设置通知点击事件 String contentTitle = "开发框架"; //通知行的标题 String contentText = "你有新消息!"; //通知行的内容 Intent intent = new Intent(CoreService.this, ChatDemoActivity.class); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //PendingIntent参数说明: //FLAG_UPDATE_CURRENT 下次通知来时,能更新通知行的内容 //FLAG_ONE_SHOT同一消息只使用一次,再次点击时,没响应了 // PendingIntent contentIntent = PendingIntent.getActivity(CoreService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT ); notification.setLatestEventInfo(CoreService.this, contentTitle, contentText, contentIntent); //发送通知 NotificationManager notificationMng = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); notificationMng.notify(2002, notification); }; }; }
Java
package cn.anlab.anappframe; import java.util.Locale; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.Toast; import cn.anlab.anappframe.system.CoreApplication; import cn.anlab.anappframe.system.Event; import cn.anlab.anappframe.widget.CompProgressDialog; public class BaseActivity extends Activity { private CompProgressDialog loadingDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); interest(errorHandler, Event.EXCEPTION); } /** * 注册当前页面(Activity)感兴趣的事件 * @param handler 捕获事件下由handler来处理 * @param event * @see Event */ protected void interest(Handler handler, int ... events) { for(int e : events) { CoreApplication.registerHandler(e, handler); } } /** * 显示加载中圆圈 */ protected void showLoading() { if(loadingDialog == null) { loadingDialog = new CompProgressDialog(this); } if(!loadingDialog.isShowing()) { loadingDialog.show(); } } /** * 隐藏加载中圆圈 */ protected void hideLoading() { if(loadingDialog != null) { loadingDialog.dismiss(); } } /** * 统一错误处理,用于所有页面 */ private Handler errorHandler = new Handler() { public void handleMessage(Message msg) { hideLoading(); Toast.makeText(BaseActivity.this, "aaaa", Toast.LENGTH_SHORT).show(); }; }; }
Java
package cn.anlab.anappframe.net.sub; import java.io.IOException; import java.nio.channels.SelectionKey; public interface INIOHandler { public void processConnect(SelectionKey sk) throws IOException; public void processRead(SelectionKey sk) throws IOException; public void processWrite() throws IOException; public void processError(Exception e); }
Java
package cn.anlab.anappframe.net.sub; import java.nio.ByteBuffer; public class InPacket extends Packet { public InPacket(ByteBuffer receiveBuf) { super.body = receiveBuf.array(); } }
Java
package cn.anlab.anappframe.net.sub; import java.io.IOException; /** * 连接监听 * * @version 1.0 * @author Stan Rong 2012-3-6 */ public interface ConnectionListener { // onConnect, onDisconnect, onData /** * 连接时触发 * @return * @throws IOException */ public boolean onConnect() throws IOException; /** * 断开连接时触发 * @return * @throws IOException */ public boolean onDisconnect() throws IOException; /** * 连接超时时触发 * @return * @throws IOException */ public boolean onConnectionTimeout() throws IOException; public boolean onIdleTimeout() throws IOException; public boolean onData() throws IOException; }
Java
package cn.anlab.anappframe.net.sub; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import android.util.Log; public class AsyncRequest { private static ThreadPoolExecutor threadPool; private InetSocketAddress address; public AsyncRequest(InetSocketAddress address) { this.address = address; } public void setConNumPerNIOThread(int count) { } public void setBody(byte[] body) { } public void startAsyn(int id) { try { TCPConnection conn= new TCPConnection("0", address); threadPool.submit(conn); } catch (IOException e) { e.printStackTrace(); } // Selector selector = Selector.open(); // channel.register(selector, SelectionKey.OP_CONNECT); // int n = 0; // try { // if(selector != null) // n = selector.select(3000); // // 如果要shutdown,关闭selector退出 // if (shutdown) { // selector.close(); // break; // } // } catch (IOException e) { // dispatchErrorToAll(e); // } // // 如果select返回大于0,处理事件 // if(n > 0) { // for (Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext();) { // // 得到下一个Key // SelectionKey sk = i.next(); // i.remove(); // // 检查其是否还有效 // if(!sk.isValid()) // continue; // // // 处理 // INIOHandler handler = (INIOHandler)sk.attachment(); // try { // if(sk.isConnectable()) // { // handler.processConnect(sk); // } // else if (sk.isReadable()) // { // handler.processRead(sk); // } // } catch (IOException e) { // handler.processError(e); // } catch (RuntimeException e) { // } // } // n = 0; // } // checkNewConnection(); // notifySend(); } public boolean isCurrRequestFull() { return false; } public void setUDP(boolean b) { } public static synchronized ThreadPoolExecutor setThreadPoolNum(int aThreadPoolMinNum, int aThreadPoolMaxNum, long keepAliveTime) { if (threadPool == null) { threadPool = new ThreadPoolExecutor(aThreadPoolMinNum, aThreadPoolMaxNum, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadPoolExecutor.DiscardOldestPolicy()); } return threadPool; } public static void main(String[] args) { AsyncRequest request = new AsyncRequest(new InetSocketAddress("10.0.2.2", 8042)); try { request.setConNumPerNIOThread(5); AsyncRequest.setThreadPoolNum(2, 5, 2); request.setUDP(false); request.setBody("hello world".getBytes()); request.startAsyn(0); if (!request.isCurrRequestFull()) { request.setBody("My name is dongfengsun".getBytes()); request.startAsyn(1); } } catch (Exception e) { Log.e("onCreate", " = " + e.getMessage()); e.printStackTrace(); } } }
Java
package cn.anlab.anappframe.net.sub; import java.io.IOException; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.nio.channels.UnresolvedAddressException; import android.util.Log; public class TCPConnection extends ConnectionImp { /** 用于通信的channel */ private final SocketChannel channel; /** * true表示远程已经关闭了这个连接 */ private boolean remoteClosed; /** * 构造一个连接到指定地址的TCPPort. * * @param address * 连接到的地址. * @throws IOException * 端口打开/端口配置/连接到地址出错. */ public TCPConnection(String id, InetSocketAddress address) throws IOException { super(id); channel = SocketChannel.open(); channel.configureBlocking(false); this.remoteAddress = address; remoteClosed = false; } public void start() { try { channel.connect(remoteAddress); } catch (UnknownHostException e) { processError(new Exception("Unknown Host")); } catch (UnresolvedAddressException e) { processError(new Exception("Unable to resolve server address")); } catch (IOException e) { processError(e); } } public SelectableChannel channel() { return channel; } public void receive() throws IOException { if (remoteClosed) return; // 接收数据 int oldPos = receiveBuf.position(); for (int r = channel.read(receiveBuf); r > 0; r = channel.read(receiveBuf)) ; byte[] tempBuffer = new byte[1024]; receiveBuf.get(tempBuffer, 0, receiveBuf.position()); Log.e("receive", " = " + new String(tempBuffer, "UTF-8")); // 得到当前位置 int pos = receiveBuf.position(); receiveBuf.flip(); // 检查是否读了0字节,这种情况一般表示远程已经关闭了这个连接 if (oldPos == pos) { remoteClosed = true; return; } InPacket packet = new InPacket(receiveBuf); inQueue.add(packet); adjustBuffer(pos); } private void adjustBuffer(int pos) { // 如果0不等于当前pos,说明至少分析了一个包 if (receiveBuf.position() > 0) { receiveBuf.compact(); receiveBuf.limit(receiveBuf.capacity()); } else { receiveBuf.limit(receiveBuf.capacity()); receiveBuf.position(pos); } } public void send() throws IOException { while (!isEmpty()) { sendBuf.clear(); OutPacket packet = remove(); channel.write(ByteBuffer.wrap(packet.getBody())); // 添加到重发队列 // packet.setTimeout(System.currentTimeMillis() + EnginConst.QQ_TIMEOUT_SEND); Log.e("debug", "have sended packet - " + packet.toString()); } } public void send(OutPacket packet) { try { sendBuf.clear(); channel.write(ByteBuffer.wrap(packet.getBody())); Log.d("debug", "have sended packet - " + packet.toString()); } catch (Exception e) { } } public void send(ByteBuffer buffer) { try { channel.write(buffer); } catch (IOException e) { } } public void dispose() { try { channel.close(); } catch (IOException e) { } } public boolean isConnected() { return channel != null && channel.isConnected(); } public void processConnect(SelectionKey sk) throws IOException { // 完成SocketChannel的连接 channel.finishConnect(); while (!channel.isConnected()) { try { Thread.sleep(300); } catch (InterruptedException e) { } channel.finishConnect(); } sk.interestOps(SelectionKey.OP_READ); Log.e("debug", "hava connected to server"); } public void processRead(SelectionKey sk) throws IOException { receive(); } public void processWrite() throws IOException { if (isConnected()) send(); } }
Java
package cn.anlab.anappframe.net.sub; import java.io.UnsupportedEncodingException; import org.json.JSONException; import org.json.JSONObject; import android.app.Application; import android.content.Context; /** * 响应分发器 * * @version 1.0 * @author Stan Rong 2012-3-6 */ public class ResponseDispatcher implements IDataHandler { private static final String DEFAULT_CHARSET_NAME = "UTF-8"; private static final String CMD_KEY = "cmd"; private static final String DATA_KEY = "data"; private String charsetName; public ResponseDispatcher() { this.charsetName = DEFAULT_CHARSET_NAME; } public ResponseDispatcher(String charsetName) { this.charsetName = charsetName; } @Override public void onDataReceived(byte[] bytes) { //转换成字符串 String content; try { content = new String(bytes, charsetName); } catch (UnsupportedEncodingException e) { content = ""; e.printStackTrace(); } //解析成JSON try { JSONObject json = new JSONObject(content); String cmd = json.getString(CMD_KEY); JSONObject data = json.getJSONObject(DATA_KEY); dispatchResponse(cmd, json); } catch (JSONException e) { e.printStackTrace(); } } /** * 分发响应 * @param cmd * @param json */ private void dispatchResponse(String cmd, JSONObject json) { } }
Java
package cn.anlab.anappframe.net.sub; public interface IDataHandler { /** * 接收到数据的处理 * @param bytes */ void onDataReceived(byte[] bytes); }
Java
package cn.anlab.anappframe.net.sub; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public abstract class ConnectionImp implements IConnection, INIOHandler, Runnable { private String id; protected InetSocketAddress remoteAddress; protected ByteBuffer receiveBuf; protected ByteBuffer sendBuf; protected Queue<InPacket> inQueue; protected Queue<OutPacket> outQueue; public ConnectionImp(String id) { this.id = id; this.receiveBuf = ByteBuffer.allocate(1024); this.sendBuf = ByteBuffer.allocate(1024); inQueue = new LinkedList<InPacket>(); } @Override public void add(OutPacket out) { outQueue.add(out); } @Override public void clearSendQueue() { inQueue.clear(); } @Override public String getId() { return id; } @Override public InetSocketAddress getRemoteAddress() { return remoteAddress; } @Override public INIOHandler getNIOHandler() { // TODO Auto-generated method stub return null; } @Override public boolean isEmpty() { // TODO Auto-generated method stub return false; } public void processError(Exception e) { // TODO ==== } public OutPacket remove() { // TODO ==== return null; } @Override public void run() { start(); } public void checkNewConnection() { //TODO === } public void notifySend() { //TODO === } public void dispatchErrorToAll(Exception e) { //TODO === } }
Java
package cn.anlab.anappframe.net.sub; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Queue; import android.util.Log; /** * 客户端连接类 * * @version 1.0 * @author Stan Rong 2012-3-2 */ public class NIOClient implements IClient, Runnable { private String address; private int port; private static Selector selector; private static final int PREFIX_BUFFER_LENGTH = 4; //报文前缀的长度 private SocketChannel channel; private IDataHandler dataHandler; public NIOClient(String address, int port) { this.address = address; this.port = port; } /** * 连接 * @throws IOException */ public void connect() throws IOException { // 开启selector,并建立socket到指定端口的连接 if (selector == null) selector = Selector.open(); channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(new InetSocketAddress(address, port)); channel.register(selector, SelectionKey.OP_CONNECT); // 进行信息读取 for (;;) { selector.select(); Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); keyIterator.remove(); // 连接事件 if (key.isConnectable()) { Log.d("anlog", "key.isConnectable()"); SocketChannel socketChannel = (SocketChannel) key.channel(); if (socketChannel.isConnectionPending()) socketChannel.finishConnect(); // socketChannel.write(ByteBuffer.wrap("aaabbb".getBytes())); //连接成功,发送认证信息 socketChannel.register(selector, SelectionKey.OP_READ); } // 读事件 if (key.isReadable()) { Log.d("anlog", "key.isReadable()"); SocketChannel socketChannel = (SocketChannel) key.channel(); if (!socketChannel.isConnected()) { Log.e("anlog", "!socketChannel.isConnected()"); //TODO } //获取报文的长度 ByteBuffer prefixBuff = ByteBuffer.allocate(PREFIX_BUFFER_LENGTH); int readSize0 = socketChannel.read(prefixBuff); if (readSize0 < PREFIX_BUFFER_LENGTH) { key.cancel(); } prefixBuff.flip(); int length = prefixBuff.asIntBuffer().get(); prefixBuff.clear(); //读取报文正文内容 ByteBuffer byteBuffer = ByteBuffer.allocate(length); int readSize = socketChannel.read(byteBuffer); if(readSize != length) { System.out.println("报文长度不对!"); //TODO } //处理响应 byteBuffer.flip(); byte[] bytes = byteBuffer.array(); dataHandler.onDataReceived(bytes); byteBuffer.clear(); } } } } /** * 断开连接 * @throws IOException */ public void disconnect() throws IOException { if(channel != null) { channel.close(); channel = null; } } /** * 判断是否已经连接 * @return */ public boolean isConnected() { if(channel != null) { return channel.isConnected(); } return false; } /** * 发送数据 */ public void send(byte[] bytes) throws IOException { int length = 4 + bytes.length; ByteBuffer buff = ByteBuffer.allocate(length); buff.putInt(length); buff.put(bytes); buff.flip(); channel.write(buff); } @Override public void run() { try { connect(); } catch (IOException e) { e.printStackTrace(); } } public void setDataHandler(IDataHandler dataHandler) { this.dataHandler = dataHandler; } public void setAddress(String address) { this.address = address; } public void setPort(int port) { this.port = port; } }
Java
package cn.anlab.anappframe.net.sub; import java.io.IOException; /** * * * @version 1.0 * @author Stan Rong 2012-3-3 */ public interface IClient { /** * 连接 * @throws IOException */ public void connect() throws IOException; /** * 断开连接 * @throws IOException */ public void disconnect() throws IOException; /** * 发送数据 * @param data * @throws IOException */ public void send(byte[] data) throws IOException; /** * 设置数据处理器 * @param dataHandler */ public void setDataHandler(IDataHandler dataHandler); /** * 设置服务端地址 * @param address */ public void setAddress(String address) ; /** * 设置服务端端口 * @param port */ public void setPort(int port); }
Java
package cn.anlab.anappframe.net.sub; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; public interface IConnection { /** * 添加一个包到发送队列 * @param out */ public void add(OutPacket out); public void clearSendQueue(); public void start(); public String getId(); public void dispose(); public InetSocketAddress getRemoteAddress(); public SelectableChannel channel(); public INIOHandler getNIOHandler(); public boolean isEmpty(); public void receive() throws IOException; public void send() throws IOException; public void send(ByteBuffer buffer); public boolean isConnected(); }
Java
package cn.anlab.anappframe.net.sub; public class OutPacket extends Packet { }
Java
package cn.anlab.anappframe.net.sub; import java.nio.ByteBuffer; public class Packet { protected int cmd; protected int rc; protected byte[] body; public int getCmd() { return cmd; } public void setCmd(int cmd) { this.cmd = cmd; } public int getRc() { return rc; } public void setRc(int rc) { this.rc = rc; } public byte[] getBody() { return body; } public void setBody(byte[] body) { this.body = body; } }
Java
package cn.anlab.anappframe.net.sub2; import org.json.JSONException; import org.json.JSONObject; public class InPacket extends Packet { public InPacket(int cmd, int rc, byte[] body) { super.cmd = cmd; super.rc = rc; super.body = body; } public String getContent() { String content = new String(body); return content; } public JSONObject getJson() throws JSONException { JSONObject json = new JSONObject(getContent()); return json; } }
Java
package cn.anlab.anappframe.net.sub2; public interface ReqCallback { public void onReceive(InPacket inPacket); }
Java
package cn.anlab.anappframe.net.sub2; import java.io.IOException; import java.net.InetSocketAddress; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.json.JSONException; import org.json.JSONObject; public class AsyncRequest { private static ExecutorService es; private static IConnection conn; private InetSocketAddress address; private Map<Integer, ReqCallback> callbackMap; public AsyncRequest(InetSocketAddress address) { this.address = address; this.callbackMap = new ConcurrentHashMap<Integer, ReqCallback>(); if(es == null) { es = Executors.newSingleThreadExecutor(); } if(conn == null || !conn.isConnected()) { conn = new TCPConnection(address, handler); } conn.setHandler(handler); es.submit(new Runnable() { @Override public void run() { try { conn.connect(); } catch (IOException e) { handler.onError(e); } } }); } /** * 发送包 * @param outPacket */ public void send(OutPacket outPacket, ReqCallback callback) { if(!conn.isConnected()) { try { conn.connect(); } catch (IOException e) { handler.onError(e); } } byte[] data = outPacket.getAllBytes(); try { callbackMap.put(outPacket.getRc(), callback); conn.send(data); } catch (IOException e) { handler.onError(e); } } private void receive(InPacket inPacket) { Integer rc = inPacket.getRc(); if( !callbackMap.containsKey(rc)) { System.out.println("no response."); return; } ReqCallback callback = callbackMap.get(rc); callback.onReceive(inPacket); } private IHandler handler = new IHandler() { @Override public boolean onReceive(byte[] data) throws IOException { String content = new String(data); InPacket inPacket = null; try { JSONObject json = new JSONObject(content); int cmd = json.getInt("cmd"); int rc = json.getInt("rc"); Object obj = json.get("data"); byte[] body = obj.toString().getBytes(); inPacket = new InPacket(cmd, rc, body); } catch (JSONException e) { handler.onError(e); } receive(inPacket); return true; } @Override public boolean onError(Exception e) { e.printStackTrace(); return false; } @Override public boolean onDisconnect() throws IOException { return false; } @Override public boolean onConnect() throws IOException { return false; } }; }
Java
package cn.anlab.anappframe.net.sub2; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import android.util.Log; public class TCPConnection implements IConnection { private static final int PREFIX_BUFFER_LENGTH = 4; //报文前缀的长度 private InetSocketAddress address; private IHandler handler; private Selector selector; private SocketChannel channel; public TCPConnection(InetSocketAddress address, IHandler handler) { this.address = address; } @Override public void connect() throws IOException { channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(address); if (selector == null || ! selector.isOpen()) { selector = Selector.open(); } channel.register(selector, SelectionKey.OP_CONNECT); for (;;) { selector.select(); Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); keyIterator.remove(); // 连接事件 if (key.isConnectable()) { Log.d("anlog", "key.isConnectable()"); SocketChannel socketChannel = (SocketChannel) key.channel(); if (socketChannel.isConnectionPending()) socketChannel.finishConnect(); socketChannel.register(selector, SelectionKey.OP_READ); } //读事件 if (key.isReadable()) { receive(key); } } } } @Override public void disconnect() throws IOException { if(channel != null) { channel.close(); channel = null; } } /** * 判断是否已经连接 * @return */ public boolean isConnected() { if(channel != null) { return channel.isConnected(); } return false; } @Override public void send(byte[] data) throws IOException { if(isConnected()) { int length = PREFIX_BUFFER_LENGTH + data.length; ByteBuffer buff = ByteBuffer.allocate(length); buff.putInt(data.length); buff.put(data); buff.flip(); channel.write(buff); buff.clear(); } } public void receive(SelectionKey key) throws IOException { Log.d("anlog", "key.isReadable()"); SocketChannel socketChannel = (SocketChannel) key.channel(); //获取报文的长度 ByteBuffer prefixBuff = ByteBuffer.allocate(PREFIX_BUFFER_LENGTH); int readSize0 = socketChannel.read(prefixBuff); if (readSize0 < PREFIX_BUFFER_LENGTH) { key.cancel(); } prefixBuff.flip(); int length = prefixBuff.asIntBuffer().get(); prefixBuff.clear(); //读取报文正文内容 ByteBuffer byteBuffer = ByteBuffer.allocate(length); int readSize = socketChannel.read(byteBuffer); if(readSize != length) { System.out.println("报文长度不对!"); handler.onError(new RuntimeException("Read size is not right.")); } //处理响应 byteBuffer.flip(); byte[] bytes = byteBuffer.array(); handler.onReceive(bytes); byteBuffer.clear(); } @Override public void setHandler(IHandler handler) { this.handler = handler; } @Override public void setAddress(InetSocketAddress address) { this.address = address; } }
Java
package cn.anlab.anappframe.net.sub2; import java.io.IOException; import java.nio.channels.SelectionKey; /** * * @version 1.0 * @author Stan Rong 2012-3-7 */ public interface IHandler { public boolean onReceive(byte[] data) throws IOException; public boolean onConnect() throws IOException; public boolean onDisconnect() throws IOException; public boolean onError(Exception e); }
Java
package cn.anlab.anappframe.net.sub2; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.json.JSONException; import org.json.JSONObject; import android.os.Handler; public class Controller { private static ExecutorService es; private static IConnection conn; private InetSocketAddress address; private Map<Integer, ReqCallback> callbackMap; private static Controller controller; public synchronized static Controller getInstance() { if(controller == null) { controller = new Controller(null); //FIXME } return controller; } public Controller(InetSocketAddress address) { this.address = address; this.callbackMap = new ConcurrentHashMap<Integer, ReqCallback>(); if(es == null) { es = Executors.newSingleThreadExecutor(); } if(conn == null || !conn.isConnected()) { conn = new TCPConnection(address, handler); } conn.setHandler(handler); es.submit(new Runnable() { @Override public void run() { try { conn.connect(); } catch (IOException e) { handler.onError(e); } } }); } // /** // * // * @param inter // * @param method // * @param params // * @param handler // */ // public void process(Class inter, String method, Map params, Handler handler) { // // } /** * 发送包 * @param outPacket */ public void send(OutPacket outPacket, ReqCallback callback) { if(!conn.isConnected()) { try { conn.connect(); } catch (IOException e) { handler.onError(e); } } byte[] data = outPacket.getAllBytes(); try { callbackMap.put(outPacket.getRc(), callback); conn.send(data); } catch (IOException e) { handler.onError(e); } } private void receive(InPacket inPacket) { Integer rc = inPacket.getRc(); if( !callbackMap.containsKey(rc)) { System.out.println("no response."); return; } ReqCallback callback = callbackMap.get(rc); callback.onReceive(inPacket); } private IHandler handler = new IHandler() { @Override public boolean onReceive(byte[] data) throws IOException { String content = new String(data); InPacket inPacket = null; try { JSONObject json = new JSONObject(content); int cmd = json.getInt("cmd"); int rc = json.getInt("rc"); Object obj = json.get("data"); byte[] body = obj.toString().getBytes(); inPacket = new InPacket(cmd, rc, body); } catch (JSONException e) { handler.onError(e); } receive(inPacket); return true; } @Override public boolean onError(Exception e) { e.printStackTrace(); return false; } @Override public boolean onDisconnect() throws IOException { return false; } @Override public boolean onConnect() throws IOException { return false; } }; public static void main(String[] args) { InetSocketAddress address = new InetSocketAddress("192.168.8.66", 7100); Controller req = new Controller(address); OutPacket op = new OutPacket(1, 2, "HelloWorld"); ReqCallback callback = new ReqCallback() { @Override public void onReceive(InPacket inPacket) { String content = inPacket.getContent(); System.out.println("receive content : " + content); } }; req.send(op, callback); } }
Java
package cn.anlab.anappframe.net.sub2; import java.io.IOException; import java.net.InetSocketAddress; public interface IConnection { /** * 连接 * @throws IOException */ public void connect() throws IOException; /** * 断开连接 * @throws IOException */ public void disconnect() throws IOException; /** * 判断是否已经连接 * @return */ public boolean isConnected(); /** * 发送数据 * @param data * @throws IOException */ public void send(byte[] data) throws IOException; /** * 设置处理器 * @param handler */ public void setHandler(IHandler handler) ; /** * 设置服务端地址 * @param address */ public void setAddress(InetSocketAddress address) ; }
Java
package cn.anlab.anappframe.net.sub2; import java.nio.ByteBuffer; import org.json.JSONObject; public class OutPacket extends Packet { public OutPacket(int cmd, int rc, byte[] body) { super.cmd = cmd; super.rc = rc; super.body = body; } public OutPacket(int cmd, int rc, String content) { super.cmd = cmd; super.rc = rc; super.body = content.getBytes(); } public OutPacket(int cmd, int rc, JSONObject json) { super.cmd = cmd; super.rc = rc; super.body = json.toString().getBytes(); } /** * {cmd:2,rc:3,data:?} * @return */ public byte[] getAllBytes() { StringBuffer sb = new StringBuffer(); sb.append("{cmd:").append(cmd).append(",rc:").append(rc).append(",data:"); byte[] bytes1 = sb.toString().getBytes(); byte[] bytes2 = body; byte[] bytes3 = "}".getBytes(); int length = bytes1.length + bytes2.length + bytes3.length; ByteBuffer buff = ByteBuffer.allocate(length); buff.put(bytes1); buff.put(bytes2); buff.put(bytes3); buff.flip(); return buff.array(); } }
Java
package cn.anlab.anappframe.net.sub2; public class Packet { protected int cmd; protected int rc; protected byte[] body; public int getCmd() { return cmd; } public void setCmd(int cmd) { this.cmd = cmd; } public int getRc() { return rc; } public void setRc(int rc) { this.rc = rc; } public byte[] getBody() { return body; } public void setBody(byte[] body) { this.body = body; } }
Java
package cn.anlab.anappframe.system; /** * 服务端推送事件 * * @version 1.0 * @author Stan Rong 2012-3-9 */ public class Event { /** * 发生异常时 */ public static final int EXCEPTION = 20120001; /** * 检测到软件有更新 */ public static final int CHECK_APK_UPDATE = 20120010; /** * 接收到聊天消息 */ public static final int RECEIVE_CHAT_MESSAGE = 20120011; /** * 接收到邮件 */ public static final int RECEIVE_MAIL_MESSAGE = 20120012; }
Java
package cn.anlab.anappframe.system; import java.lang.ref.SoftReference; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.app.ActivityManager; import android.app.Application; import android.content.res.Configuration; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.WindowManager; import android.widget.ListView; import android.widget.Toast; import cn.anlab.anappframe.BaseActivity; import cn.anlab.anappframe.R; import cn.anlab.anappframe.net.IClient; import cn.anlab.anappframe.net.IOClient; import cn.anlab.anappframe.net.IOErrorListener; import cn.anlab.anappframe.net.JsonIOHandler; import cn.anlab.anappframe.net.Packet; import cn.anlab.anappframe.net.ReceiveCallback; public class CoreApplication extends Application { private static final String tag = "anlog"; public static CoreApplication application; private static String hostname = "192.168.1.100"; // 192.168.8.66 private static int port = 8899; private static int THREAD_POOL_SIZE = 3; private IClient<Packet> conn; /** * key为感兴趣的命令(接收到的cmd), value为回调处理的handler */ private ConcurrentMap<Integer, Set<Handler>> handlerMap; /** * 接口类软件引用,key为类名, value为Object对象 */ public SoftReference<Map<String, Object>> interObjMapRef; public ExecutorService asyncRunTaskPool; /** * Channel */ public int currentChannel; public static IClient<Packet> getConnection() { return application.conn; } public static Map<String, Object>getInterObjMap() { return application.interObjMapRef.get(); } public static ExecutorService getAsyncRunTaskPool() { return application.asyncRunTaskPool; } @Override public void onCreate() { super.onCreate(); Log.d("anlog", "CoreApplication.onCreate()"); application = this; // 客户端接收到服务端数据的处理handler集 handlerMap = new ConcurrentHashMap<Integer, Set<Handler>>(); // 接口对象类软件引用 Map<String, Object> interObjMap = new HashMap<String, Object>(); interObjMapRef = new SoftReference<Map<String, Object>>(interObjMap); // 异步任务线程池 asyncRunTaskPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE); // registerHandler(Event.EXCEPTION, appHandler); java.lang.System.setProperty("java.net.preferIPv4Stack", "true"); java.lang.System.setProperty("java.net.preferIPv6Addresses", "false"); } /** * 初始化网络连接 */ public static void initNetConnection() { application.conn = new IOClient<Packet>(); application.conn.setProtocolHandler(new JsonIOHandler()); application.conn.setIoErrorListener(application.ioErrorListener); application.conn.setReceiveCallback(application.receiveCallback); application.conn.connect(hostname, port); } /** * 向远程服务器发送数据 * @param cmd * @param data */ public static void sendRemote(int cmd, Object data) { if( ! application.conn.isConnected()) { application.conn.connect(hostname, port); } Packet p = new Packet(cmd, data); application.conn.send(p); } /** * 切换通道 * @see R.array.channels */ public static void changeChannel(String channelCode) { // 国际化 Locale locale = new Locale(channelCode); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; application.getBaseContext().getResources().updateConfiguration(config, null); } private Handler appHandler = new Handler() { public void handleMessage(Message msg) { Toast.makeText(CoreApplication.this, "[e]" + msg.obj, Toast.LENGTH_SHORT).show(); }; }; /** * 注册Handler <br /> * 服务端发来数据时,根据interestEvent来选择由哪些handler来处理界面的展示 * * @param interestEvent * @param handler * @see Event */ public static void registerHandler(int interestEvent, Handler handler) { Integer eventKey = new Integer(interestEvent); if (!application.handlerMap.containsKey(eventKey)) { application.handlerMap.put(eventKey, new HashSet<Handler>()); } Set<Handler> handlerSet = application.handlerMap.get(eventKey); if (!handlerSet.contains(handler)) { Log.i(tag, "register event = " + interestEvent + ", handler = " + handler.toString()); handlerSet.add(handler); } } /** * 分发响应 * * @param cmd * 感兴趣的事件,即服务端发过来的cmd命令编码 * @see Event */ private void dispatchResponse(int cmd, Object data) { Set<Handler> handlerSet = handlerMap.get(new Integer(cmd)); if (handlerSet != null && handlerSet.size() > 0) { // 遍历每一个Handler,发消息 for (Handler h : handlerSet) { Message msg = new Message(); msg.what = cmd; msg.obj = data; h.sendMessage(msg); } } else { Log.w(tag, "not found handler with eventKey = " + cmd); } } /** * IO错误监听 */ private IOErrorListener ioErrorListener = new IOErrorListener() { @Override public void onError(int errorCode, Exception e) { if(errorCode == CONNECT_TIMEOUT || errorCode == IO_EXCEPTION) { application.conn.disconnect(); } Log.e(tag, "IOErrorListener.onError = " + e); Message msg = new Message(); msg.what = Event.EXCEPTION; msg.obj = e; appHandler.sendMessage(msg); }; }; /** * 回调处理,监听服务端发来的数据 */ private ReceiveCallback<Packet> receiveCallback = new ReceiveCallback<Packet>() { @Override public void onReceive(InetSocketAddress from, Packet p) { Log.e("CoreApplication", "from : " + from + ", receive : " + p); int cmd = p.getCmd(); Object data = p.getData(); dispatchResponse(cmd, data); } }; @Override public void onTerminate() { super.onTerminate(); Log.d("anlog", "CoreApplication.onTerminate()"); } }
Java
package cn.anlab.anappframe.anim; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation; /** * This ActivitySwitcher uses a 3D rotation to animate an activity during its * start or finish. * * see: http://blog.robert-heim.de/karriere/android-startactivity-rotate-3d-animation-activityswitcher/ * * @author Robert Heim * */ public class ActivitySwitcher { private final static int DURATION = 500; //300 private final static float DEPTH = 800.0f; //400 /* ----------------------------------------------- */ public interface AnimationFinishedListener { /** * Called when the animation is finished. */ public void onAnimationFinished(); } /* ----------------------------------------------- */ public static void animationIn(View container, WindowManager windowManager) { animationIn(container, windowManager, null); } public static void animationIn(View container, WindowManager windowManager, AnimationFinishedListener listener) { apply3DRotation(90, 0, false, container, windowManager, listener); } public static void animationOut(View container, WindowManager windowManager) { animationOut(container, windowManager, null); } public static void animationOut(View container, WindowManager windowManager, AnimationFinishedListener listener) { apply3DRotation(0, -90, true, container, windowManager, listener); } /* ----------------------------------------------- */ private static void apply3DRotation(float fromDegree, float toDegree, boolean reverse, View container, WindowManager windowManager, final AnimationFinishedListener listener) { Display display = windowManager.getDefaultDisplay(); final float centerX = display.getWidth() / 2.0f; final float centerY = display.getHeight() / 2.0f; final Rotate3dAnimation a = new Rotate3dAnimation(fromDegree, toDegree, centerX, centerY, DEPTH, reverse); a.reset(); a.setDuration(DURATION); a.setFillAfter(true); a.setInterpolator(new AccelerateInterpolator()); if (listener != null) { a.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { listener.onAnimationFinished(); } }); } container.clearAnimation(); container.startAnimation(a); } }
Java
package cn.anlab.anappframe.anim; import android.view.animation.Animation; import android.view.animation.Transformation; import android.graphics.Camera; import android.graphics.Matrix; /** * An animation that rotates the view on the Y axis between two specified angles. * This animation also adds a translation on the Z axis (depth) to improve the effect. */ public class Rotate3dAnimation extends Animation { private final float mFromDegrees; private final float mToDegrees; private final float mCenterX; private final float mCenterY; private final float mDepthZ; private final boolean mReverse; private Camera mCamera; /** * Creates a new 3D rotation on the Y axis. The rotation is defined by its * start angle and its end angle. Both angles are in degrees. The rotation * is performed around a center point on the 2D space, definied by a pair * of X and Y coordinates, called centerX and centerY. When the animation * starts, a translation on the Z axis (depth) is performed. The length * of the translation can be specified, as well as whether the translation * should be reversed in time. * * @param fromDegrees the start angle of the 3D rotation * @param toDegrees the end angle of the 3D rotation * @param centerX the X center of the 3D rotation * @param centerY the Y center of the 3D rotation * @param reverse true if the translation should be reversed, false otherwise */ public Rotate3dAnimation(float fromDegrees, float toDegrees, float centerX, float centerY, float depthZ, boolean reverse) { mFromDegrees = fromDegrees; mToDegrees = toDegrees; mCenterX = centerX; mCenterY = centerY; mDepthZ = depthZ; mReverse = reverse; } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); mCamera = new Camera(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { final float fromDegrees = mFromDegrees; float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime); final float centerX = mCenterX; final float centerY = mCenterY; final Camera camera = mCamera; final Matrix matrix = t.getMatrix(); camera.save(); if (mReverse) { camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime); } else { camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime)); } camera.rotateY(degrees); camera.getMatrix(matrix); camera.restore(); matrix.preTranslate(-centerX, -centerY); matrix.postTranslate(centerX, centerY); } }
Java
package cn.anlab.anappframe.anim; import cn.anlab.anappframe.R; public enum Trans { /** * 向左滑动 */ SLIDE_LEFT { public int[] getEnterAndExitAnim() { return new int[] { R.anim.push_left_in, R.anim.push_left_out }; } }, /** * 渐渐出现 */ FADE { public int[] getEnterAndExitAnim() { return new int[] { R.anim.fade_in, R.anim.fade_out }; } }, /** * 从中心点弹出 */ POP_CENTER { public int[] getEnterAndExitAnim() { return new int[] { R.anim.pop_center, R.anim.non_move }; } }, /** * 向中心点收缩 */ SHRINK_CENTER { public int[] getEnterAndExitAnim() { return new int[] { R.anim.non_move, R.anim.shrink_center }; } }; /** * 获取进入的Activity的出现效果和退出的Activity的退出效果 * * @return */ public abstract int[] getEnterAndExitAnim(); }
Java
package cn.anlab.anappframe; import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; public class AnappframeActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
Java
package cn.anlab.anappframe.widget; import cn.anlab.anappframe.R; import android.app.AlertDialog; import android.content.Context; import android.view.Window; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; /** * Loading进度框组件 * * @version 1.0 * @author Stan Rong 2012-3-3 */ public class CompProgressDialog { private Context context; private AlertDialog dialog; private ImageView ivLoading; public CompProgressDialog(Context context) { this.context = context; dialog = new AlertDialog.Builder(context).create(); dialog.show(); Window win = dialog.getWindow(); win.setContentView(R.layout.comp_progress_dialog); dialog.dismiss(); ivLoading = (ImageView)dialog.findViewById(R.id.comp_progress_dialog_loading); } /** * 显示对话框 */ public void show() { dialog.show(); Animation anim = AnimationUtils.loadAnimation(context, R.anim.rotate_loading); ivLoading.startAnimation(anim); } /** * 取消对话框 */ public void dismiss() { dialog.dismiss(); ivLoading.clearAnimation(); } /** * 判断是否正在显示 * @return */ public boolean isShowing() { return dialog.isShowing(); } }
Java
package cn.anlab.anappframe.widget; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import cn.anlab.anappframe.R; /** * 对话框组件 * * @version 1.0 * @author Stan Rong 2012-3-3 */ public class CompDialog { private Context context; private AlertDialog dialog; private View contentView; public static final int BUTTON1 = -1; public static final int BUTTON2 = -2; public static final int BUTTON3 = -3; //按钮及按键事件 private Button[] buttons = {null, null, null}; private DialogInterface.OnClickListener[] buttonClickListeners = {null, null, null}; public CompDialog(Context context) { this.context = context; dialog = new AlertDialog.Builder(context).create(); dialog.show(); Window win = dialog.getWindow(); win.setContentView(R.layout.comp_dialog); dialog.dismiss(); } public CompDialog(Context context, String title) { this(context); setTitle(title); } public CompDialog(Context context, String title, String message) { this(context); setTitle(title); setMessage(message); } public CompDialog(Context context, String title, View contentView) { this(context); setTitle(title); setContentView(contentView); } /** * 设置标题 * @param title */ public void setTitle(String title) { TextView tvTitle = (TextView)dialog.findViewById(R.id.comp_dialog_title); tvTitle.setText(title); } /** * 设置要显示的文本内容 * @param message */ public void setMessage(String message) { TextView tvMessage = (TextView)dialog.findViewById(R.id.comp_dialog_message); tvMessage.setVisibility(View.VISIBLE); tvMessage.setText(message); } /** * 设置内容区域 * @param contentView */ public void setContentView(View contentView) { this.contentView = contentView; LinearLayout center = (LinearLayout)dialog.findViewById(R.id.comp_dialog_center); center.removeAllViews(); center.addView(contentView); } /** * 设置按钮及事件 * @param buttonCode * @param dialogClickListener */ public void setButton(final int buttonCode, final String text, final DialogInterface.OnClickListener dialogClickListener) { Button button = null; switch (buttonCode) { case BUTTON1: button = (Button)dialog.findViewById(R.id.comp_dialog_button1); break; case BUTTON2: button = (Button)dialog.findViewById(R.id.comp_dialog_button2); break; case BUTTON3: button = (Button)dialog.findViewById(R.id.comp_dialog_button3); break; default: throw new IllegalArgumentException("方法setButton(int,DialogInterface.OnClickListener)的第1个参数,只支持BUTTON1, BUTTON2, BUTTON3."); } button.setText(text); button.setVisibility(View.VISIBLE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialogClickListener.onClick(dialog, buttonCode); } }); } /** * 显示对话框 */ public void show() { dialog.show(); } /** * 取消对话框 */ public void dismiss() { dialog.dismiss(); } }
Java
package cn.anlab.anappframe.widget; import java.util.List; import java.util.Map; import android.content.Context; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import cn.anlab.anappframe.demo.adapter.ListViewAdapter; /** * 列表选择对话框 * * @version 1.0 * @author Stan Rong 2012-3-3 */ public class CompListDialog extends CompDialog { private ListView listView; private ListViewAdapter adapter; public CompListDialog(Context context, List<Map<String, String>> dataList, String textKey) { super(context); listView = new ListView(context); adapter = new ListViewAdapter(context, dataList, textKey); listView.setOnItemClickListener(rowClickListener); } private AdapterView.OnItemClickListener rowClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { List<Map<String, String>> dataList = adapter.getDataList(); } }; }
Java
package cn.anlab.anappframe.widget; import android.content.Context; /** * 简单文本显示对话框 * * @version 1.0 * @author Stan Rong 2012-3-3 */ public class CompMessageDialog extends CompDialog { public CompMessageDialog(Context context) { super(context); } }
Java
package cn.anlab.anappframe.widget; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.View.MeasureSpec; import android.widget.LinearLayout; import android.widget.Scroller; /** * 可左右滚动的布局 * */ public class HorizonalScrollLayout extends LinearLayout { /** * 通过Handler将滑屏结果通知使用该滑屏控件的Activity<br> * 必须先调用<br> * <code>public void setHandler(Handler handler) </code><br> * 来设置handler.返回的消息为:<br> * <code> * Message msg = new Message();<br> msg.what = ON_SCROLL_CHANGED_MESSAGE_WHAT;<br> msg.arg1 = whichScreen;//滑到的目标屏幕索引(0为第一个屏幕)<br> handler.sendMessage(msg);<br> * * </code> */ public static final int ON_SCROLL_CHANGED_MESSAGE_WHAT = 2087; private static final String TAG = "HorizonalScrollLayout"; private Scroller mScroller; private VelocityTracker mVelocityTracker; private int mCurScreen; private int mDefaultScreen = 0; private static final int TOUCH_STATE_REST = 0; private static final int TOUCH_STATE_SCROLLING = 1; private static final int SNAP_VELOCITY = 600; private int mTouchState = TOUCH_STATE_REST; private int mTouchSlop; private float mLastMotionX; private float mLastMotionY; Handler handler; public HorizonalScrollLayout(Context context, AttributeSet attrs) { super(context, attrs); mScroller = new Scroller(context); mCurScreen = mDefaultScreen; mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childLeft = 0; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View childView = getChildAt(i); if (childView.getVisibility() != View.GONE) { final int childWidth = childView.getMeasuredWidth(); childView.layout(childLeft, 0, childLeft + childWidth, childView.getMeasuredHeight()); childLeft += childWidth; } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int width = MeasureSpec.getSize(widthMeasureSpec); final int widthMode = MeasureSpec.getMode(widthMeasureSpec); if (widthMode != MeasureSpec.EXACTLY) { throw new IllegalStateException("ScrollLayout only canmCurScreen run at EXACTLY mode!"); } final int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode != MeasureSpec.EXACTLY) { throw new IllegalStateException("ScrollLayout only can run at EXACTLY mode!"); } // The children are given the same width and height as the scrollLayout final int count = getChildCount(); for (int i = 0; i < count; i++) { getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec); } // Log.e(TAG, "moving to screen "+mCurScreen); scrollTo(mCurScreen * width, 0); } /** * According to the position of current layout scroll to the destination * page. */ public void snapToDestination() { final int screenWidth = getWidth(); final int destScreen = (getScrollX() + screenWidth / 2) / screenWidth; snapToScreen(destScreen); } public void snapToScreen(int whichScreen) { // get the valid layout page whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1)); if (getScrollX() != (whichScreen * getWidth())) { final int delta = whichScreen * getWidth() - getScrollX(); mScroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta)); mCurScreen = whichScreen; invalidate(); // Redraw the layout } if (handler != null) { Message msg = new Message(); msg.what = ON_SCROLL_CHANGED_MESSAGE_WHAT; msg.arg1 = whichScreen; handler.sendMessage(msg); } } public void setToScreen(int whichScreen) { whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1)); mCurScreen = whichScreen; scrollTo(whichScreen * getWidth(), 0); invalidate(); } public int getCurScreen() { return mCurScreen; } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); postInvalidate(); } } @Override public boolean onTouchEvent(MotionEvent event) { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(event); final int action = event.getAction(); final float x = event.getX(); final float y = event.getY(); switch (action) { case MotionEvent.ACTION_DOWN: // Log.e(TAG, "event down!"); if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mLastMotionX = x; break; case MotionEvent.ACTION_MOVE: int deltaX = (int) (mLastMotionX - x); mLastMotionX = x; scrollBy(deltaX, 0); break; case MotionEvent.ACTION_UP: // Log.e(TAG, "event : up"); // if (mTouchState == TOUCH_STATE_SCROLLING) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000); int velocityX = (int) velocityTracker.getXVelocity(); // Log.e(TAG, "velocityX:" + velocityX); if (velocityX > SNAP_VELOCITY && mCurScreen > 0) { // Fling enough to move left // Log.e(TAG, "snap left"); snapToScreen(mCurScreen - 1); } else if (velocityX < -SNAP_VELOCITY && mCurScreen < getChildCount() - 1) { // Fling enough to move right // Log.e(TAG, "snap right"); snapToScreen(mCurScreen + 1); } else { snapToDestination(); } if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } // } mTouchState = TOUCH_STATE_REST; break; case MotionEvent.ACTION_CANCEL: mTouchState = TOUCH_STATE_REST; break; } return true; } public void setHandler(Handler handler) { this.handler = handler; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { // Log.e(TAG, "onInterceptTouchEvent-slop:" + mTouchSlop); final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) { return true; } final float x = ev.getX(); final float y = ev.getY(); switch (action) { case MotionEvent.ACTION_MOVE: /* * 如果内部的子视图有ScrollView,当用户在ScrollView上下滑动的时候,判断如果Y轴变化值大于X轴变化的1 * .2倍,就不要消费这个事件了 否则会导致用户本来是想上下滑动ScrollView 结果这个滑动事件被本视图吸收了,变为左右滑动 */ int deltaX = (int) (mLastMotionX - x); int deltaY = (int) (mLastMotionY - y); if (Math.abs(deltaY) > Math.abs(deltaX * 1.2)) { return false; } /* * ========================================= */ final int xDiff = (int) Math.abs(mLastMotionX - x); if (xDiff > mTouchSlop) { mTouchState = TOUCH_STATE_SCROLLING; } break; case MotionEvent.ACTION_DOWN: mLastMotionX = x; mLastMotionY = y; mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING; break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: mTouchState = TOUCH_STATE_REST; break; } return mTouchState != TOUCH_STATE_REST; } }
Java
package cn.anlab.anappframe.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import cn.anlab.anappframe.R; /** * Tab页 * @author rongxinhua * */ public class CompTabGroup extends LinearLayout { private Context context; private OnTabClickListener onTabClickListener; private String[] tabTexts; private int defaultSelectedIndex; private LayoutInflater inflater; public CompTabGroup(Context context) { super(context); } public CompTabGroup(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); setOrientation(HORIZONTAL); setGravity(Gravity.CENTER); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CompTabGroup); //Tab显示文本数组 int tabTextsResId = a.getResourceId(R.styleable.CompTabGroup_tabTexts, 0); if(tabTextsResId != 0) { tabTexts = getResources().getStringArray(tabTextsResId); } defaultSelectedIndex = a.getInt(R.styleable.CompTabGroup_defaultSelectedIndex, 0); //加载Tab布局 for(int i = 0; i < tabTexts.length; i ++ ) { LinearLayout.LayoutParams prm = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); View view = inflater.inflate(R.layout.comp_tabgroup_tab, null); // Drawable d = getResources().getDrawable(R.drawable.tab_bg); Drawable d = getResources().getDrawable(R.drawable.aaa); Bitmap bitmap = ((BitmapDrawable)d).getBitmap(); Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas c = new Canvas(output); Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); RectF rectF = new RectF(rect); Paint paint = new Paint(); c.drawRoundRect(rectF, 0, 10, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); c.drawBitmap(bitmap, rect, rect, paint); BitmapDrawable bd = new BitmapDrawable(output); Drawable drawable = (Drawable)bd; view.setBackgroundDrawable(drawable); // /** // * 获得圆角图片 // * @param bitmap // * @param roundPx // * @return // */ // public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) { // Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); // Canvas canvas = new Canvas(output); // final Paint paint = new Paint(); // final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); // final RectF rectF = new RectF(rect); // canvas.drawRoundRect(rectF, roundPx, roundPx, paint); // paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); // canvas.drawBitmap(bitmap, rect, rect, paint); // return output; // } TextView tv = (TextView) view.findViewById(R.id.textView1); tv.setText(tabTexts[i]); addView(view, prm); } } interface OnTabClickListener { public void onTabClick(View tab, int tabIndex); } }
Java
package cn.anlab.anappframe.widget; import cn.anlab.anappframe.R; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.AbsListView; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; /** * 数据列表组件 <br/> * 在原有的基础上,增加头行滚动分页、底部点击按钮分页的支持 * * @version 1.0 * @author Stan Rong 2012-3-3 */ public class CompListView extends ListView { private Context context; /** * 属性:头行滚动加载 */ public static final int PROP_HEADER_LOADING =1 << 0; /** * 属性:底部点击MORE按钮加载 */ public static final int PROP_FOOTER_LOADING =1 << 1; //头部状态 public static final int HEADER_STATE_GONE = 1; //隐藏状态 public static final int HEADER_STATE_TO_RELEASE = 2; //等待释放状态 public static final int HEADER_STATE_LOADING = 3; //加载中状态 public static final int FOOTER_STATE_GONE = 1; //隐藏状态 public static final int FOOTER_STATE_MORE_BUTTON = 2; //更多按钮状态 public static final int FOOTER_STATE_LOADING = 3; //加载中状态 private int properties = 0; LinearLayout headerView; //头行(加载中) LinearLayout footerView; //尾行(查看更多) /** * 构造方法 * @param context * @param properties 属性,如CompListView.PROP_HEADER_LOADING | CompListView.PROP_FOOTER_LOADING */ public CompListView(Context context, int properties) { super(context); this.context = context; this.properties = properties; setHeaderAndFooter(); } public CompListView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CompListView); setHeaderAndFooter(); } // TypedArray a = context.obtainStyledAttributes(attrs, // R.styleable.MyView); // // int textColor = a.getColor(R.styleable.MyView_textColor, // 0XFFFFFFFF); // float textSize = a.getDimension(R.styleable.MyView_textSize, 36); // // mPaint.setTextSize(textSize); // mPaint.setColor(textColor); // // a.recycle(); // /** * 设置头行和尾行视图 */ private void setHeaderAndFooter() { if(hasProperty(PROP_HEADER_LOADING)) { addHeaderView(); } if(hasProperty(PROP_FOOTER_LOADING)) { addFooterView(); } } /** * 显示、隐藏头行 */ public void setHeaderState(int state) { if( ! hasProperty(PROP_HEADER_LOADING)) { throw new RuntimeException("Make sure you have set the property PROP_HEADER_LOADING."); } switch (state) { case HEADER_STATE_GONE: headerView.setVisibility(View.GONE); setItemHeight(footerView, 0); break; case HEADER_STATE_TO_RELEASE: headerView.setVisibility(View.VISIBLE); setItemHeight(footerView, 45); ivLoading.setImageDrawable(getResources().getDrawable(R.drawable.up)); tvLoading.setText("release to load..."); break; case HEADER_STATE_LOADING: headerView.setVisibility(View.VISIBLE); setItemHeight(footerView, 30); ivLoading.setImageDrawable(getResources().getDrawable(R.drawable.loading_small1)); tvLoading.setText("loading..."); break; } } /** * 显示、隐藏尾行 */ public void setFooterState(int state) { if( ! hasProperty(PROP_FOOTER_LOADING)) { throw new RuntimeException("Make sure you have set the property PROP_FOOTER_LOADING."); } switch (state) { case FOOTER_STATE_GONE: footerView.setVisibility(View.GONE); setItemHeight(footerView, 0); break; case FOOTER_STATE_MORE_BUTTON: footerView.setVisibility(View.VISIBLE); setItemHeight(footerView, AbsListView.LayoutParams.WRAP_CONTENT); btnMore.setText("MORE"); break; case FOOTER_STATE_LOADING: footerView.setVisibility(View.VISIBLE); setItemHeight(footerView, AbsListView.LayoutParams.WRAP_CONTENT); btnMore.setText("loading..."); break; } } private void setItemHeight(View iView, int height) { AbsListView.LayoutParams iViewPrm = (AbsListView.LayoutParams)iView.getLayoutParams(); if(iViewPrm == null) { iViewPrm = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, AbsListView.LayoutParams.WRAP_CONTENT); } else { iViewPrm.height = AbsListView.LayoutParams.WRAP_CONTENT; } } /** * 添加ListView头行:加载中的图标及文字描述 */ private void addHeaderView() { headerView = new LinearLayout(context); headerView.setGravity(Gravity.CENTER); // headerView.setPadding(0, 3, 0, 3); headerView.setVisibility(View.GONE); //加载中图标 ivLoading = new ImageView(context); ivLoading.setImageResource(R.drawable.loading_small1); LinearLayout.LayoutParams prm = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); headerView.addView(ivLoading, prm); //加载中文字描述 tvLoading = new TextView(context); tvLoading.setText("Loading..."); prm = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); headerView.addView(tvLoading, prm); AbsListView.LayoutParams itemPrm = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, 0); headerView.setLayoutParams(itemPrm); //添加到ListView头行 addHeaderView(headerView); } private TextView tvLoading; private ImageView ivLoading; /** * 添加ListView尾行:加载底部 */ private void addFooterView() { footerView = new LinearLayout(context); footerView.setGravity(Gravity.CENTER); footerView.setVisibility(View.GONE); //加载按钮 btnMore = new Button(context); btnMore.setText("More..."); btnMore.setBackgroundResource(R.drawable.btn_default); LinearLayout.LayoutParams prm = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); footerView.addView(btnMore, prm); //添加到ListView头行 addFooterView(footerView); } private Button btnMore; /** * 判断当前ListView是否具备某属性 * @param property * @return */ public boolean hasProperty(int property) { if((properties & property) == property) { return true; } else { return false; } } }
Java
package cn.anlab.anappframe.widget; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import cn.anlab.anappframe.R; public class PullToRefreshListView extends ListView implements OnScrollListener { private static final int TAP_TO_REFRESH = 1; private static final int PULL_TO_REFRESH = 2; private static final int RELEASE_TO_REFRESH = 3; private static final int REFRESHING = 4; private static final String TAG = "PullToRefreshListView"; private OnRefreshListener mOnRefreshListener; /** * Listener that will receive notifications every time the list scrolls. */ private OnScrollListener mOnScrollListener; private LayoutInflater mInflater; private RelativeLayout mRefreshView; private TextView mRefreshViewText; private ImageView mRefreshViewImage; private ProgressBar mRefreshViewProgress; private TextView mRefreshViewLastUpdated; private int mCurrentScrollState; private int mRefreshState; private RotateAnimation mFlipAnimation; private RotateAnimation mReverseFlipAnimation; private int mRefreshViewHeight; private int mRefreshOriginalTopPadding; private int mLastMotionY; private boolean mBounceHack; public PullToRefreshListView(Context context) { super(context); init(context); } public PullToRefreshListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public PullToRefreshListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { // Load all of the animations we need in code rather than through XML mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mFlipAnimation.setInterpolator(new LinearInterpolator()); mFlipAnimation.setDuration(250); mFlipAnimation.setFillAfter(true); mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mReverseFlipAnimation.setInterpolator(new LinearInterpolator()); mReverseFlipAnimation.setDuration(250); mReverseFlipAnimation.setFillAfter(true); mInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mRefreshView = (RelativeLayout) mInflater.inflate( R.layout.pull_to_refresh_header, this, false); mRefreshViewText = (TextView) mRefreshView .findViewById(R.id.pull_to_refresh_text); mRefreshViewImage = (ImageView) mRefreshView .findViewById(R.id.pull_to_refresh_image); mRefreshViewProgress = (ProgressBar) mRefreshView .findViewById(R.id.pull_to_refresh_progress); mRefreshViewLastUpdated = (TextView) mRefreshView .findViewById(R.id.pull_to_refresh_updated_at); mRefreshViewImage.setMinimumHeight(50); mRefreshView.setOnClickListener(new OnClickRefreshListener()); mRefreshOriginalTopPadding = mRefreshView.getPaddingTop(); mRefreshState = TAP_TO_REFRESH; addHeaderView(mRefreshView); super.setOnScrollListener(this); measureView(mRefreshView); mRefreshViewHeight = mRefreshView.getMeasuredHeight(); } @Override protected void onAttachedToWindow() { setSelection(1); } @Override public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); setSelection(1); } /** * Set the listener that will receive notifications every time the list * scrolls. * * @param l * The scroll listener. */ @Override public void setOnScrollListener(AbsListView.OnScrollListener l) { mOnScrollListener = l; } /** * Register a callback to be invoked when this list should be refreshed. * * @param onRefreshListener * The callback to run. */ public void setOnRefreshListener(OnRefreshListener onRefreshListener) { mOnRefreshListener = onRefreshListener; } /** * Set a text to represent when the list was last updated. * * @param lastUpdated * Last updated at. */ public void setLastUpdated(CharSequence lastUpdated) { if (lastUpdated != null) { mRefreshViewLastUpdated.setVisibility(View.VISIBLE); mRefreshViewLastUpdated.setText(lastUpdated); } else { mRefreshViewLastUpdated.setVisibility(View.GONE); } } @Override public boolean onTouchEvent(MotionEvent event) { final int y = (int) event.getY(); mBounceHack = false; switch (event.getAction()) { case MotionEvent.ACTION_UP: if (!isVerticalScrollBarEnabled()) { setVerticalScrollBarEnabled(true); } if (getFirstVisiblePosition() == 0 && mRefreshState != REFRESHING) { if ((mRefreshView.getBottom() >= mRefreshViewHeight || mRefreshView .getTop() >= 0) && mRefreshState == RELEASE_TO_REFRESH) { // Initiate the refresh mRefreshState = REFRESHING; prepareForRefresh(); onRefresh(); } else if (mRefreshView.getBottom() < mRefreshViewHeight || mRefreshView.getTop() <= 0) { // Abort refresh and scroll down below the refresh view resetHeader(); setSelection(1); } } break; case MotionEvent.ACTION_DOWN: mLastMotionY = y; break; case MotionEvent.ACTION_MOVE: applyHeaderPadding(event); break; } return super.onTouchEvent(event); } private void applyHeaderPadding(MotionEvent ev) { // getHistorySize has been available since API 1 int pointerCount = ev.getHistorySize(); for (int p = 0; p < pointerCount; p++) { if (mRefreshState == RELEASE_TO_REFRESH) { if (isVerticalFadingEdgeEnabled()) { setVerticalScrollBarEnabled(false); } int historicalY = (int) ev.getHistoricalY(p); // Calculate the padding to apply, we divide by 1.7 to // simulate a more resistant effect during pull. int topPadding = (int) (((historicalY - mLastMotionY) - mRefreshViewHeight) / 1.7); mRefreshView.setPadding(mRefreshView.getPaddingLeft(), topPadding, mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom()); } } } /** * Sets the header padding back to original size. */ private void resetHeaderPadding() { mRefreshView.setPadding(mRefreshView.getPaddingLeft(), mRefreshOriginalTopPadding, mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom()); } /** * Resets the header to the original state. */ private void resetHeader() { if (mRefreshState != TAP_TO_REFRESH) { mRefreshState = TAP_TO_REFRESH; resetHeaderPadding(); // Set refresh view text to the pull label mRefreshViewText.setText(R.string.pull_to_refresh_tap_label); // Replace refresh drawable with arrow drawable mRefreshViewImage .setImageResource(R.drawable.ic_pulltorefresh_arrow); // Clear the full rotation animation mRefreshViewImage.clearAnimation(); // Hide progress bar and arrow. mRefreshViewImage.setVisibility(View.GONE); mRefreshViewProgress.setVisibility(View.GONE); } } private void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // When the refresh view is completely visible, change the text to say // "Release to refresh..." and flip the arrow drawable. if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && mRefreshState != REFRESHING) { if (firstVisibleItem == 0) { mRefreshViewImage.setVisibility(View.VISIBLE); if ((mRefreshView.getBottom() >= mRefreshViewHeight + 20 || mRefreshView .getTop() >= 0) && mRefreshState != RELEASE_TO_REFRESH) { mRefreshViewText .setText(R.string.pull_to_refresh_release_label); mRefreshViewImage.clearAnimation(); mRefreshViewImage.startAnimation(mFlipAnimation); mRefreshState = RELEASE_TO_REFRESH; } else if (mRefreshView.getBottom() < mRefreshViewHeight + 20 && mRefreshState != PULL_TO_REFRESH) { mRefreshViewText .setText(R.string.pull_to_refresh_pull_label); if (mRefreshState != TAP_TO_REFRESH) { mRefreshViewImage.clearAnimation(); mRefreshViewImage.startAnimation(mReverseFlipAnimation); } mRefreshState = PULL_TO_REFRESH; } } else { mRefreshViewImage.setVisibility(View.GONE); resetHeader(); } } else if (mCurrentScrollState == SCROLL_STATE_FLING && firstVisibleItem == 0 && mRefreshState != REFRESHING) { setSelection(1); mBounceHack = true; } else if (mBounceHack && mCurrentScrollState == SCROLL_STATE_FLING) { setSelection(1); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCurrentScrollState = scrollState; if (mCurrentScrollState == SCROLL_STATE_IDLE) { mBounceHack = false; } if (mOnScrollListener != null) { mOnScrollListener.onScrollStateChanged(view, scrollState); } } public void prepareForRefresh() { resetHeaderPadding(); mRefreshViewImage.setVisibility(View.GONE); // We need this hack, otherwise it will keep the previous drawable. mRefreshViewImage.setImageDrawable(null); mRefreshViewProgress.setVisibility(View.VISIBLE); // Set refresh view text to the refreshing label mRefreshViewText.setText(R.string.pull_to_refresh_refreshing_label); mRefreshState = REFRESHING; } public void onRefresh() { Log.d(TAG, "onRefresh"); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } /** * Resets the list to a normal state after a refresh. * * @param lastUpdated * Last updated at. */ public void onRefreshComplete(CharSequence lastUpdated) { setLastUpdated(lastUpdated); onRefreshComplete(); } /** * Resets the list to a normal state after a refresh. */ public void onRefreshComplete() { Log.d(TAG, "onRefreshComplete"); resetHeader(); // If refresh view is visible when loading completes, scroll down to // the next item. if (mRefreshView.getBottom() > 0) { invalidateViews(); setSelection(1); } } /** * Invoked when the refresh view is clicked on. This is mainly used when * there's only a few items in the list and it's not possible to drag the * list. */ private class OnClickRefreshListener implements OnClickListener { @Override public void onClick(View v) { if (mRefreshState != REFRESHING) { prepareForRefresh(); onRefresh(); } } } /** * Interface definition for a callback to be invoked when list should be * refreshed. */ public interface OnRefreshListener { /** * Called when the list should be refreshed. * <p> * A call to {@link PullToRefreshListView #onRefreshComplete()} is * expected to indicate that the refresh has completed. */ public void onRefresh(); } }
Java
package cn.anlab.anappframe.widget.adapter; import java.util.List; import java.util.Map; import cn.anlab.anappframe.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class ListDialogAdapter extends BaseAdapter { private Context context; private List<Map<String, String>> dataList; LayoutInflater inflater; public ListDialogAdapter(Context context, List<Map<String, String>> dataList) { this.context = context; this.dataList = dataList; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return dataList.size(); } @Override public Object getItem(int position) { return dataList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.demo_listview_item, null); } Map<String, String> map = (Map<String, String>)getItem(position); TextView tv1 = (TextView)convertView.findViewById(R.id.textView1); TextView tv2 = (TextView)convertView.findViewById(R.id.textView1); TextView tv3 = (TextView)convertView.findViewById(R.id.textView1); tv1.setText(map.get("uid")); tv2.setText("Age " + map.get("age") + ", High " + map.get("high")); tv3.setText(map.get("area")); return convertView; } }
Java
package cn.anlab.anappframe.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { //数据库名称 private static final String DB_NAME = "anappframe.db"; public DBHelper(Context context, int version) { super(context, DB_NAME, null, version); } @Override public void onCreate(SQLiteDatabase db) { executeSql(db, 0, 1); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { executeSql(db, oldVersion, newVersion); } /** * 执行新版本与本地版本差余的SQL * @param db * @param oldVersion 上次安装时的版本 * @param newVersion 此次安装时的版本 */ private void executeSql(SQLiteDatabase db, int oldVersion, int newVersion) { while((++oldVersion) <= newVersion) { executeSqlByVersion(db, oldVersion); } } /** * 执行某个版本的SQL * @param version */ private void executeSqlByVersion(SQLiteDatabase db, int version) { switch (version) { case 1: //第1个版本要执行的SQL { db.execSQL("create table if not exists tb_demo1(uid integer primary key autoincrement, uname text )"); db.execSQL("create table if not exists tb_demo2(uid integer primary key autoincrement, uname text )"); } break; case 2: //第2个版本要执行的SQL { db.execSQL("create table if not exists tb_demo3(uid integer primary key autoincrement, uname text )"); } break; //~~扩展~~,以后每发一次版本,将该版本要执行的SQL在这里写 default: break; } } }
Java
package cn.anlab.anappframe.util; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.Set; import android.os.Handler; import android.os.Message; import cn.anlab.anappframe.system.CoreApplication; public class RunTask<T> implements Runnable { private Class<T> clazz; private String methodName; private Object[] params; public RunTask(Class<T> clazz, String methodName, Object ... params) { this.clazz = clazz; this.methodName = methodName; this.params = params; } public void invoke() { //从先软引用中寻找对象,若不存在,则新建 Map<String, Object> interObjMap = CoreApplication.getInterObjMap(); String clazzName = clazz.getName(); if(! interObjMap.containsKey(clazzName)) { T obj; try { obj = clazz.newInstance(); interObjMap.put(clazzName, obj); } catch (Exception e) { throw new RuntimeException("RunTask新建实例异常!"); } } Object target = interObjMap.get(clazzName); //获取方法 Class[] paramsClasses = new Class[params.length]; for(int i = 0; i < params.length; i ++) { paramsClasses[i] = params[i].getClass(); //以下约定:定接口时,HashMap这些,用Map代替, ArrayList用List代替 if(params[i] instanceof Map) { paramsClasses[i] = Map.class; } else if(params[i] instanceof List) { paramsClasses[i] = List.class; } else if(params[i] instanceof Set) { paramsClasses[i] = Set.class; } } Method method = ClassUtil.getMethodIfAvailable(clazz, methodName, paramsClasses); if(method == null) { throw new RuntimeException("RunTask调用方法异常:方法不存在或参数不合法!"); } //调用方法 try { method.invoke(target, params); } catch (Exception e) { Log.e("anlog", "RunTask调用反射异常!", e); throw new RuntimeException("RunTask调用方法异常."); } // Message msg = new Message(); // msg.what = what; // msg.obj = rtnObj; // callbackHandler.sendMessage(msg); } @Override public void run() { invoke(); } }
Java
package cn.anlab.anappframe.util; /* * Copyright 2002-2009 the original author or authors. 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. */ import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * Miscellaneous class utility methods. Mainly for internal use within the * framework; consider Jakarta's Commons Lang for a more comprehensive suite of * class utilities. * * @author Juergen Hoeller * @author Keith Donald * @author Rob Harrop * @since 1.1 */ @SuppressWarnings("unchecked") public class ClassUtil { /** Suffix for array class names: "[]" */ public static final String ARRAY_SUFFIX="[]"; /** Prefix for internal array class names: "[" */ private static final String INTERNAL_ARRAY_PREFIX="["; /** Prefix for internal non-primitive array class names: "[L" */ private static final String NON_PRIMITIVE_ARRAY_PREFIX="[L"; /** The package separator character '.' */ private static final char PACKAGE_SEPARATOR='.'; /** The inner class separator character '$' */ private static final char INNER_CLASS_SEPARATOR='$'; /** The CGLIB class separator character "$$" */ public static final String CGLIB_CLASS_SEPARATOR="$$"; /** The ".class" file suffix */ public static final String CLASS_FILE_SUFFIX=".class"; /** * Map with primitive wrapper type as key and corresponding primitive type * as value, for example: Integer.class -> int.class. */ private static final Map<Class<?>,Class<?>> primitiveWrapperTypeMap=new HashMap<Class<?>,Class<?>>(8); /** * Map with primitive type as key and corresponding wrapper type as value, * for example: int.class -> Integer.class. */ private static final Map<Class<?>,Class<?>> primitiveTypeToWrapperMap=new HashMap<Class<?>,Class<?>>(8); /** * Map with primitive type name as key and corresponding primitive type as * value, for example: "int" -> "int.class". */ private static final Map<String,Class<?>> primitiveTypeNameMap=new HashMap<String,Class<?>>(16); /** * Map with common "java.lang" class name as key and corresponding Class as * value. Primarily for efficient deserialization of remote invocations. */ private static final Map<String,Class<?>> commonClassCache=new HashMap<String,Class<?>>(32); static { primitiveWrapperTypeMap.put(Boolean.class,boolean.class); primitiveWrapperTypeMap.put(Byte.class,byte.class); primitiveWrapperTypeMap.put(Character.class,char.class); primitiveWrapperTypeMap.put(Double.class,double.class); primitiveWrapperTypeMap.put(Float.class,float.class); primitiveWrapperTypeMap.put(Integer.class,int.class); primitiveWrapperTypeMap.put(Long.class,long.class); primitiveWrapperTypeMap.put(Short.class,short.class); for(Map.Entry<Class<?>,Class<?>> entry:primitiveWrapperTypeMap.entrySet()) { primitiveTypeToWrapperMap.put(entry.getValue(),entry.getKey()); registerCommonClasses(entry.getKey()); } Set<Class<?>> primitiveTypes=new HashSet<Class<?>>(16); primitiveTypes.addAll(primitiveWrapperTypeMap.values()); primitiveTypes.addAll(Arrays.asList(boolean[].class,byte[].class,char[].class,double[].class,float[].class,int[].class,long[].class,short[].class)); for(Class<?> primitiveType:primitiveTypes) { primitiveTypeNameMap.put(primitiveType.getName(),primitiveType); } registerCommonClasses(Boolean[].class,Byte[].class,Character[].class,Double[].class,Float[].class,Integer[].class,Long[].class,Short[].class); registerCommonClasses(Number.class,Number[].class,String.class,String[].class,Object.class,Object[].class,Class.class,Class[].class); registerCommonClasses(Throwable.class,Exception.class,RuntimeException.class,Error.class,StackTraceElement.class,StackTraceElement[].class); } /** * Register the given common classes with the ClassUtils cache. */ private static void registerCommonClasses(Class...commonClasses) { for(Class clazz:commonClasses) { commonClassCache.put(clazz.getName(),clazz); } } /** * Return the default ClassLoader to use: typically the thread context * ClassLoader, if available; the ClassLoader that loaded the ClassUtils * class will be used as fallback. * <p> * Call this method if you intend to use the thread context ClassLoader in a * scenario where you absolutely need a non-null ClassLoader reference: for * example, for class path resource loading (but not necessarily for * <code>Class.forName</code>, which accepts a <code>null</code> ClassLoader * reference as well). * * @return the default ClassLoader (never <code>null</code>) * @see java.lang.Thread#getContextClassLoader() */ public static ClassLoader getDefaultClassLoader() { ClassLoader cl=null; try { cl=Thread.currentThread().getContextClassLoader(); } catch(Throwable ex) { // Cannot access thread context ClassLoader - falling back to system // class loader... } if(cl==null) { // No thread context class loader -> use class loader of this class. cl=ClassUtil.class.getClassLoader(); } return cl; } /** * Override the thread context ClassLoader with the environment's bean * ClassLoader if necessary, i.e. if the bean ClassLoader is not equivalent * to the thread context ClassLoader already. * * @param classLoaderToUse * the actual ClassLoader to use for the thread context * @return the original thread context ClassLoader, or <code>null</code> if * not overridden */ public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) { Thread currentThread=Thread.currentThread(); ClassLoader threadContextClassLoader=currentThread.getContextClassLoader(); if(classLoaderToUse!=null&&!classLoaderToUse.equals(threadContextClassLoader)) { currentThread.setContextClassLoader(classLoaderToUse); return threadContextClassLoader; } else { return null; } } /** * Replacement for <code>Class.forName()</code> that also returns Class * instances for primitives (like "int") and array class names (like * "String[]"). * <p> * Always uses the default class loader: that is, preferably the thread * context class loader, or the ClassLoader that loaded the ClassUtils class * as fallback. * * @param name * the name of the Class * @return Class instance for the supplied name * @throws ClassNotFoundException * if the class was not found * @throws LinkageError * if the class file could not be loaded * @see Class#forName(String, boolean, ClassLoader) * @see #getDefaultClassLoader() */ public static Class forName(String name) throws ClassNotFoundException,LinkageError { return forName(name,getDefaultClassLoader()); } /** * Replacement for <code>Class.forName()</code> that also returns Class * instances for primitives (e.g."int") and array class names (e.g. * "String[]"). Furthermore, it is also capable of resolving inner class * names in Java source style (e.g. "java.lang.Thread.State" instead of * "java.lang.Thread$State"). * * @param name * the name of the Class * @param classLoader * the class loader to use (may be <code>null</code>, which * indicates the default class loader) * @return Class instance for the supplied name * @throws ClassNotFoundException * if the class was not found * @throws LinkageError * if the class file could not be loaded * @see Class#forName(String, boolean, ClassLoader) */ public static Class forName(String name,ClassLoader classLoader) throws ClassNotFoundException,LinkageError { // Assert.notNull(name, "Name must not be null"); Class clazz=resolvePrimitiveClassName(name); if(clazz==null) { clazz=commonClassCache.get(name); } if(clazz!=null) { return clazz; } // "java.lang.String[]" style arrays if(name.endsWith(ARRAY_SUFFIX)) { String elementClassName=name.substring(0,name.length()-ARRAY_SUFFIX.length()); Class elementClass=forName(elementClassName,classLoader); return Array.newInstance(elementClass,0).getClass(); } // "[Ljava.lang.String;" style arrays if(name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX)&&name.endsWith(";")) { String elementName=name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(),name.length()-1); Class elementClass=forName(elementName,classLoader); return Array.newInstance(elementClass,0).getClass(); } // "[[I" or "[[Ljava.lang.String;" style arrays if(name.startsWith(INTERNAL_ARRAY_PREFIX)) { String elementName=name.substring(INTERNAL_ARRAY_PREFIX.length()); Class elementClass=forName(elementName,classLoader); return Array.newInstance(elementClass,0).getClass(); } ClassLoader classLoaderToUse=classLoader; if(classLoaderToUse==null) { classLoaderToUse=getDefaultClassLoader(); } try { return classLoaderToUse.loadClass(name); } catch(ClassNotFoundException ex) { int lastDotIndex=name.lastIndexOf('.'); if(lastDotIndex!=-1) { String innerClassName=name.substring(0,lastDotIndex)+'$'+name.substring(lastDotIndex+1); try { return classLoaderToUse.loadClass(innerClassName); } catch(ClassNotFoundException ex2) { // swallow - let original exception get through } } throw ex; } } /** * Resolve the given class name into a Class instance. Supports primitives * (like "int") and array class names (like "String[]"). * <p> * This is effectively equivalent to the <code>forName</code> method with * the same arguments, with the only difference being the exceptions thrown * in case of class loading failure. * * @param className * the name of the Class * @param classLoader * the class loader to use (may be <code>null</code>, which * indicates the default class loader) * @return Class instance for the supplied name * @throws IllegalArgumentException * if the class name was not resolvable (that is, the class * could not be found or the class file could not be loaded) * @see #forName(String, ClassLoader) */ public static Class resolveClassName(String className,ClassLoader classLoader) throws IllegalArgumentException { try { return forName(className,classLoader); } catch(ClassNotFoundException ex) { throw new IllegalArgumentException("Cannot find class ["+className+"]",ex); } catch(LinkageError ex) { throw new IllegalArgumentException("Error loading class ["+className+"]: problem with class file or dependent class.",ex); } } /** * Resolve the given class name as primitive class, if appropriate, * according to the JVM's naming rules for primitive classes. * <p> * Also supports the JVM's internal class names for primitive arrays. Does * <i>not</i> support the "[]" suffix notation for primitive arrays; this is * only supported by {@link #forName}. * * @param name * the name of the potentially primitive class * @return the primitive class, or <code>null</code> if the name does not * denote a primitive class or primitive array class */ public static Class resolvePrimitiveClassName(String name) { Class result=null; // Most class names will be quite long, considering that they // SHOULD sit in a package, so a length check is worthwhile. if(name!=null&&name.length()<=8) { // Could be a primitive - likely. result=primitiveTypeNameMap.get(name); } return result; } /** * Determine whether the {@link Class} identified by the supplied name is * present and can be loaded. Will return <code>false</code> if either the * class or one of its dependencies is not present or cannot be loaded. * * @param className * the name of the class to check * @return whether the specified class is present * @deprecated as of Spring 2.5, in favor of * {@link #isPresent(String, ClassLoader)} */ @Deprecated public static boolean isPresent(String className) { return isPresent(className,getDefaultClassLoader()); } /** * Determine whether the {@link Class} identified by the supplied name is * present and can be loaded. Will return <code>false</code> if either the * class or one of its dependencies is not present or cannot be loaded. * * @param className * the name of the class to check * @param classLoader * the class loader to use (may be <code>null</code>, which * indicates the default class loader) * @return whether the specified class is present */ public static boolean isPresent(String className,ClassLoader classLoader) { try { forName(className,classLoader); return true; } catch(Throwable ex) { // Class or one of its dependencies is not present... return false; } } /** * Return the user-defined class for the given instance: usually simply the * class of the given instance, but the original class in case of a * CGLIB-generated subclass. * * @param instance * the instance to check * @return the user-defined class */ public static Class getUserClass(Object instance) { // Assert.notNull(instance, "Instance must not be null"); return getUserClass(instance.getClass()); } /** * Return the user-defined class for the given class: usually simply the * given class, but the original class in case of a CGLIB-generated * subclass. * * @param clazz * the class to check * @return the user-defined class */ public static Class getUserClass(Class clazz) { return(clazz!=null&&clazz.getName().contains(CGLIB_CLASS_SEPARATOR)?clazz.getSuperclass():clazz); } /** * Check whether the given class is cache-safe in the given context, i.e. * whether it is loaded by the given ClassLoader or a parent of it. * * @param clazz * the class to analyze * @param classLoader * the ClassLoader to potentially cache metadata in */ public static boolean isCacheSafe(Class clazz,ClassLoader classLoader) { // Assert.notNull(clazz, "Class must not be null"); ClassLoader target=clazz.getClassLoader(); if(target==null) { return false; } ClassLoader cur=classLoader; if(cur==target) { return true; } while(cur!=null) { cur=cur.getParent(); if(cur==target) { return true; } } return false; } /** * Get the class name without the qualified package name. * * @param className * the className to get the short name for * @return the class name of the class without the package name * @throws IllegalArgumentException * if the className is empty */ public static String getShortName(String className) { // Assert.hasLength(className, "Class name must not be empty"); int lastDotIndex=className.lastIndexOf(PACKAGE_SEPARATOR); int nameEndIndex=className.indexOf(CGLIB_CLASS_SEPARATOR); if(nameEndIndex==-1) { nameEndIndex=className.length(); } String shortName=className.substring(lastDotIndex+1,nameEndIndex); shortName=shortName.replace(INNER_CLASS_SEPARATOR,PACKAGE_SEPARATOR); return shortName; } /** * Get the class name without the qualified package name. * * @param clazz * the class to get the short name for * @return the class name of the class without the package name */ public static String getShortName(Class clazz) { return getShortName(getQualifiedName(clazz)); } /** * Return the short string name of a Java class in decapitalized JavaBeans * property format. Strips the outer class name in case of an inner class. * * @param clazz * the class * @return the short name rendered in a standard JavaBeans property format * @see java.beans.Introspector#decapitalize(String) */ public static String getShortNameAsProperty(Class clazz) { String shortName=ClassUtil.getShortName(clazz); int dotIndex=shortName.lastIndexOf('.'); shortName=(dotIndex!=-1?shortName.substring(dotIndex+1):shortName); // return Introspector.decapitalize(shortName); return shortName; //FIXME } /** * Determine the name of the class file, relative to the containing package: * e.g. "String.class" * * @param clazz * the class * @return the file name of the ".class" file */ public static String getClassFileName(Class clazz) { // Assert.notNull(clazz, "Class must not be null"); String className=clazz.getName(); int lastDotIndex=className.lastIndexOf(PACKAGE_SEPARATOR); return className.substring(lastDotIndex+1)+CLASS_FILE_SUFFIX; } /** * Determine the name of the package of the given class: e.g. "java.lang" * for the <code>java.lang.String</code> class. * * @param clazz * the class * @return the package name, or the empty String if the class is defined in * the default package */ public static String getPackageName(Class clazz) { // Assert.notNull(clazz, "Class must not be null"); String className=clazz.getName(); int lastDotIndex=className.lastIndexOf(PACKAGE_SEPARATOR); return(lastDotIndex!=-1?className.substring(0,lastDotIndex):""); } /** * Return the qualified name of the given class: usually simply the class * name, but component type class name + "[]" for arrays. * * @param clazz * the class * @return the qualified name of the class */ public static String getQualifiedName(Class clazz) { // Assert.notNull(clazz, "Class must not be null"); if(clazz.isArray()) { return getQualifiedNameForArray(clazz); } else { return clazz.getName(); } } /** * Build a nice qualified name for an array: component type class name + * "[]". * * @param clazz * the array class * @return a qualified name for the array class */ private static String getQualifiedNameForArray(Class clazz) { StringBuilder result=new StringBuilder(); while(clazz.isArray()) { clazz=clazz.getComponentType(); result.append(ClassUtil.ARRAY_SUFFIX); } result.insert(0,clazz.getName()); return result.toString(); } /** * Return the qualified name of the given method, consisting of fully * qualified interface/class name + "." + method name. * * @param method * the method * @return the qualified name of the method */ public static String getQualifiedMethodName(Method method) { // Assert.notNull(method, "Method must not be null"); return method.getDeclaringClass().getName()+"."+method.getName(); } /** * Return a descriptive name for the given object's type: usually simply the * class name, but component type class name + "[]" for arrays, and an * appended list of implemented interfaces for JDK proxies. * * @param value * the value to introspect * @return the qualified name of the class */ public static String getDescriptiveType(Object value) { if(value==null) { return null; } Class clazz=value.getClass(); if(Proxy.isProxyClass(clazz)) { StringBuilder result=new StringBuilder(clazz.getName()); result.append(" implementing "); Class[] ifcs=clazz.getInterfaces(); for(int i=0;i<ifcs.length;i++) { result.append(ifcs[i].getName()); if(i<ifcs.length-1) { result.append(','); } } return result.toString(); } else if(clazz.isArray()) { return getQualifiedNameForArray(clazz); } else { return clazz.getName(); } } /** * Determine whether the given class has a constructor with the given * signature. * <p> * Essentially translates <code>NoSuchMethodException</code> to "false". * * @param clazz * the clazz to analyze * @param paramTypes * the parameter types of the method * @return whether the class has a corresponding constructor * @see java.lang.Class#getMethod */ public static boolean hasConstructor(Class clazz,Class...paramTypes) { return(getConstructorIfAvailable(clazz,paramTypes)!=null); } /** * Determine whether the given class has a constructor with the given * signature, and return it if available (else return <code>null</code>). * <p> * Essentially translates <code>NoSuchMethodException</code> to * <code>null</code>. * * @param clazz * the clazz to analyze * @param paramTypes * the parameter types of the method * @return the constructor, or <code>null</code> if not found * @see java.lang.Class#getConstructor */ public static Constructor getConstructorIfAvailable(Class clazz,Class...paramTypes) { // Assert.notNull(clazz, "Class must not be null"); try { return clazz.getConstructor(paramTypes); } catch(NoSuchMethodException ex) { return null; } } /** * Determine whether the given class has a method with the given signature. * <p> * Essentially translates <code>NoSuchMethodException</code> to "false". * * @param clazz * the clazz to analyze * @param methodName * the name of the method * @param paramTypes * the parameter types of the method * @return whether the class has a corresponding method * @see java.lang.Class#getMethod */ public static boolean hasMethod(Class clazz,String methodName,Class...paramTypes) { return(getMethodIfAvailable(clazz,methodName,paramTypes)!=null); } /** * Determine whether the given class has a method with the given signature, * and return it if available (else return <code>null</code>). * <p> * Essentially translates <code>NoSuchMethodException</code> to * <code>null</code>. * * @param clazz * the clazz to analyze * @param methodName * the name of the method * @param paramTypes * the parameter types of the method * @return the method, or <code>null</code> if not found * @see java.lang.Class#getMethod */ public static Method getMethodIfAvailable(Class clazz,String methodName,Class...paramTypes) { // Assert.notNull(clazz, "Class must not be null"); // Assert.notNull(methodName, "Method name must not be null"); try { return clazz.getMethod(methodName,paramTypes); } catch(NoSuchMethodException ex) { return null; } } /** * Return the number of methods with a given name (with any argument types), * for the given class and/or its superclasses. Includes non-public methods. * * @param clazz * the clazz to check * @param methodName * the name of the method * @return the number of methods with the given name */ public static int getMethodCountForName(Class clazz,String methodName) { // Assert.notNull(clazz, "Class must not be null"); // Assert.notNull(methodName, "Method name must not be null"); int count=0; Method[] declaredMethods=clazz.getDeclaredMethods(); for(Method method:declaredMethods) { if(methodName.equals(method.getName())) { count++; } } Class[] ifcs=clazz.getInterfaces(); for(Class ifc:ifcs) { count+=getMethodCountForName(ifc,methodName); } if(clazz.getSuperclass()!=null) { count+=getMethodCountForName(clazz.getSuperclass(),methodName); } return count; } /** * Does the given class and/or its superclasses at least have one or more * methods (with any argument types)? Includes non-public methods. * * @param clazz * the clazz to check * @param methodName * the name of the method * @return whether there is at least one method with the given name */ public static boolean hasAtLeastOneMethodWithName(Class clazz,String methodName) { // Assert.notNull(clazz, "Class must not be null"); // Assert.notNull(methodName, "Method name must not be null"); Method[] declaredMethods=clazz.getDeclaredMethods(); for(Method method:declaredMethods) { if(method.getName().equals(methodName)) { return true; } } Class[] ifcs=clazz.getInterfaces(); for(Class ifc:ifcs) { if(hasAtLeastOneMethodWithName(ifc,methodName)) { return true; } } return(clazz.getSuperclass()!=null&&hasAtLeastOneMethodWithName(clazz.getSuperclass(),methodName)); } /** * Given a method, which may come from an interface, and a target class used * in the current reflective invocation, find the corresponding target * method if there is one. E.g. the method may be <code>IFoo.bar()</code> * and the target class may be <code>DefaultFoo</code>. In this case, the * method may be <code>DefaultFoo.bar()</code>. This enables attributes on * that method to be found. * <p> * <b>NOTE:</b> In contrast to * {@link org.springframework.aop.support.AopUtils#getMostSpecificMethod}, * this method does <i>not</i> resolve Java 5 bridge methods automatically. * Call * {@link org.springframework.core.BridgeMethodResolver#findBridgedMethod} * if bridge method resolution is desirable (e.g. for obtaining metadata * from the original method definition). * * @param method * the method to be invoked, which may come from an interface * @param targetClass * the target class for the current invocation. May be * <code>null</code> or may not even implement the method. * @return the specific target method, or the original method if the * <code>targetClass</code> doesn't implement it or is * <code>null</code> * @see org.springframework.aop.support.AopUtils#getMostSpecificMethod */ public static Method getMostSpecificMethod(Method method,Class targetClass) { if(method!=null&&targetClass!=null&&!targetClass.equals(method.getDeclaringClass())) { try { method=targetClass.getMethod(method.getName(),method.getParameterTypes()); } catch(NoSuchMethodException ex) { // Perhaps the target class doesn't implement this method: // that's fine, just use the original method. } } return method; } /** * Return a static method of a class. * * @param methodName * the static method name * @param clazz * the class which defines the method * @param args * the parameter types to the method * @return the static method, or <code>null</code> if no static method was * found * @throws IllegalArgumentException * if the method name is blank or the clazz is null */ public static Method getStaticMethod(Class clazz,String methodName,Class...args) { // Assert.notNull(clazz, "Class must not be null"); // Assert.notNull(methodName, "Method name must not be null"); try { Method method=clazz.getDeclaredMethod(methodName,args); if((method.getModifiers()&Modifier.STATIC)!=0) { return method; } } catch(NoSuchMethodException ex) { return null; } return null; } /** * Check if the given class represents a primitive wrapper, i.e. Boolean, * Byte, Character, Short, Integer, Long, Float, or Double. * * @param clazz * the class to check * @return whether the given class is a primitive wrapper class */ public static boolean isPrimitiveWrapper(Class clazz) { // Assert.notNull(clazz, "Class must not be null"); return primitiveWrapperTypeMap.containsKey(clazz); } /** * Check if the given class represents a primitive (i.e. boolean, byte, * char, short, int, long, float, or double) or a primitive wrapper (i.e. * Boolean, Byte, Character, Short, Integer, Long, Float, or Double). * * @param clazz * the class to check * @return whether the given class is a primitive or primitive wrapper class */ public static boolean isPrimitiveOrWrapper(Class clazz) { // Assert.notNull(clazz, "Class must not be null"); return(clazz.isPrimitive()||isPrimitiveWrapper(clazz)); } /** * Check if the given class represents an array of primitives, i.e. boolean, * byte, char, short, int, long, float, or double. * * @param clazz * the class to check * @return whether the given class is a primitive array class */ public static boolean isPrimitiveArray(Class clazz) { // Assert.notNull(clazz, "Class must not be null"); return(clazz.isArray()&&clazz.getComponentType().isPrimitive()); } /** * Check if the given class represents an array of primitive wrappers, i.e. * Boolean, Byte, Character, Short, Integer, Long, Float, or Double. * * @param clazz * the class to check * @return whether the given class is a primitive wrapper array class */ public static boolean isPrimitiveWrapperArray(Class clazz) { // Assert.notNull(clazz, "Class must not be null"); return(clazz.isArray()&&isPrimitiveWrapper(clazz.getComponentType())); } /** * Resolve the given class if it is a primitive class, returning the * corresponding primitive wrapper type instead. * * @param clazz * the class to check * @return the original class, or a primitive wrapper for the original * primitive type */ public static Class resolvePrimitiveIfNecessary(Class clazz) { // Assert.notNull(clazz, "Class must not be null"); return(clazz.isPrimitive()?primitiveTypeToWrapperMap.get(clazz):clazz); } /** * Check if the right-hand side type may be assigned to the left-hand side * type, assuming setting by reflection. Considers primitive wrapper classes * as assignable to the corresponding primitive types. * * @param lhsType * the target type * @param rhsType * the value type that should be assigned to the target type * @return if the target type is assignable from the value type * @see TypeUtils#isAssignable */ public static boolean isAssignable(Class lhsType,Class rhsType) { // Assert.notNull(lhsType, "Left-hand side type must not be null"); // Assert.notNull(rhsType, "Right-hand side type must not be null"); return(lhsType.isAssignableFrom(rhsType)||lhsType.equals(primitiveWrapperTypeMap.get(rhsType))); } /** * Determine if the given type is assignable from the given value, assuming * setting by reflection. Considers primitive wrapper classes as assignable * to the corresponding primitive types. * * @param type * the target type * @param value * the value that should be assigned to the type * @return if the type is assignable from the value */ public static boolean isAssignableValue(Class type,Object value) { // Assert.notNull(type, "Type must not be null"); return(value!=null?isAssignable(type,value.getClass()):!type.isPrimitive()); } /** * Convert a "/"-based resource path to a "."-based fully qualified class * name. * * @param resourcePath * the resource path pointing to a class * @return the corresponding fully qualified class name */ public static String convertResourcePathToClassName(String resourcePath) { return resourcePath.replace('/','.'); } /** * Convert a "."-based fully qualified class name to a "/"-based resource * path. * * @param className * the fully qualified class name * @return the corresponding resource path, pointing to the class */ public static String convertClassNameToResourcePath(String className) { return className.replace('.','/'); } /** * Return a path suitable for use with <code>ClassLoader.getResource</code> * (also suitable for use with <code>Class.getResource</code> by prepending * a slash ('/') to the return value. Built by taking the package of the * specified class file, converting all dots ('.') to slashes ('/'), adding * a trailing slash if necesssary, and concatenating the specified resource * name to this. <br/> * As such, this function may be used to build a path suitable for loading a * resource file that is in the same package as a class file, although * {@link org.springframework.core.io.ClassPathResource} is usually even * more convenient. * * @param clazz * the Class whose package will be used as the base * @param resourceName * the resource name to append. A leading slash is optional. * @return the built-up resource path * @see java.lang.ClassLoader#getResource * @see java.lang.Class#getResource */ public static String addResourcePathToPackagePath(Class clazz,String resourceName) { // Assert.notNull(resourceName, "Resource name must not be null"); if(!resourceName.startsWith("/")) { return classPackageAsResourcePath(clazz)+"/"+resourceName; } return classPackageAsResourcePath(clazz)+resourceName; } /** * Given an input class object, return a string which consists of the * class's package name as a pathname, i.e., all dots ('.') are replaced by * slashes ('/'). Neither a leading nor trailing slash is added. The result * could be concatenated with a slash and the name of a resource, and fed * directly to <code>ClassLoader.getResource()</code>. For it to be fed to * <code>Class.getResource</code> instead, a leading slash would also have * to be prepended to the returned value. * * @param clazz * the input class. A <code>null</code> value or the default * (empty) package will result in an empty string ("") being * returned. * @return a path which represents the package name * @see ClassLoader#getResource * @see Class#getResource */ public static String classPackageAsResourcePath(Class clazz) { if(clazz==null) { return ""; } String className=clazz.getName(); int packageEndIndex=className.lastIndexOf('.'); if(packageEndIndex==-1) { return ""; } String packageName=className.substring(0,packageEndIndex); return packageName.replace('.','/'); } /** * Build a String that consists of the names of the classes/interfaces in * the given array. * <p> * Basically like <code>AbstractCollection.toString()</code>, but stripping * the "class "/"interface " prefix before every class name. * * @param classes * a Collection of Class objects (may be <code>null</code>) * @return a String of form "[com.foo.Bar, com.foo.Baz]" * @see java.util.AbstractCollection#toString() */ public static String classNamesToString(Class...classes) { return classNamesToString(Arrays.asList(classes)); } /** * Build a String that consists of the names of the classes/interfaces in * the given collection. * <p> * Basically like <code>AbstractCollection.toString()</code>, but stripping * the "class "/"interface " prefix before every class name. * * @param classes * a Collection of Class objects (may be <code>null</code>) * @return a String of form "[com.foo.Bar, com.foo.Baz]" * @see java.util.AbstractCollection#toString() */ public static String classNamesToString(Collection<Class> classes) { if(classes.isEmpty()) { return "[]"; } StringBuilder sb=new StringBuilder("["); for(Iterator<Class> it=classes.iterator();it.hasNext();) { Class clazz=it.next(); sb.append(clazz.getName()); if(it.hasNext()) { sb.append(", "); } } sb.append("]"); return sb.toString(); } /** * Return all interfaces that the given instance implements as array, * including ones implemented by superclasses. * * @param instance * the instance to analyse for interfaces * @return all interfaces that the given instance implements as array */ public static Class[] getAllInterfaces(Object instance) { // Assert.notNull(instance, "Instance must not be null"); return getAllInterfacesForClass(instance.getClass()); } /** * Return all interfaces that the given class implements as array, including * ones implemented by superclasses. * <p> * If the class itself is an interface, it gets returned as sole interface. * * @param clazz * the class to analyse for interfaces * @return all interfaces that the given object implements as array */ public static Class[] getAllInterfacesForClass(Class clazz) { return getAllInterfacesForClass(clazz,null); } /** * Return all interfaces that the given class implements as array, including * ones implemented by superclasses. * <p> * If the class itself is an interface, it gets returned as sole interface. * * @param clazz * the class to analyse for interfaces * @param classLoader * the ClassLoader that the interfaces need to be visible in (may * be <code>null</code> when accepting all declared interfaces) * @return all interfaces that the given object implements as array */ public static Class[] getAllInterfacesForClass(Class clazz,ClassLoader classLoader) { // Assert.notNull(clazz, "Class must not be null"); if(clazz.isInterface()) { return new Class[]{clazz}; } List<Class> interfaces=new ArrayList<Class>(); while(clazz!=null) { Class[] ifcs=clazz.getInterfaces(); for(Class ifc:ifcs) { if(!interfaces.contains(ifc)&&(classLoader==null||isVisible(ifc,classLoader))) { interfaces.add(ifc); } } clazz=clazz.getSuperclass(); } return interfaces.toArray(new Class[interfaces.size()]); } /** * Return all interfaces that the given instance implements as Set, * including ones implemented by superclasses. * * @param instance * the instance to analyse for interfaces * @return all interfaces that the given instance implements as Set */ public static Set<Class> getAllInterfacesAsSet(Object instance) { // Assert.notNull(instance, "Instance must not be null"); return getAllInterfacesForClassAsSet(instance.getClass()); } /** * Return all interfaces that the given class implements as Set, including * ones implemented by superclasses. * <p> * If the class itself is an interface, it gets returned as sole interface. * * @param clazz * the class to analyse for interfaces * @return all interfaces that the given object implements as Set */ public static Set<Class> getAllInterfacesForClassAsSet(Class clazz) { return getAllInterfacesForClassAsSet(clazz,null); } /** * Return all interfaces that the given class implements as Set, including * ones implemented by superclasses. * <p> * If the class itself is an interface, it gets returned as sole interface. * * @param clazz * the class to analyse for interfaces * @param classLoader * the ClassLoader that the interfaces need to be visible in (may * be <code>null</code> when accepting all declared interfaces) * @return all interfaces that the given object implements as Set */ public static Set<Class> getAllInterfacesForClassAsSet(Class clazz,ClassLoader classLoader) { // Assert.notNull(clazz, "Class must not be null"); if(clazz.isInterface()) { return Collections.singleton(clazz); } Set<Class> interfaces=new LinkedHashSet<Class>(); while(clazz!=null) { for(int i=0;i<clazz.getInterfaces().length;i++) { Class ifc=clazz.getInterfaces()[i]; if(classLoader==null||isVisible(ifc,classLoader)) { interfaces.add(ifc); } } clazz=clazz.getSuperclass(); } return interfaces; } /** * Create a composite interface Class for the given interfaces, implementing * the given interfaces in one single Class. * <p> * This implementation builds a JDK proxy class for the given interfaces. * * @param interfaces * the interfaces to merge * @param classLoader * the ClassLoader to create the composite Class in * @return the merged interface as Class * @see java.lang.reflect.Proxy#getProxyClass */ public static Class createCompositeInterface(Class[] interfaces,ClassLoader classLoader) { // Assert.notEmpty(interfaces, "Interfaces must not be empty"); // Assert.notNull(classLoader, "ClassLoader must not be null"); return Proxy.getProxyClass(classLoader,interfaces); } /** * Check whether the given class is visible in the given ClassLoader. * * @param clazz * the class to check (typically an interface) * @param classLoader * the ClassLoader to check against (may be <code>null</code>, in * which case this method will always return <code>true</code>) */ public static boolean isVisible(Class clazz,ClassLoader classLoader) { if(classLoader==null) { return true; } try { Class actualClass=classLoader.loadClass(clazz.getName()); return(clazz==actualClass); // Else: different interface class found... } catch(ClassNotFoundException ex) { // No interface class found... return false; } } /* * 取得某一类所在包的所有类名 不含迭代 */ public static String[] getPackageAllClassName(String classLocation,String packageName) { // 将packageName分解 String[] packagePathSplit=packageName.split("[.]"); String realClassLocation=classLocation; int packageLength=packagePathSplit.length; for(int i=0;i<packageLength;i++) { realClassLocation=realClassLocation+File.separator+packagePathSplit[i]; } File packeageDir=new File(realClassLocation); if(packeageDir.isDirectory()) { String[] allClassName=packeageDir.list(); return allClassName; } return null; } /** * 从包package中获取所有的Class * * @param pack * @return */ public static Set<Class<?>> getClasses(Package pack) { // 第一个class类的集合 Set<Class<?>> classes=new LinkedHashSet<Class<?>>(); // 是否循环迭代 boolean recursive=true; // 获取包的名字 并进行替换 String packageName=pack.getName(); String packageDirName=packageName.replace('.','/'); // 定义一个枚举的集合 并进行循环来处理这个目录下的things Enumeration<URL> dirs; try { dirs=Thread.currentThread().getContextClassLoader().getResources(packageDirName); // 循环迭代下去 while(dirs.hasMoreElements()) { // 获取下一个元素 URL url=dirs.nextElement(); // 得到协议的名称 String protocol=url.getProtocol(); // 如果是以文件的形式保存在服务器上 if("file".equals(protocol)) { // 获取包的物理路径 String filePath=URLDecoder.decode(url.getFile(),"UTF-8"); // 以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName,filePath,recursive,classes); } else if("jar".equals(protocol)) { // 如果是jar包文件 // 定义一个JarFile JarFile jar; try { // 获取jar jar=((JarURLConnection)url.openConnection()).getJarFile(); // 从此jar包 得到一个枚举类 Enumeration<JarEntry> entries=jar.entries(); // 同样的进行循环迭代 while(entries.hasMoreElements()) { // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry=entries.nextElement(); String name=entry.getName(); // 如果是以/开头的 if(name.charAt(0)=='/') { // 获取后面的字符串 name=name.substring(1); } // 如果前半部分和定义的包名相同 if(name.startsWith(packageDirName)) { int idx=name.lastIndexOf('/'); // 如果以"/"结尾 是一个包 if(idx!=-1) { // 获取包名 把"/"替换成"." packageName=name.substring(0,idx).replace('/','.'); } // 如果可以迭代下去 并且是一个包 if((idx!=-1)||recursive) { // 如果是一个.class文件 而且不是目录 if(name.endsWith(CLASS_FILE_SUFFIX)&&!entry.isDirectory()) { // 去掉后面的".class" 获取真正的类名 String className=name.substring(packageName.length()+1,name.length()-6); try { // 添加到classes classes.add(Class.forName(packageName+'.'+className)); } catch(ClassNotFoundException e) { e.printStackTrace(); } } } } } } catch(IOException e) { e.printStackTrace(); } } } } catch(IOException e) { e.printStackTrace(); } return classes; } /** * 从包package中获取所有的Class * * @param pack * @return */ public static Set<Class<?>> getClasses(String packageName) { // 第一个class类的集合 Set<Class<?>> classes=new LinkedHashSet<Class<?>>(); // 是否循环迭代 boolean recursive=true; // 获取包的名字 并进行替换 // String packageName = pack.getName(); String packageDirName=packageName.replace('.','/'); // 定义一个枚举的集合 并进行循环来处理这个目录下的things Enumeration<URL> dirs; try { dirs=Thread.currentThread().getContextClassLoader().getResources(packageDirName); // 循环迭代下去 while(dirs.hasMoreElements()) { // 获取下一个元素 URL url=dirs.nextElement(); // 得到协议的名称 String protocol=url.getProtocol(); // 如果是以文件的形式保存在服务器上 if("file".equals(protocol)) { // 获取包的物理路径 String filePath=URLDecoder.decode(url.getFile(),"UTF-8"); // 以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName,filePath,recursive,classes); } else if("jar".equals(protocol)) { // 如果是jar包文件 // 定义一个JarFile JarFile jar; try { // 获取jar jar=((JarURLConnection)url.openConnection()).getJarFile(); // 从此jar包 得到一个枚举类 Enumeration<JarEntry> entries=jar.entries(); // 同样的进行循环迭代 while(entries.hasMoreElements()) { // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry=entries.nextElement(); String name=entry.getName(); // 如果是以/开头的 if(name.charAt(0)=='/') { // 获取后面的字符串 name=name.substring(1); } // 如果前半部分和定义的包名相同 if(name.startsWith(packageDirName)) { int idx=name.lastIndexOf('/'); // 如果以"/"结尾 是一个包 if(idx!=-1) { // 获取包名 把"/"替换成"." packageName=name.substring(0,idx).replace('/','.'); } // 如果可以迭代下去 并且是一个包 if((idx!=-1)||recursive) { // 如果是一个.class文件 而且不是目录 if(name.endsWith(CLASS_FILE_SUFFIX)&&!entry.isDirectory()) { // 去掉后面的".class" 获取真正的类名 String className=name.substring(packageName.length()+1,name.length()-6); try { // 添加到classes classes.add(Class.forName(packageName+'.'+className)); } catch(ClassNotFoundException e) { System.out.println("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } } } catch(IOException e) { System.out.println("在扫描用户定义视图时从jar包获取文件出错"); e.printStackTrace(); } } } } catch(IOException e) { e.printStackTrace(); } return classes; } /** * 以文件的形式来获取包下的所有Class * * @param packageName * @param packagePath * @param recursive * @param classes */ public static void findAndAddClassesInPackageByFile(String packageName,String packagePath,final boolean recursive,Set<Class<?>> classes) { // 获取此包的目录 建立一个File File dir=new File(packagePath); // 如果不存在或者 也不是目录就直接返回 if(!dir.exists()||!dir.isDirectory()) { System.out.println("用户定义包名 "+packageName+" 下没有任何文件"); return; } // 如果存在 就获取包下的所有文件 包括目录 File[] dirfiles=dir.listFiles(new FileFilter() { // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) public boolean accept(File file) { return (recursive&&file.isDirectory())||(file.getName().endsWith(".class")); } }); // 循环所有文件 for(File file:dirfiles) { // 如果是目录 则继续扫描 if(file.isDirectory()) { findAndAddClassesInPackageByFile(packageName+"."+file.getName(),file.getAbsolutePath(),recursive,classes); } else { // 如果是java类文件 去掉后面的.class 只留下类名 String className=file.getName().substring(0,file.getName().length()-6); try { // 添加到集合中去 classes.add(Class.forName(packageName+'.'+className)); } catch(ClassNotFoundException e) { System.out.println("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } /** * 直接读取对象属性值,无视private/protected修饰符,不经过getter函数. */ public static Object getFieldValue(final Object object,final String fieldName) { Object result=null; try { Field field=getDeclaredField(object,fieldName); makeAccessible(field); result=field.get(object); } catch(IllegalAccessException e) { } return result; } /** * 强制转换fileld可访问. */ protected static void makeAccessible(Field field) { if(!Modifier.isPublic(field.getModifiers())||!Modifier.isPublic(field.getDeclaringClass().getModifiers())) { field.setAccessible(true); } } /** * 循环向上转型,获取对象的DeclaredField. */ public static Field getDeclaredField(final Object object,final String fieldName) { return getDeclaredField(object.getClass(),fieldName); } /** * 循环向上转型,获取类的DeclaredField. */ @SuppressWarnings("unchecked") protected static Field getDeclaredField(final Class clazz,final String fieldName) { for(Class superClass=clazz;superClass!=Object.class;superClass=superClass.getSuperclass()) { try { return superClass.getDeclaredField(fieldName); } catch(NoSuchFieldException e) { // Field不在当前类定义,继续向上转型 } } return null; } /** * 直接设置对象属性值,无视private/protected修饰符,不经过setter函数. */ public static void setFieldValue(final Object object,final String fieldName,final Object value) { try { Field field=getDeclaredField(object,fieldName); makeAccessible(field); field.set(object,value); } catch(IllegalAccessException e) { } } }
Java
package cn.anlab.anappframe.util; import cn.anlab.anappframe.anim.Trans; import android.app.Activity; import android.content.Context; import android.util.DisplayMetrics; import android.view.WindowManager; public class ViewUtil { /** * 获取屏幕的长宽属性 * @param context * @return */ public static DisplayMetrics getDisplayMetrics(Context context) { DisplayMetrics dm = new DisplayMetrics(); WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(dm); return dm; } /** * 设置Activity转换的动画效果 * @param activity * @param tran */ public static void setTransition(Activity activity, Trans tran) { int[] anims = tran.getEnterAndExitAnim(); activity.overridePendingTransition(anims[0], anims[1]); } /** * 获取颜色 * @param context * @param resId * @return */ public static int getColor(Context context, int resId) { return context.getResources().getColor(resId); } /** * 将px转为dip * * @param context * @param pxValue * @return * @author : wang.jun<br> * @time : 2011-12-14 下午03:47:10<br> */ public static final int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** * 将dip转为px * * @param context * @param dipValue * @return * @author : wang.jun<br> * @time : 2011-12-14 下午03:57:26<br> */ public static final int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } }
Java
package cn.anlab.anappframe.util; import android.os.Handler; import cn.anlab.anappframe.system.CoreApplication; public class AQ { /** * 添加到处理序列 * @param clazz * @param methodName ---mark:handler和what都不用了,统一用interest注册 * @param param */ public synchronized static <T>void addToAsyncQueue(Class<T> clazz, String methodName, Object ... params) { RunTask<T> task = new RunTask<T>(clazz, methodName, params); CoreApplication.getAsyncRunTaskPool().submit(task); } }
Java
package cn.anlab.anappframe.activity; import android.app.Activity; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.FloatMath; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.ViewSwitcher; import cn.anlab.anappframe.R; public class PhotoActivity extends Activity implements OnTouchListener { private ImageSwitcher switcher; private Gallery gallery; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.photo); switcher = (ImageSwitcher) findViewById(R.id.switcher); ivPhoto = (ImageView)findViewById(R.id.ivPhoto); gallery = (Gallery) findViewById(R.id.gallery); // 设置图片生成工厂 switcher.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { ImageView iv = new ImageView(PhotoActivity.this); iv.setScaleType(ScaleType.MATRIX); iv.setOnTouchListener(PhotoActivity.this); return iv; } }); // 设置图片切换的动画 switcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); switcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out)); // 显示中间那张图片 switcher.setImageDrawable(getResources().getDrawable( ids[ids.length / 2])); switcher.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); // Gallery // Gallery gallery = new Gallery(this) { // @Override // public boolean onFling(MotionEvent e1, MotionEvent e2, // float velocityX, float velocityY) { // return false; // } // }; gallery.setSpacing(1); // 需要设置此属性,不然两图片边缘会有部分重叠在一起 ColorDrawable drawable = new ColorDrawable(Color.WHITE); drawable.setAlpha(200); gallery.setBackgroundDrawable(drawable); gallery.setPadding(5, 5, 5, 5); gallery.setAdapter(imgAdapter); // 点击事件,切换大图 gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ivPhoto.setImageResource(ids[position]); selectPos = position; switcher.setImageDrawable(getResources().getDrawable( ids[position])); } }); // 选中中间那张 gallery.setSelection(ids.length / 2, true); detector = new GestureDetector(this, gestureListener); System.out.println("count = " + switcher.getChildCount()); } private int selectPos = 0; int[] ids = { R.drawable.girl2, R.drawable.girl1, R.drawable.girl3, R.drawable.girl4, R.drawable.girl5 }; BaseAdapter imgAdapter = new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = new ImageView(PhotoActivity.this); convertView.setLayoutParams(new Gallery.LayoutParams(120, 80)); ((ImageView) convertView).setScaleType(ScaleType.CENTER_CROP); } Drawable drawable = getResources().getDrawable(ids[position]); ((ImageView) convertView).setImageDrawable(drawable); return convertView; } @Override public long getItemId(int position) { return 0; } @Override public Object getItem(int position) { return null; } @Override public int getCount() { return ids.length; } }; // Matrix instances to move and zoom image Matrix matrix = new Matrix(); Matrix eventMatrix = new Matrix(); // possible touch states final static int NONE = 0; final static int DRAG = 1; final static int ZOOM = 2; int touchState = NONE; final static float MIN_DIST = 50; static float eventDistance = 0; static float centerX = 0, centerY = 0; @Override public boolean onTouch(View v, MotionEvent event) { return detector.onTouchEvent(event); // ImageView view = (ImageView) v; // switch (event.getAction() & MotionEvent.ACTION_MASK) { // case MotionEvent.ACTION_DOWN: // Log.i("MultitouchTestActivity", "ACTION_DOWN, (" + event.getX(0) + ", " + event.getY(0) + ")"); // // primary touch event starts: remember touch down location // touchState = DRAG; // centerX = event.getX(0); // centerY = event.getY(0); // eventMatrix.set(matrix); // break; // case MotionEvent.ACTION_POINTER_DOWN: // Log.i("MultitouchTestActivity", "ACTION_POINTER_DOWN, (" + event.getX(0) + ", " + event.getY(0) + "), (" + event.getX(1) + ", " + event.getY(1) + ")"); // // secondary touch event starts: remember distance and center // eventDistance = calcDistance(event); // calcMidpoint(centerX, centerY, event); //???怎么改变形参? // if (eventDistance > MIN_DIST) { // eventMatrix.set(matrix); // touchState = ZOOM; // } // break; // // case MotionEvent.ACTION_MOVE: // if (touchState == DRAG) { // Log.i("MultitouchTestActivity", "ACTION_MOVE, (" + event.getX(0) + ", " + event.getY(0) + ")"); // // single finger drag, translate accordingly // matrix.set(eventMatrix); // matrix.postTranslate(event.getX(0) - centerX, event.getY(0) - centerY); // } else if (touchState == ZOOM) { // Log.i("MultitouchTestActivity", "ACTION_MOVE, (" + event.getX(0) + ", " + event.getY(0) + "), (" + event.getX(1) + ", " + event.getY(1) + ")"); // // multi-finger zoom, scale accordingly around center // float dist = calcDistance(event); // if (dist > MIN_DIST) { // matrix.set(eventMatrix); // float scale = dist / eventDistance; // matrix.postScale(scale, scale, centerX, centerY); // } // } // // Perform the transformation // view.setImageMatrix(matrix); // break; // case MotionEvent.ACTION_UP: // case MotionEvent.ACTION_POINTER_UP: // Log.i("MultitouchTestActivity", "ACTION_UP, (" + event.getX(0) + ", " + event.getY(0) + ")"); // touchState = NONE; // break; // } // return true; } //手势监听事件,监听所有手势 OnGestureListener gestureListener = new OnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { Log.i("PicGallery", "onSingleTapUp..." + e.getAction()); return false; } @Override public void onShowPress(MotionEvent e) { Log.i("PicGallery", "onShowPress..." + e.getAction()); } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { Log.i("PicGallery", "onScroll...e1 = " + e1.getAction() + ", e2 = " + e2.getAction() + ", distanceX = " + distanceX + ", distanceY = " + distanceY); // switcher.getChildAt(selectPos).scrollBy((int)distanceX, (int)distanceY); ivPhoto.scrollBy((int)distanceX, (int)distanceY); return false; } @Override public void onLongPress(MotionEvent e) { Log.i("PicGallery", "onLongPress..." + e.getAction()); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.i("PicGallery", "onFling...e1 = " + e1.getAction() + ", e2 = " + e2.getAction() + ", velocityX = " + velocityX + ", velocityY = " + velocityY); return false; } @Override public boolean onDown(MotionEvent e) { Log.i("PicGallery", "onDown..." + e.getAction()); // return false; //返回false的话,下面的move, up等事件就接收不到了 return true; //所以,要返回true } }; private GestureDetector detector; private ImageView ivPhoto; /** * 计算触摸的两点间的距离 * @param event * @return */ private float calcDistance(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } /** * 计算触摸的两点的中点坐标 * @param centerX * @param centerY * @param event */ private void calcMidpoint(float centerX, float centerY, MotionEvent event) { centerX = (event.getX(0) + event.getX(1)) / 2; centerY = (event.getY(0) + event.getY(1)) / 2; } }
Java
package cn.anlab.anappframe.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import cn.anlab.anappframe.BaseActivity; import cn.anlab.anappframe.R; import cn.anlab.anappframe.demo.activity.HomeDemoActivity; import cn.anlab.anappframe.system.CoreApplication; public class SplashActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash); waitTask.start(); } public Thread waitTask = new Thread() { public void run() { try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } handler.sendEmptyMessage(1); }; }; private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { CoreApplication.initNetConnection(); //跳转到首页 Intent intent = new Intent(); intent.setClass(SplashActivity.this, HomeDemoActivity.class); startActivity(intent); finish(); }; }; }
Java
package cn.anlab.anappframe.demo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DemoDataUtil { public static List<Map<String, String>> getHomeItem(int count) { List<Map<String, String>>list = new ArrayList<Map<String, String>>(); for(int i = 0; i < count; i ++ ) { Map<String, String> map = new HashMap<String, String>(); map.put("name", "Menu" + i); map.put("uid", "ID056" + i); map.put("age", 20 + i + ""); map.put("high", "760"); map.put("area", "Guangdong China"); list.add(map); } return list; } }
Java
package cn.anlab.anappframe.demo.bo; import java.util.Map; public class LoginBO { public void login(Map data) { } public void loginSuccess(Map data) { } public void loginFail(Map data) { } }
Java
package cn.anlab.anappframe.demo.bo; import java.util.List; import java.util.Map; import cn.anlab.anappframe.system.CoreApplication; public class ChatBO extends BO { public void sendSms(Map data) { int cmd = 123; CoreApplication.sendRemote(cmd, data); } public void receiveSms(Map data) { } public void queryMailList(Map data) { } public void queryMailListRsp(List data) { } }
Java
package cn.anlab.anappframe.demo.bo; import android.os.Handler; import cn.anlab.anappframe.net.Packet; import cn.anlab.anappframe.system.CoreApplication; public class BO { }
Java
package cn.anlab.anappframe.demo.adapter; import java.util.List; import java.util.Map; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.TextView; import cn.anlab.anappframe.R; public class HomeAdapter extends BaseAdapter { private Context context; private List<Map<String, String>> dataList; public HomeAdapter(Context context, List<Map<String, String>> dataList) { this.context = context; this.dataList = dataList; } @Override public int getCount() { return dataList.size(); } @Override public Object getItem(int position) { return dataList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.demo_home_menu_item, null); TextView tv = (TextView)itemView.findViewById(R.id.home_menu_item_txt); Map<String, String> map = (Map<String, String>)getItem(position); tv.setText(map.get("name")); return itemView; } }
Java
package cn.anlab.anappframe.demo.adapter; import java.util.List; import java.util.Map; import cn.anlab.anappframe.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.RadioButton; import android.widget.TextView; /** * 列表对话框中列表的Adapter * * @version 1.0 * @author Stan Rong 2012-3-6 */ public class ListViewAdapter extends BaseAdapter { private Context context; private List<Map<String, String>> dataList; private String textKey; LayoutInflater inflater; public ListViewAdapter(Context context, List<Map<String, String>> dataList, String textKey) { this.context = context; this.dataList = dataList; this.textKey = textKey; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return dataList.size(); } @Override public Object getItem(int position) { return dataList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.comp_listdialog_item, null); } Map<String, String> map = (Map<String, String>)getItem(position); TextView tv = (TextView)convertView.findViewById(R.id.comp_listdialog_text); RadioButton radio = (RadioButton)convertView.findViewById(R.id.comp_listdialog_radio); setItemData(map, tv); return convertView; } /** * 设置每行的文本内容 <br/> * 可重写此方法,去给每行的文本赋值 * @param rowData * @param tv */ protected void setItemData(Map<String, String> rowData, TextView tv) { tv.setText(rowData.get(textKey)); } public List<Map<String, String>> getDataList() { return dataList; } }
Java
package cn.anlab.anappframe.demo.activity; import android.app.Activity; import android.os.Bundle; public class TabDemoActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
Java
package cn.anlab.anappframe.demo.activity; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Spinner; import android.widget.Toast; import cn.anlab.anappframe.R; import cn.anlab.anappframe.demo.DemoDataUtil; import cn.anlab.anappframe.demo.adapter.HomeAdapter; import cn.anlab.anappframe.widget.CompDialog; import cn.anlab.anappframe.widget.CompProgressDialog; public class WidgetDemoActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_widget); Dialog d = new Dialog(this); CompDialog dialog = new CompDialog(this); dialog.setTitle("Test Dialog"); dialog.setMessage("How are you? Marry."); // dialog.show(); DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(WidgetDemoActivity.this, "which = " + which, Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }; dialog.setButton(CompDialog.BUTTON1, "OK", dialogListener); dialog.setButton(CompDialog.BUTTON2, "Cancel", dialogListener); // CompProgressDialog pdialog = new CompProgressDialog(this); // pdialog.show(); ImageView iv = (ImageView)findViewById(R.id.imageView1); Animation anim = AnimationUtils.loadAnimation(this, R.anim.rotate_loading); iv.startAnimation(anim); //下拉框 List<Map<String, String>> itemList = DemoDataUtil.getHomeItem(15); HomeAdapter adapter = new HomeAdapter(this, itemList); Spinner spn = (Spinner)findViewById(R.id.spinner1); spn.setAdapter(adapter); itemList.remove(0); adapter.notifyDataSetChanged(); new AlertDialog.Builder(this).setTitle("AlertDialog改样式").setMessage("改样式啦,终于成功了...").show(); } }
Java
package cn.anlab.anappframe.demo.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import cn.anlab.anappframe.R; public class DActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_intent); Log.i("anlog", "D.onCreate()"); TextView tv = (TextView) findViewById(R.id.textView1); tv.setText("DDDD"); tv.setOnClickListener(this); } @Override protected void onStart() { super.onStart(); Log.i("anlog", "D.onStart()"); } @Override protected void onResume() { super.onResume(); Log.i("anlog", "D.onResume();"); } @Override protected void onStop() { super.onStop(); Log.i("anlog", "D.onStop();"); } @Override protected void onPause() { super.onPause(); Log.i("anlog", "D.onPause();"); } @Override protected void onDestroy() { super.onDestroy(); Log.i("anlog", "D.onDestroy();"); } @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(this, BActivity.class); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }
Java
package cn.anlab.anappframe.demo.activity; import java.util.HashMap; import java.util.Map; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import cn.anlab.anappframe.BaseActivity; import cn.anlab.anappframe.R; import cn.anlab.anappframe.demo.bo.ChatBO; import cn.anlab.anappframe.system.Event; import cn.anlab.anappframe.util.AQ; public class ChatDemoActivity extends BaseActivity { LinearLayout panel; EditText edtInput; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_chat); interest(handler, Event.RECEIVE_CHAT_MESSAGE); panel = (LinearLayout)findViewById(R.id.sms_list_panel); edtInput = (EditText)findViewById(R.id.editText1); edtInput.setText("Hello."); Button btnSend = (Button)findViewById(R.id.button1); btnSend.setOnClickListener(btnSendClick); } public void showSmsSended(String content) { View pane = getLayoutInflater().inflate(R.layout.demo_chat_sms_sended, null); TextView tv= (TextView)pane.findViewById(R.id.textView2); tv.setText(content); panel.addView(pane); } public void showSmsReceived(String content) { View pane = getLayoutInflater().inflate(R.layout.demo_chat_sms_received, null); TextView tv= (TextView)pane.findViewById(R.id.textView1); tv.setText(content); panel.addView(pane); } /** * 点击事件 */ private View.OnClickListener btnSendClick = new View.OnClickListener() { @Override public void onClick(View v) { String input = edtInput.getText().toString().trim(); Map m = new HashMap(); m.put("msg", input); m.put("userKey", "123456"); // showLoading(); showSmsSended(input); AQ.addToAsyncQueue(ChatBO.class, "sendSms", m); } }; private Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 333: break; case Event.RECEIVE_CHAT_MESSAGE: //收到消息后 hideLoading(); Map data = (Map)msg.obj; String text = (String)data.get("msg"); showSmsReceived(text); break; default: break; } }; }; protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data) { }; }
Java
package cn.anlab.anappframe.demo.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import cn.anlab.anappframe.R; public class AActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_intent); Log.i("anlog", "A.onCreate()"); TextView tv = (TextView) findViewById(R.id.textView1); tv.setText("AAAA"); tv.setOnClickListener(this); } @Override protected void onStart() { super.onStart(); Log.i("anlog", "A.onStart()"); } @Override protected void onResume() { super.onResume(); Log.i("anlog", "A.onResume();"); } @Override protected void onStop() { super.onStop(); Log.i("anlog", "A.onStop();"); } @Override protected void onPause() { super.onPause(); Log.i("anlog", "A.onPause();"); } @Override protected void onDestroy() { super.onDestroy(); Log.i("anlog", "A.onDestroy();"); } @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(this, BActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
Java
package cn.anlab.anappframe.demo.activity; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import cn.anlab.anappframe.R; import cn.anlab.anappframe.activity.PhotoActivity; import cn.anlab.anappframe.anim.ActivitySwitcher; import cn.anlab.anappframe.demo.DemoDataUtil; import cn.anlab.anappframe.demo.adapter.HomeAdapter; import cn.anlab.anappframe.service.CoreService; import cn.anlab.anappframe.system.CoreApplication; import com.gallery.ActivityMain; public class HomeDemoActivity extends Activity { ImageView banner; ImageView bannerx; TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_home); GridView gv = (GridView)findViewById(R.id.home_menu_gridview); gv.setVerticalSpacing(20); gv.setSelector(new ColorDrawable(Color.TRANSPARENT)); HomeAdapter adapter = new HomeAdapter(this, DemoDataUtil.getHomeItem(10)); gv.setAdapter(adapter); gv.setOnItemClickListener(menuClickListener); banner = (ImageView)findViewById(R.id.imageView1); banner.setVisibility(View.GONE); bannerx = (ImageView)findViewById(R.id.imageView2); tv = (TextView)findViewById(R.id.textView1); tv.setText(getResources().getString(R.string.app_name)); } @Override protected void onResume() { // animateIn this activity ActivitySwitcher.animationIn(findViewById(R.id.container), getWindowManager()); super.onResume(); } @Override public void finish() { // we need to override this to performe the animtationOut on each // finish. ActivitySwitcher.animationOut(findViewById(R.id.container), getWindowManager(), new ActivitySwitcher.AnimationFinishedListener() { @Override public void onAnimationFinished() { HomeDemoActivity.super.finish(); // disable default animation overridePendingTransition(0, 0); } }); } // ... private AdapterView.OnItemClickListener menuClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: startActivity(new Intent(HomeDemoActivity.this, WidgetDemoActivity.class)); break; case 1: startActivity(new Intent(HomeDemoActivity.this, ChatDemoActivity.class)); break; case 2: //开启服务 // Toast.makeText(HomeDemoActivity.this, "start service ...", Toast.LENGTH_SHORT).show(); // startService(new Intent(HomeDemoActivity.this, CoreService.class)); startActivity(new Intent(HomeDemoActivity.this, PullToRefreshListViewDemoActivity.class)); break; case 3: // startActivity(new Intent(HomeDemoActivity.this, ListViewDemoActivity.class)); // we only animateOut this activity here. // The new activity will animateIn from its onResume() - be sure to implement it. final Intent intent = new Intent(getApplicationContext(), ListViewDemoActivity.class); // disable default animation for new intent intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); ActivitySwitcher.animationOut(findViewById(R.id.container), getWindowManager(), new ActivitySwitcher.AnimationFinishedListener() { @Override public void onAnimationFinished() { startActivity(intent); } }); break; case 4: //国际化 CoreApplication.changeChannel("ca"); tv.setText(getResources().getString(R.string.app_name)); bannerx.setImageDrawable(getResources().getDrawable(R.drawable.app_bannerx)); break; case 5: //国际化 CoreApplication.changeChannel("cb"); tv.setText(getResources().getString(R.string.app_name)); bannerx.setImageDrawable(getResources().getDrawable(R.drawable.app_bannerx)); break; case 6: //国际化 CoreApplication.changeChannel("cc"); tv.setText(getResources().getString(R.string.app_name)); bannerx.setImageDrawable(getResources().getDrawable(R.drawable.app_bannerx)); break; case 7: banner.setImageLevel(0); // startActivity(new Intent(HomeDemoActivity.this, DimensActivity.class)); startActivity(new Intent(HomeDemoActivity.this, ActivityMain.class)); break; case 8: banner.setImageLevel(1); startActivity(new Intent(HomeDemoActivity.this, ActivityGroupDemoActivity.class)); break; case 9: banner.setImageLevel(2); startActivity(new Intent(HomeDemoActivity.this, PhotoActivity.class)); break; default: break; } } }; }
Java
package cn.anlab.anappframe.demo.activity; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import cn.anlab.anappframe.R; import cn.anlab.anappframe.demo.DemoDataUtil; import cn.anlab.anappframe.demo.adapter.ListViewAdapter; import cn.anlab.anappframe.widget.CompListView; public class ListViewDemoActivity extends Activity { CompListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_listview); LinearLayout container = (LinearLayout)findViewById(R.id.container); // ListView lv = (ListView)findViewById(R.id.listView1); // //启用快速滚动块 // lv.setFastScrollEnabled(true); // // ListViewAdapter adapter = new ListViewAdapter(this, DemoDataUtil.getHomeItem(45)); // lv.setAdapter(adapter); lv = new CompListView(this, CompListView.PROP_FOOTER_LOADING |CompListView.PROP_HEADER_LOADING); // lv.setHeaderVisibility(View.VISIBLE); lv.setFooterState(CompListView.FOOTER_STATE_MORE_BUTTON); //启用快速滚动块 lv.setFastScrollEnabled(true); ListViewAdapter adapter = new ListViewAdapter(this, DemoDataUtil.getHomeItem(45), "name"); lv.setAdapter(adapter); LinearLayout.LayoutParams prm = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); container.addView(lv); //行点击事件 lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i("anlog", "position : " + position); } }); //滚动加载 lv.setOnScrollListener(lvOnScrollListener); } //滚动事件 private OnScrollListener lvOnScrollListener = new OnScrollListener() { private int firstVisibleItem; @Override public void onScrollStateChanged(AbsListView view, int scrollState) { Log.i("anlog", "scrollState : " + scrollState); if(firstVisibleItem == 0) { if(scrollState == OnScrollListener.SCROLL_STATE_IDLE) { lv.setHeaderState(CompListView.HEADER_STATE_LOADING); } else { lv.setHeaderState(CompListView.HEADER_STATE_TO_RELEASE); } } } @Override public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) { Log.i("anlog", "firstVisibleItem : " + firstVisibleItem + ", visibleItemCount : " + visibleItemCount + ", totalItemCount : " + totalItemCount); this.firstVisibleItem = firstVisibleItem; } }; } //private int lastItemIndex = 0; // //@Override //public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { //// Log.i("CompListView", "first : " + firstVisibleItem + ", visible : " + visibleItemCount + ", total : " + totalItemCount); // lastItemIndex = firstVisibleItem + visibleItemCount; //} //@Override //public void onScrollStateChanged(AbsListView view, int scrollState) { // if ((scrollState == OnScrollListener.SCROLL_STATE_IDLE) && lastItemIndex == adapter.getCount() + 1) { // if(hasMore) { // loadDataFromBO(); // } else { // Toast.makeText(context, MESSAGE_NO_DATA, Toast.LENGTH_SHORT).show(); // } // } //}
Java
package cn.anlab.anappframe.demo.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import cn.anlab.anappframe.R; public class CActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_intent); Log.i("anlog", "C.onCreate()"); TextView tv = (TextView) findViewById(R.id.textView1); tv.setText("CCCC"); tv.setOnClickListener(this); } @Override protected void onStart() { super.onStart(); Log.i("anlog", "C.onStart()"); } @Override protected void onResume() { super.onResume(); Log.i("anlog", "C.onResume();"); } @Override protected void onStop() { super.onStop(); Log.i("anlog", "C.onStop();"); } @Override protected void onPause() { super.onPause(); Log.i("anlog", "C.onPause();"); } @Override protected void onDestroy() { super.onDestroy(); Log.i("anlog", "C.onDestroy();"); } @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(this, DActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
Java
package cn.anlab.anappframe.demo.activity; import android.app.Activity; import android.os.Bundle; public class AlertDialogThemeDemoActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
Java
package cn.anlab.anappframe.demo.activity; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import cn.anlab.anappframe.BaseActivity; import cn.anlab.anappframe.R; import cn.anlab.anappframe.util.ViewUtil; public class DimensActivity extends BaseActivity { private LinearLayout container; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_dimens); container = (LinearLayout) findViewById(R.id.linearLayout1); TextView tv; for(int i = 5; i < 30; i ++) { tv = new TextView(this); tv.setText(i + "dip : " + "Hello World. 你好,世界!"); tv.setTextSize(ViewUtil.dip2px(this, i)); container.addView(tv); } } }
Java
package cn.anlab.anappframe.demo.activity; import android.app.ActivityGroup; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ScrollView; import cn.anlab.anappframe.R; public class ActivityGroupDemoActivity extends ActivityGroup implements OnClickListener { ScrollView sv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group); Button btn1 = (Button) findViewById(R.id.button1); Button btn2 = (Button) findViewById(R.id.button2); Button btn3 = (Button) findViewById(R.id.button3); btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); sv = (ScrollView) findViewById(R.id.container); } @Override public void onClick(View v) { sv.removeAllViews(); Intent intent; Window win; View view; switch (v.getId()) { case R.id.button1: intent = new Intent(ActivityGroupDemoActivity.this, DimensActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); win = getLocalActivityManager().startActivity("Module1", intent); view = win.getDecorView(); sv.addView(view); break; case R.id.button2: intent = new Intent(ActivityGroupDemoActivity.this, ChatDemoActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); win = getLocalActivityManager().startActivity("Module2", intent); view = win.getDecorView(); sv.addView(view); break; case R.id.button3: intent = new Intent(ActivityGroupDemoActivity.this, ListViewDemoActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); win = getLocalActivityManager().startActivity("Module2", intent); view = win.getDecorView(); sv.addView(view); break; } } }
Java
package cn.anlab.anappframe.demo.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import cn.anlab.anappframe.R; public class BActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_intent); Log.i("anlog", "B.onCreate()"); TextView tv = (TextView) findViewById(R.id.textView1); tv.setText("BBBB"); tv.setOnClickListener(this); } @Override protected void onStart() { super.onStart(); Log.i("anlog", "B.onStart()"); } @Override protected void onResume() { super.onResume(); Log.i("anlog", "B.onResume();"); } @Override protected void onStop() { super.onStop(); Log.i("anlog", "B.onStop();"); } @Override protected void onPause() { super.onPause(); Log.i("anlog", "B.onPause();"); } @Override protected void onDestroy() { super.onDestroy(); Log.i("anlog", "B.onDestroy();"); } @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(this, AActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
Java
package cn.anlab.anappframe.demo.activity; import java.util.Arrays; import java.util.LinkedList; import android.app.ListActivity; import android.os.AsyncTask; import android.os.Bundle; import android.widget.ArrayAdapter; import cn.anlab.anappframe.R; import cn.anlab.anappframe.widget.PullToRefreshListView; import cn.anlab.anappframe.widget.PullToRefreshListView.OnRefreshListener; public class PullToRefreshListViewDemoActivity extends ListActivity { private LinkedList<String> mListItems; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pull_to_refresh); // Set a listener to be invoked when the list should be refreshed. ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { // Do work to refresh the list here. new GetDataTask().execute(); } }); mListItems = new LinkedList<String>(); mListItems.addAll(Arrays.asList(mStrings)); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems); setListAdapter(adapter); } private class GetDataTask extends AsyncTask<Void, Void, String[]> { @Override protected String[] doInBackground(Void... params) { // Simulates a background job. try { Thread.sleep(2000); } catch (InterruptedException e) { ; } return mStrings; } @Override protected void onPostExecute(String[] result) { mListItems.addFirst("Added after refresh..."); // Call onRefreshComplete when the list has been refreshed. ((PullToRefreshListView) getListView()).onRefreshComplete(); super.onPostExecute(result); } } private String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre", "Allgauer Emmentaler"}; }
Java
package com.gallery; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuffXfermode; import android.graphics.Bitmap.Config; import android.graphics.PorterDuff.Mode; import android.graphics.Shader.TileMode; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ImageView.ScaleType; public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; private Integer[] mImageIds; private ImageView[] mImages; public ImageAdapter(Context c, Integer[] ImageIds) { mContext = c; mImageIds = ImageIds; mImages = new ImageView[mImageIds.length]; } public boolean createReflectedImages() { final int reflectionGap = 4; int index = 0; for (int imageId : mImageIds) { Bitmap originalImage = BitmapFactory.decodeResource(mContext .getResources(), imageId); int width = originalImage.getWidth(); int height = originalImage.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width, height / 2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(originalImage, 0, 0, null); Paint deafaultPaint = new Paint(); canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, originalImage .getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); ImageView imageView = new ImageView(mContext); imageView.setImageBitmap(bitmapWithReflection); imageView.setLayoutParams(new GalleryFlow.LayoutParams(180, 240)); // imageView.setScaleType(ScaleType.MATRIX); mImages[index++] = imageView; } return true; } private Resources getResources() { // TODO Auto-generated method stub return null; } public int getCount() { return mImageIds.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { return mImages[position]; } public float getScale(boolean focused, int offset) { return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset))); } }
Java
package com.gallery; import android.app.Activity; import android.os.Bundle; import cn.anlab.anappframe.R; public class ActivityMain extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_gallery); Integer[] images = { R.drawable.img0001, R.drawable.img0030, R.drawable.img0100, R.drawable.img0130, R.drawable.img0200, R.drawable.img0230, R.drawable.img0300, R.drawable.img0330, R.drawable.img0354 }; ImageAdapter adapter = new ImageAdapter(this, images); adapter.createReflectedImages(); GalleryFlow galleryFlow = (GalleryFlow) findViewById(R.id.Gallery01); galleryFlow.setAdapter(adapter); } }
Java
package cn.anlab.anappframe.net; public interface IOErrorListener { public static final int CONNECT_TIMEOUT = 1; public static final int IO_EXCEPTION = 2; public void onError(int ErrorType, Exception e); }
Java
package cn.anlab.anappframe.net; import java.net.InetSocketAddress; public interface ReceiveCallback<P> { public void onReceive(InetSocketAddress from, P p); }
Java
package cn.anlab.anappframe.util; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; public class JsonUtil { private static final SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static final char TYPE_LEFT_BRACE='{'; public static final char TYPE_RIGHT_BRACE='}'; public static final char TYPE_LEFT_SQUARE='['; public static final char TYPE_RIGHT_SQUARE=']'; public static final char TYPE_COMMA=','; public static final char TYPE_COLON=':'; public static final String toJSONString(Object v) { if(v==null) return "null"; StringBuffer sb=new StringBuffer(); write(sb,v); return sb.toString(); } static class Point { int p; } private static final void writeMap(StringBuffer sb,Map v) { if(v==null) { sb.append("null"); return; } int i=0; int size=v.size(); Set<Entry> entrys=v.entrySet(); sb.append(TYPE_LEFT_BRACE); for(Entry e:entrys) { i++; Object key=e.getKey(); Object var=e.getValue(); write(sb,key); sb.append(TYPE_COLON); write(sb,var); if(i<size) { sb.append(TYPE_COMMA); } } sb.append(TYPE_RIGHT_BRACE); } private static final void writeObject(StringBuffer sb,Object v) { if(v!=null) { Class c=v.getClass(); Field[] fields=c.getDeclaredFields(); Map<Object,Object> kv=new LinkedHashMap<Object,Object>(); for(Field field:fields) { int modifierType=field.getModifiers(); if(!Modifier.isStatic(modifierType)&&Modifier.isPublic(modifierType)) { try { Object key=field.getName(); Object var=field.get(v); if(var!=null) { kv.put(key,var); } } catch(IllegalArgumentException e) { e.printStackTrace(); } catch(IllegalAccessException e) { e.printStackTrace(); } } } Method[] ma=c.getDeclaredMethods(); try { for(int i=0;i<ma.length;i++) { Method m=ma[i]; int modifierType=m.getModifiers(); Class<?>[] ptypes=m.getParameterTypes(); if(ptypes.length==0) { if(!Modifier.isStatic(modifierType)&&Modifier.isPublic(modifierType)) { if(m.getName().startsWith("get")) { String name=lowerFirstChar(m.getName().substring(3)); if(!kv.containsKey(name)) { Object value=m.invoke(v,new Object[]{}); kv.put(name,value); } } else if(m.getName().startsWith("is")) { String name=lowerFirstChar(m.getName().substring(2)); if(!kv.containsKey(name)) { Object value=m.invoke(v,new Object[]{}); kv.put(name,value); } } } } } } catch(Exception e) { e.printStackTrace(); } if(kv.size()>0) { write(sb,kv); } } } public static String lowerFirstChar(String str) { if(str==null) { return null; } char[] ca=str.toCharArray(); ca[0]=Character.toLowerCase(ca[0]); return new String(ca); } private static final void writeList(StringBuffer sb,List v) { if(v==null) { sb.append("null"); return; } int size=v.size(); sb.append(TYPE_LEFT_SQUARE); for(int i=0;i<size;i++) { Object obj=v.get(i); write(sb,obj); if(i<size-1) { sb.append(TYPE_COMMA); } } sb.append(TYPE_RIGHT_SQUARE); } private static final void writeArray(StringBuffer sb,Object[] v) { if(v==null) { sb.append("null"); return; } int size=v.length; sb.append(TYPE_LEFT_SQUARE); for(int i=0;i<size;i++) { Object obj=v[i]; write(sb,obj); if(i<size-1) { sb.append(TYPE_COMMA); } } sb.append(TYPE_RIGHT_SQUARE); } private static final void write(StringBuffer sb,Object obj) { if(obj==null) { sb.append("null"); } else if(obj instanceof Boolean) { sb.append(((Boolean)obj).booleanValue()); } else if(obj instanceof Integer) { sb.append(((Integer)obj).intValue()); } else if(obj instanceof String) { String s=(String)obj; s=s.replace("\\","\\\\"); s=s.replace("\"","\\\""); s=s.replace("/","\\/"); s=s.replace("\b","\\b"); s=s.replace("\f","\\f"); s=s.replace("\n","\\n"); s=s.replace("\r","\\r"); s=s.replace("\t","\\t"); sb.append("\"").append(s).append("\""); } else if(obj instanceof List) { writeList(sb,((List)obj)); } else if(obj instanceof Map) { writeMap(sb,((Map)obj)); } else if(obj instanceof Byte) { sb.append(((Byte)obj).byteValue()); } else if(obj instanceof Short) { sb.append(((Short)obj).shortValue()); } else if(obj instanceof Long) { sb.append(((Long)obj).longValue()); } else if(obj instanceof Float) { sb.append(((Float)obj).floatValue()); } else if(obj instanceof Double) { sb.append(((Double)obj).doubleValue()); } else if(obj instanceof Date) { Date d=(Date)obj; sb.append("\"").append(myFmt.format(d)).append("\""); } else if(obj.getClass().isArray()) { writeArray(sb,(Object[])obj); } else { writeObject(sb,obj); } } private static class KV { boolean inString=false; boolean isEmpty=true; public static final int STEP_KEY=0; public static final int STEP_VALUE=1; public static final int V_STRING=0; public static final int V_LIST=1; public static final int V_MAP=2; public int step=STEP_KEY; public int vType=V_STRING; public StringBuffer key=new StringBuffer(); public StringBuffer vStr=new StringBuffer(); public List vList=new ArrayList(); public Map vMap=new HashMap(); public void append(char c) { isEmpty=false; if(step==STEP_KEY) { key.append(c); } else if(step==STEP_VALUE&&vType==V_STRING) { vStr.append(c); } } public void putTo(Map map) { if(isEmpty) return; String k=key.toString(); if(vType==V_STRING) { String v=vStr.toString(); map.put(toObject(k),toObject(v)); } else if(vType==V_LIST) { map.put(toObject(k),vList); } else if(vType==V_MAP) { map.put(toObject(k),vMap); } } public String toString() { if(vType==V_STRING) { return TYPE_LEFT_SQUARE+key.toString()+TYPE_COLON+vStr.toString()+TYPE_RIGHT_SQUARE; } else if(vType==V_LIST) { return TYPE_LEFT_SQUARE+key.toString()+TYPE_COLON+vList+TYPE_RIGHT_SQUARE; } else if(vType==V_MAP) { return TYPE_LEFT_SQUARE+key.toString()+TYPE_COLON+vMap+TYPE_RIGHT_SQUARE; } return ""; } } private static KV newKV() { return new KV(); } private static final Object toObject(String s) { if(s==null) return s; s=s.trim(); if(s.length() == 0) return s; if(s.contains("null")) return null; char b1=s.charAt(0); char b2=s.charAt(s.length()-1); if(b1=='\"'&&b2=='\"') { s=s.substring(1,s.length()-1); s=s.replace("\\\"","\""); s=s.replace("\\/","/"); s=s.replace("\\b","\b"); s=s.replace("\\f","\f"); s=s.replace("\\n","\n"); s=s.replace("\\r","\r"); s=s.replace("\\t","\t"); s=s.replace("\\\\","\\"); return s; } else { try { return Integer.parseInt(s); } catch(Exception e1) { try { return Long.parseLong(s); } catch(Exception e2) { try { return Double.parseDouble(s); } catch(Exception e3) { try { if(s.toLowerCase().equals("true")) return true; else if(s.toLowerCase().equals("false")) return false; throw new Exception(); } catch(Exception e) { } } } } } return s; } public static final Object parse(String s) { if(s==null||s.length() == 0) throw new RuntimeException("s isEmpty!!"); Point p=new Point(); if(s.charAt(0)==TYPE_LEFT_BRACE) { return parseMap(s,p); } else if(s.charAt(0)==TYPE_LEFT_SQUARE) { return parseList(s,p); } throw new RuntimeException("No Support."); } private static final List parseList(String s,Point p) { if(s==null||s.length() == 0) throw new RuntimeException("s isEmpty!!"); boolean F=true; boolean isObject=false; List list=new ArrayList(); boolean inString=false; StringBuffer buff=new StringBuffer(); int length=s.length(); for(;p.p<length;p.p++) { char c=s.charAt(p.p); if(c==TYPE_LEFT_SQUARE&&!inString) { if(F) { F=false; } else { List list2=parseList(s,p); list.add(list2); } } else if(c==TYPE_RIGHT_SQUARE&&!inString) { if(buff.length()>0) { String str=buff.toString(); list.add(toObject(str)); p.p++; } return list; } else if(c==TYPE_COMMA&&!inString) { String str=buff.toString(); if(isObject&&str.isEmpty()) { isObject=false; } else { list.add(toObject(str)); buff=new StringBuffer(); } } else if(c==TYPE_LEFT_BRACE&&!inString) { Map map=parseMap(s,p); list.add(map); isObject=true; buff=new StringBuffer(); } else if(c=='\r'||c=='\n') { continue; } else { if(c=='\"') inString=!inString; buff.append(c); } } return list; } private static final Map parseMap(String s,Point p) { if(s==null||s.length() == 0) throw new RuntimeException("s isEmpty!!"); boolean F=true; Map map=new HashMap(); KV kv=newKV(); int length=s.length(); for(;p.p<length;p.p++) { char c=s.charAt(p.p); if(c==TYPE_LEFT_BRACE&&!kv.inString) { if(F) { F=false; } else { kv.vType=KV.V_MAP; kv.vMap=parseMap(s,p); kv.putTo(map); kv=newKV(); } } else if(c==TYPE_RIGHT_BRACE&&!kv.inString) { kv.putTo(map); return map; } else if(c==TYPE_COLON&&!kv.inString) { kv.step=KV.STEP_VALUE; } else if(c==TYPE_COMMA&&!kv.inString) { kv.putTo(map); kv=newKV(); } else if(c==TYPE_LEFT_SQUARE&&!kv.inString) { kv.vType=KV.V_LIST; kv.vList=parseList(s,p); kv.putTo(map); kv=newKV(); } else if(c=='\r'||c=='\n') { continue; } else { if(c=='\"') kv.inString=!kv.inString; if(kv.step==KV.STEP_KEY) { kv.append(c); } else if(kv.step==KV.STEP_VALUE) { kv.append(c); } } } return map; } }
Java
package cn.anlab.anappframe.util; public class Log { public static void i(String tag, String info) { System.out.println("[i]" + tag + " : " + info); } public static void d(String tag, String info) { System.out.println("[d]" + tag + " : " + info); } public static void w(String tag, String info) { System.out.println("[w]" + tag + " : " + info); } public static void e(String tag, String info) { System.out.println("[e]" + tag + " : " + info); } public static void e(String tag, String info, Throwable e) { System.out.println("[e]" + tag + " : " + info + " e : " + e); e.printStackTrace(); } }
Java
package cn.anlab.anappframe.net; public interface IOErrorListener { public static final int CONNECT_TIMEOUT = 1; public static final int IO_EXCEPTION = 2; public void onError(int ErrorType, Exception e); }
Java
package cn.anlab.anappframe; import java.io.IOException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import cn.anlab.anappframe.net.IOErrorListener; import cn.anlab.anappframe.net.IOServer; import cn.anlab.anappframe.net.JsonIOHandler; import cn.anlab.anappframe.net.Packet; import cn.anlab.anappframe.net.ReceiveCallback; import cn.anlab.anappframe.util.Log; public class Test { public static void main(String[] args) throws IOException { final IOServer server = new IOServer(); server.setHandler(new JsonIOHandler()); server.setIoErrorListener(new IOErrorListener() { @Override public void onError(int ErrorType, Exception e) { Log.e("anlog", "exception : " + e.getMessage()); } }); server.setReceiveCallback(new ReceiveCallback<Packet>() { @Override public void onReceive(InetSocketAddress from, Packet p) { Log.e("anlog", "packet : " + p.toString()); Map m = new HashMap(); m.put("msg", "Hello Boy."); m.put("userKey", "123456"); Packet pp = new Packet(20120011, m); server.send(from, pp); } }); server.start(); } }
Java
package cn.anlab.anappframe.util; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; public class JsonUtil { private static final SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static final char TYPE_LEFT_BRACE='{'; public static final char TYPE_RIGHT_BRACE='}'; public static final char TYPE_LEFT_SQUARE='['; public static final char TYPE_RIGHT_SQUARE=']'; public static final char TYPE_COMMA=','; public static final char TYPE_COLON=':'; public static final String toJSONString(Object v) { if(v==null) return "null"; StringBuffer sb=new StringBuffer(); write(sb,v); return sb.toString(); } static class Point { int p; } private static final void writeMap(StringBuffer sb,Map v) { if(v==null) { sb.append("null"); return; } int i=0; int size=v.size(); Set<Entry> entrys=v.entrySet(); sb.append(TYPE_LEFT_BRACE); for(Entry e:entrys) { i++; Object key=e.getKey(); Object var=e.getValue(); write(sb,key); sb.append(TYPE_COLON); write(sb,var); if(i<size) { sb.append(TYPE_COMMA); } } sb.append(TYPE_RIGHT_BRACE); } private static final void writeObject(StringBuffer sb,Object v) { if(v!=null) { Class c=v.getClass(); Field[] fields=c.getDeclaredFields(); Map<Object,Object> kv=new LinkedHashMap<Object,Object>(); for(Field field:fields) { int modifierType=field.getModifiers(); if(!Modifier.isStatic(modifierType)&&Modifier.isPublic(modifierType)) { try { Object key=field.getName(); Object var=field.get(v); if(var!=null) { kv.put(key,var); } } catch(IllegalArgumentException e) { e.printStackTrace(); } catch(IllegalAccessException e) { e.printStackTrace(); } } } Method[] ma=c.getDeclaredMethods(); try { for(int i=0;i<ma.length;i++) { Method m=ma[i]; int modifierType=m.getModifiers(); Class<?>[] ptypes=m.getParameterTypes(); if(ptypes.length==0) { if(!Modifier.isStatic(modifierType)&&Modifier.isPublic(modifierType)) { if(m.getName().startsWith("get")) { String name=lowerFirstChar(m.getName().substring(3)); if(!kv.containsKey(name)) { Object value=m.invoke(v,new Object[]{}); kv.put(name,value); } } else if(m.getName().startsWith("is")) { String name=lowerFirstChar(m.getName().substring(2)); if(!kv.containsKey(name)) { Object value=m.invoke(v,new Object[]{}); kv.put(name,value); } } } } } } catch(Exception e) { e.printStackTrace(); } if(kv.size()>0) { write(sb,kv); } } } public static String lowerFirstChar(String str) { if(str==null) { return null; } char[] ca=str.toCharArray(); ca[0]=Character.toLowerCase(ca[0]); return new String(ca); } private static final void writeList(StringBuffer sb,List v) { if(v==null) { sb.append("null"); return; } int size=v.size(); sb.append(TYPE_LEFT_SQUARE); for(int i=0;i<size;i++) { Object obj=v.get(i); write(sb,obj); if(i<size-1) { sb.append(TYPE_COMMA); } } sb.append(TYPE_RIGHT_SQUARE); } private static final void writeArray(StringBuffer sb,Object[] v) { if(v==null) { sb.append("null"); return; } int size=v.length; sb.append(TYPE_LEFT_SQUARE); for(int i=0;i<size;i++) { Object obj=v[i]; write(sb,obj); if(i<size-1) { sb.append(TYPE_COMMA); } } sb.append(TYPE_RIGHT_SQUARE); } private static final void write(StringBuffer sb,Object obj) { if(obj==null) { sb.append("null"); } else if(obj instanceof Boolean) { sb.append(((Boolean)obj).booleanValue()); } else if(obj instanceof Integer) { sb.append(((Integer)obj).intValue()); } else if(obj instanceof String) { String s=(String)obj; s=s.replace("\\","\\\\"); s=s.replace("\"","\\\""); s=s.replace("/","\\/"); s=s.replace("\b","\\b"); s=s.replace("\f","\\f"); s=s.replace("\n","\\n"); s=s.replace("\r","\\r"); s=s.replace("\t","\\t"); sb.append("\"").append(s).append("\""); } else if(obj instanceof List) { writeList(sb,((List)obj)); } else if(obj instanceof Map) { writeMap(sb,((Map)obj)); } else if(obj instanceof Byte) { sb.append(((Byte)obj).byteValue()); } else if(obj instanceof Short) { sb.append(((Short)obj).shortValue()); } else if(obj instanceof Long) { sb.append(((Long)obj).longValue()); } else if(obj instanceof Float) { sb.append(((Float)obj).floatValue()); } else if(obj instanceof Double) { sb.append(((Double)obj).doubleValue()); } else if(obj instanceof Date) { Date d=(Date)obj; sb.append("\"").append(myFmt.format(d)).append("\""); } else if(obj.getClass().isArray()) { writeArray(sb,(Object[])obj); } else { writeObject(sb,obj); } } private static class KV { boolean inString=false; boolean isEmpty=true; public static final int STEP_KEY=0; public static final int STEP_VALUE=1; public static final int V_STRING=0; public static final int V_LIST=1; public static final int V_MAP=2; public int step=STEP_KEY; public int vType=V_STRING; public StringBuffer key=new StringBuffer(); public StringBuffer vStr=new StringBuffer(); public List vList=new ArrayList(); public Map vMap=new HashMap(); public void append(char c) { isEmpty=false; if(step==STEP_KEY) { key.append(c); } else if(step==STEP_VALUE&&vType==V_STRING) { vStr.append(c); } } public void putTo(Map map) { if(isEmpty) return; String k=key.toString(); if(vType==V_STRING) { String v=vStr.toString(); map.put(toObject(k),toObject(v)); } else if(vType==V_LIST) { map.put(toObject(k),vList); } else if(vType==V_MAP) { map.put(toObject(k),vMap); } } public String toString() { if(vType==V_STRING) { return TYPE_LEFT_SQUARE+key.toString()+TYPE_COLON+vStr.toString()+TYPE_RIGHT_SQUARE; } else if(vType==V_LIST) { return TYPE_LEFT_SQUARE+key.toString()+TYPE_COLON+vList+TYPE_RIGHT_SQUARE; } else if(vType==V_MAP) { return TYPE_LEFT_SQUARE+key.toString()+TYPE_COLON+vMap+TYPE_RIGHT_SQUARE; } return ""; } } private static KV newKV() { return new KV(); } private static final Object toObject(String s) { if(s==null) return s; s=s.trim(); if(s.length() == 0) return s; if(s.contains("null")) return null; char b1=s.charAt(0); char b2=s.charAt(s.length()-1); if(b1=='\"'&&b2=='\"') { s=s.substring(1,s.length()-1); s=s.replace("\\\"","\""); s=s.replace("\\/","/"); s=s.replace("\\b","\b"); s=s.replace("\\f","\f"); s=s.replace("\\n","\n"); s=s.replace("\\r","\r"); s=s.replace("\\t","\t"); s=s.replace("\\\\","\\"); return s; } else { try { return Integer.parseInt(s); } catch(Exception e1) { try { return Long.parseLong(s); } catch(Exception e2) { try { return Double.parseDouble(s); } catch(Exception e3) { try { if(s.toLowerCase().equals("true")) return true; else if(s.toLowerCase().equals("false")) return false; throw new Exception(); } catch(Exception e) { } } } } } return s; } public static final Object parse(String s) { if(s==null||s.length() == 0) throw new RuntimeException("s isEmpty!!"); Point p=new Point(); if(s.charAt(0)==TYPE_LEFT_BRACE) { return parseMap(s,p); } else if(s.charAt(0)==TYPE_LEFT_SQUARE) { return parseList(s,p); } throw new RuntimeException("No Support."); } private static final List parseList(String s,Point p) { if(s==null||s.length() == 0) throw new RuntimeException("s isEmpty!!"); boolean F=true; boolean isObject=false; List list=new ArrayList(); boolean inString=false; StringBuffer buff=new StringBuffer(); int length=s.length(); for(;p.p<length;p.p++) { char c=s.charAt(p.p); if(c==TYPE_LEFT_SQUARE&&!inString) { if(F) { F=false; } else { List list2=parseList(s,p); list.add(list2); } } else if(c==TYPE_RIGHT_SQUARE&&!inString) { if(buff.length()>0) { String str=buff.toString(); list.add(toObject(str)); p.p++; } return list; } else if(c==TYPE_COMMA&&!inString) { String str=buff.toString(); if(isObject&&str.isEmpty()) { isObject=false; } else { list.add(toObject(str)); buff=new StringBuffer(); } } else if(c==TYPE_LEFT_BRACE&&!inString) { Map map=parseMap(s,p); list.add(map); isObject=true; buff=new StringBuffer(); } else if(c=='\r'||c=='\n') { continue; } else { if(c=='\"') inString=!inString; buff.append(c); } } return list; } private static final Map parseMap(String s,Point p) { if(s==null||s.length() == 0) throw new RuntimeException("s isEmpty!!"); boolean F=true; Map map=new HashMap(); KV kv=newKV(); int length=s.length(); for(;p.p<length;p.p++) { char c=s.charAt(p.p); if(c==TYPE_LEFT_BRACE&&!kv.inString) { if(F) { F=false; } else { kv.vType=KV.V_MAP; kv.vMap=parseMap(s,p); kv.putTo(map); kv=newKV(); } } else if(c==TYPE_RIGHT_BRACE&&!kv.inString) { kv.putTo(map); return map; } else if(c==TYPE_COLON&&!kv.inString) { kv.step=KV.STEP_VALUE; } else if(c==TYPE_COMMA&&!kv.inString) { kv.putTo(map); kv=newKV(); } else if(c==TYPE_LEFT_SQUARE&&!kv.inString) { kv.vType=KV.V_LIST; kv.vList=parseList(s,p); kv.putTo(map); kv=newKV(); } else if(c=='\r'||c=='\n') { continue; } else { if(c=='\"') kv.inString=!kv.inString; if(kv.step==KV.STEP_KEY) { kv.append(c); } else if(kv.step==KV.STEP_VALUE) { kv.append(c); } } } return map; } }
Java
package cn.anlab.anappframe.util; public class Log { public static void i(String tag, String info) { System.out.println("[i]" + tag + " : " + info); } public static void d(String tag, String info) { System.out.println("[d]" + tag + " : " + info); } public static void w(String tag, String info) { System.out.println("[w]" + tag + " : " + info); } public static void e(String tag, String info) { System.out.println("[e]" + tag + " : " + info); } }
Java
// Copyright 2012 Google Inc. All Rights Reserved. package com.example.android.notepad; import android.app.Service; import android.content.Intent; import android.os.IBinder; /** * Service for the DriveSyncAdapter. */ public class DriveSyncService extends Service { private static final Object sSyncAdapterLock = new Object(); private static DriveSyncAdapter sSyncAdapter = null; @Override public void onCreate() { synchronized (sSyncAdapterLock) { if (sSyncAdapter == null) { sSyncAdapter = new DriveSyncAdapter(getApplicationContext(), true); } } } @Override public IBinder onBind(Intent intent) { return sSyncAdapter.getSyncAdapterBinder(); } }
Java
/* * Copyright (C) 2007 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.example.android.notepad; import android.net.Uri; import android.provider.BaseColumns; /** * Defines a contract between the Note Pad content provider and its clients. A * contract defines the information that a client needs to access the provider * as one or more data tables. A contract is a public, non-extendable (final) * class that contains constants defining column names and URIs. A well-written * client depends only on the constants in the contract. */ public final class AndroidDrivePad { public static final String AUTHORITY = "docs.google.com"; // This class cannot be instantiated private AndroidDrivePad() { } /** * Notes table contract */ public static final class Notes implements BaseColumns { // This class cannot be instantiated private Notes() { } /** * The table name offered by this provider */ public static final String TABLE_NAME = "notes"; /* * URI definitions */ /** * The scheme part for this provider's URI */ private static final String SCHEME = "https://"; /** * Path parts for the URIs */ /** * Path part for the Notes URI */ private static final String PATH_NOTES = "/feeds/default/private/full"; /** * Path part for the Note ID URI */ private static final String PATH_NOTE_ID = "/"; /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_NOTES); /** * The content URI base for a single note. Callers must append a numeric * note id to this Uri to retrieve a note */ public static final Uri CONTENT_ID_URI_BASE = Uri.parse(SCHEME + AUTHORITY + PATH_NOTE_ID); /** * The content URI match pattern for a single note, specified by its ID. Use * this to match incoming URIs or to construct an Intent. */ public static final Uri CONTENT_ID_URI_PATTERN = Uri.parse(SCHEME + AUTHORITY + PATH_NOTE_ID + "*"); /* * MIME type definitions */ /** * The MIME type of {@link #CONTENT_URI} providing a directory of notes. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note"; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single note. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.note"; /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "modified DESC"; /* * Column definitions */ /** * Column name for the title of the note * <P> * Type: TEXT * </P> */ public static final String COLUMN_NAME_TITLE = "title"; /** * Column name of the note content * <P> * Type: TEXT * </P> */ public static final String COLUMN_NAME_NOTE = "note"; /** * Column name for the creation timestamp * <P> * Type: INTEGER (long from System.curentTimeMillis()) * </P> */ public static final String COLUMN_NAME_CREATE_DATE = "created"; /** * Column name for the modification timestamp * <P> * Type: INTEGER (long from System.curentTimeMillis()) * </P> */ public static final String COLUMN_NAME_MODIFICATION_DATE = "modified"; } }
Java
/* * Copyright (C) 2007 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.example.android.notepad; import android.content.ClipDescription; import android.content.ContentProvider; import android.content.ContentProvider.PipeDataWriter; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.content.res.AssetFileDescriptor; import android.content.res.Resources; 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.os.Bundle; import android.os.ParcelFileDescriptor; import android.text.TextUtils; import android.util.Log; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.HashMap; /** * Provides access to a database of notes. Each note has a title, the note * itself, a creation date and a modified data. */ public class NotePadProvider extends ContentProvider implements PipeDataWriter<Cursor> { // Used for debugging and logging private static final String TAG = "NotePadProvider"; /** * The database that the provider uses as its underlying data store */ private static final String DATABASE_NAME = "note_pad.db"; /** * The database version */ private static final int DATABASE_VERSION = 4; /** * A projection map used to select columns from the database */ private static HashMap<String, String> sNotesProjectionMap; /** * Standard projection for the interesting columns of a normal note. */ private static final String[] READ_NOTE_PROJECTION = new String[] { NotePad.Notes.COLUMN_NAME_NOTE, NotePad.Notes.COLUMN_NAME_TITLE}; private static final int READ_NOTE_NOTE_INDEX = 0; private static final int READ_NOTE_TITLE_INDEX = 1; /* * Constants used by the Uri matcher to choose an action based on the pattern * of the incoming URI */ // The incoming URI matches the Notes URI pattern private static final int NOTES = 1; // The incoming URI matches the Note ID URI pattern private static final int NOTE_ID = 2; // The incoming URI matches the Note File ID URI pattern private static final int FILE_ID = 3; /** * A UriMatcher instance */ private static final UriMatcher sUriMatcher; // Handle to a new DatabaseHelper. private DatabaseHelper mOpenHelper; /** * A block that instantiates and sets static objects */ static { /* * Creates and initializes the URI matcher */ // Create a new instance sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); // Add a pattern that routes URIs terminated with "notes" to a NOTES // operation sUriMatcher.addURI(NotePad.AUTHORITY, "*/notes", NOTES); // Add a pattern that routes URIs terminated with "notes" plus an integer // to a note ID operation sUriMatcher.addURI(NotePad.AUTHORITY, "*/notes/#", NOTE_ID); // Add a pattern that routes URIs terminated with "files" plus an ID // to a file ID operation sUriMatcher.addURI(NotePad.AUTHORITY, "*/files/*", FILE_ID); /* * Creates and initializes a projection map that returns all columns */ // Creates a new projection map instance. The map returns a column name // given a string. The two are usually equal. sNotesProjectionMap = new HashMap<String, String>(); // Maps the string "_ID" to the column name "_ID" sNotesProjectionMap.put(NotePad.Notes._ID, NotePad.Notes._ID); // Maps "title" to "title" sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_TITLE, NotePad.Notes.COLUMN_NAME_TITLE); // Maps "note" to "note" sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_NOTE, NotePad.Notes.COLUMN_NAME_NOTE); // Maps "created" to "created" sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_CREATE_DATE, NotePad.Notes.COLUMN_NAME_CREATE_DATE); // Maps "modified" to "modified" sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE); sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_ACCOUNT, NotePad.Notes.COLUMN_NAME_ACCOUNT); sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_FILE_ID, NotePad.Notes.COLUMN_NAME_FILE_ID); sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_DELETED, NotePad.Notes.COLUMN_NAME_DELETED); } /** * * This class helps open, create, and upgrade the database file. Set to * package visibility for testing purposes. */ static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { // calls the super constructor, requesting the default cursor factory. super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * * Creates the underlying database with table name and column names taken * from the NotePad class. */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + NotePad.Notes.TABLE_NAME + " (" + NotePad.Notes._ID + " INTEGER PRIMARY KEY," + NotePad.Notes.COLUMN_NAME_TITLE + " TEXT," + NotePad.Notes.COLUMN_NAME_NOTE + " TEXT," + NotePad.Notes.COLUMN_NAME_CREATE_DATE + " INTEGER," + NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " INTEGER," + NotePad.Notes.COLUMN_NAME_FILE_ID + " TEXT," + NotePad.Notes.COLUMN_NAME_ACCOUNT + " TEXT," + NotePad.Notes.COLUMN_NAME_DELETED + " BOOL DEFAULT FALSE" + ");"); } /** * * Demonstrates that the provider must consider what happens when the * underlying datastore is changed. In this sample, the database is upgraded * the database by destroying the existing data. A real application should * upgrade the database in place. */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Logs that the database is being upgraded Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); // Kills the table and existing data db.execSQL("DROP TABLE IF EXISTS notes"); // Recreates the database with a new version onCreate(db); } } /** * Initializes the provider by creating a new DatabaseHelper. onCreate() is * called automatically when Android creates the provider in response to a * resolver request from a client. */ @Override public boolean onCreate() { // Creates a new helper object. Note that the database itself isn't opened // until // something tries to access it, and it's only created if it doesn't already // exist. mOpenHelper = new DatabaseHelper(getContext()); // Assumes that any failures will be reported by a thrown exception. return true; } /** * This method is called when a client calls * {@link android.content.ContentResolver#query(Uri, String[], String, String[], String)} * . Queries the database and returns a cursor containing the results. * * @return A cursor containing the results of the query. The cursor exists but * is empty if the query returns no results or an exception occurs. * @throws IllegalArgumentException if the incoming URI pattern is invalid. */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Constructs a new query builder and sets its table name SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(NotePad.Notes.TABLE_NAME); // Only retrieve notes for the specified account. String where = NotePad.Notes.COLUMN_NAME_ACCOUNT + "=" + "\"" + uri.getPathSegments().get(NotePad.Notes.NOTE_ACCOUNT_PATH_POSITION) + "\""; /** * Choose the projection and adjust the "where" clause based on URI * pattern-matching. */ switch (sUriMatcher.match(uri)) { // If the incoming URI is for notes, chooses the Notes projection case NOTES: qb.setProjectionMap(sNotesProjectionMap); break; /* * If the incoming URI is for a single note identified by its ID, chooses * the note ID projection, and appends "_ID = <noteID>" to the where * clause, so that it selects that single note */ case NOTE_ID: qb.setProjectionMap(sNotesProjectionMap); where += "AND " + NotePad.Notes._ID + // the name of the ID column "=" + // the position of the note ID itself in the incoming URI uri.getPathSegments().get(NotePad.Notes.NOTE_FILE_ID_PATH_POSITION); break; /* * If the incoming URI is for a single note identified by its file ID, * chooses the note ID projection, and appends "fileId = <fileID>" to the * where clause, so that it selects that single note */ case FILE_ID: qb.setProjectionMap(sNotesProjectionMap); where += "AND " + NotePad.Notes.COLUMN_NAME_FILE_ID + // the name of the ID column " = " + // the position of the note ID itself in the incoming URI "\"" + uri.getPathSegments().get(NotePad.Notes.NOTE_FILE_ID_PATH_POSITION) + "\""; break; default: // If the URI doesn't match any of the known patterns, throw an // exception. throw new IllegalArgumentException("Unknown URI " + uri); } qb.appendWhere(where); String orderBy; // If no sort order is specified, uses the default if (TextUtils.isEmpty(sortOrder)) { orderBy = NotePad.Notes.DEFAULT_SORT_ORDER; } else { // otherwise, uses the incoming sort order orderBy = sortOrder; } // Opens the database object in "read" mode, since no writes need to be // done. SQLiteDatabase db = mOpenHelper.getReadableDatabase(); /* * Performs the query. If no problems occur trying to read the database, * then a Cursor object is returned; otherwise, the cursor variable contains * null. If no records were selected, then the Cursor object is empty, and * Cursor.getCount() returns 0. */ Cursor c = qb.query(db, // The database to query projection, // The columns to return from the query selection, // The columns for the where clause selectionArgs, // The values for the where clause null, // don't group the rows null, // don't filter by row groups orderBy // The sort order ); // Tells the Cursor what URI to watch, so it knows when its source data // changes c.setNotificationUri(getContext().getContentResolver(), uri); return c; } /** * This is called when a client calls * {@link android.content.ContentResolver#getType(Uri)}. Returns the MIME data * type of the URI given as a parameter. * * @param uri The URI whose MIME type is desired. * @return The MIME type of the URI. * @throws IllegalArgumentException if the incoming URI pattern is invalid. */ @Override public String getType(Uri uri) { /** * Chooses the MIME type based on the incoming URI pattern */ switch (sUriMatcher.match(uri)) { // If the pattern is for notes or live folders, returns the general content // type. case NOTES: return NotePad.Notes.CONTENT_TYPE; // If the pattern is for note IDs, returns the note ID content type. case NOTE_ID: return NotePad.Notes.CONTENT_ITEM_TYPE; // If the URI pattern doesn't match any permitted patterns, throws an // exception. default: throw new IllegalArgumentException("Unknown URI " + uri); } } /** * This describes the MIME types that are supported for opening a note URI as * a stream. */ static ClipDescription NOTE_STREAM_TYPES = new ClipDescription(null, new String[] {ClipDescription.MIMETYPE_TEXT_PLAIN}); /** * Returns the types of available data streams. URIs to specific notes are * supported. The application can convert such a note to a plain text stream. * * @param uri the URI to analyze * @param mimeTypeFilter The MIME type to check for. This method only returns * a data stream type for MIME types that match the filter. Currently, * only text/plain MIME types match. * @return a data stream MIME type. Currently, only text/plan is returned. * @throws IllegalArgumentException if the URI pattern doesn't match any * supported patterns. */ @Override public String[] getStreamTypes(Uri uri, String mimeTypeFilter) { /** * Chooses the data stream type based on the incoming URI pattern. */ switch (sUriMatcher.match(uri)) { // If the pattern is for notes or live folders, return null. Data streams // are not // supported for this type of URI. case NOTES: return null; // If the pattern is for note IDs and the MIME filter is text/plain, // then return // text/plain case NOTE_ID: return NOTE_STREAM_TYPES.filterMimeTypes(mimeTypeFilter); // If the URI pattern doesn't match any permitted patterns, throws an // exception. default: throw new IllegalArgumentException("Unknown URI " + uri); } } /** * Returns a stream of data for each supported stream type. This method does a * query on the incoming URI, then uses * {@link android.content.ContentProvider#openPipeHelper(Uri, String, Bundle, Object, PipeDataWriter)} * to start another thread in which to convert the data into a stream. * * @param uri The URI pattern that points to the data stream * @param mimeTypeFilter A String containing a MIME type. This method tries to * get a stream of data with this MIME type. * @param opts Additional options supplied by the caller. Can be interpreted * as desired by the content provider. * @return AssetFileDescriptor A handle to the file. * @throws FileNotFoundException if there is no file associated with the * incoming URI. */ @Override public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts) throws FileNotFoundException { // Checks to see if the MIME type filter matches a supported MIME type. String[] mimeTypes = getStreamTypes(uri, mimeTypeFilter); // If the MIME type is supported if (mimeTypes != null) { // Retrieves the note for this URI. Uses the query method defined for this // provider, // rather than using the database query method. Cursor c = query(uri, // The URI of a note READ_NOTE_PROJECTION, // Gets a projection containing the note's ID, // title, // and contents null, // No WHERE clause, get all matching records null, // Since there is no WHERE clause, no selection criteria null // Use the default sort order (modification date, // descending ); // If the query fails or the cursor is empty, stop if (c == null || !c.moveToFirst()) { // If the cursor is empty, simply close the cursor and return if (c != null) { c.close(); } // If the cursor is null, throw an exception throw new FileNotFoundException("Unable to query " + uri); } // Start a new thread that pipes the stream data back to the caller. return new AssetFileDescriptor(openPipeHelper(uri, mimeTypes[0], opts, c, this), 0, AssetFileDescriptor.UNKNOWN_LENGTH); } // If the MIME type is not supported, return a read-only handle to the file. return super.openTypedAssetFile(uri, mimeTypeFilter, opts); } /** * Implementation of {@link android.content.ContentProvider.PipeDataWriter} to * perform the actual work of converting the data in one of cursors to a * stream of data for the client to read. */ @Override public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType, Bundle opts, Cursor c) { // We currently only support conversion-to-text from a single note entry, // so no need for cursor data type checking here. FileOutputStream fout = new FileOutputStream(output.getFileDescriptor()); PrintWriter pw = null; try { pw = new PrintWriter(new OutputStreamWriter(fout, "UTF-8")); pw.println(c.getString(READ_NOTE_TITLE_INDEX)); pw.println(""); pw.println(c.getString(READ_NOTE_NOTE_INDEX)); } catch (UnsupportedEncodingException e) { Log.w(TAG, "Ooops", e); } finally { c.close(); if (pw != null) { pw.flush(); } try { fout.close(); } catch (IOException e) { } } } /** * This is called when a client calls * {@link android.content.ContentResolver#insert(Uri, ContentValues)}. Inserts * a new row into the database. This method sets up default values for any * columns that are not included in the incoming map. If rows were inserted, * then listeners are notified of the change. * * @return The row ID of the inserted row. * @throws SQLException if the insertion fails. */ @Override public Uri insert(Uri uri, ContentValues initialValues) { // Validates the incoming URI. Only the full provider URI is allowed for // inserts. if (sUriMatcher.match(uri) != NOTES) { throw new IllegalArgumentException("Unknown URI " + uri); } // A map to hold the new record's values. ContentValues values; // If the incoming values map is not null, uses it for the new values. if (initialValues != null) { values = new ContentValues(initialValues); } else { // Otherwise, create a new value map values = new ContentValues(); } // Gets the current system time in milliseconds Long now = Long.valueOf(System.currentTimeMillis()); // If the values map doesn't contain the creation date, sets the value to // the current time. if (values.containsKey(NotePad.Notes.COLUMN_NAME_CREATE_DATE) == false) { values.put(NotePad.Notes.COLUMN_NAME_CREATE_DATE, now); } // If the values map doesn't contain the modification date, sets the value // to the current // time. if (values.containsKey(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE) == false) { values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, now); } // If the values map doesn't contain a title, sets the value to the default // title. if (values.containsKey(NotePad.Notes.COLUMN_NAME_TITLE) == false) { Resources r = Resources.getSystem(); values.put(NotePad.Notes.COLUMN_NAME_TITLE, r.getString(android.R.string.untitled)); } // If the values map doesn't contain note text, sets the value to an empty // string. if (values.containsKey(NotePad.Notes.COLUMN_NAME_NOTE) == false) { values.put(NotePad.Notes.COLUMN_NAME_NOTE, ""); } // If the values map doesn't contain note text, sets the value to an empty // string. if (values.containsKey(NotePad.Notes.COLUMN_NAME_DELETED) == false) { values.put(NotePad.Notes.COLUMN_NAME_DELETED, 0); } values.put(NotePad.Notes.COLUMN_NAME_ACCOUNT, uri.getPathSegments().get(NotePad.Notes.NOTE_ACCOUNT_PATH_POSITION)); // Opens the database object in "write" mode. SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // Performs the insert and returns the ID of the new note. long rowId = db.insert(NotePad.Notes.TABLE_NAME, // The table to insert // into. NotePad.Notes.COLUMN_NAME_NOTE, // A hack, SQLite sets this column value // to null // if values is empty. values // A map of column names, and the values to insert // into the columns. ); // If the insert succeeded, the row ID exists. if (rowId > 0) { // Creates a URI with the note ID pattern and the new row ID appended to // it. Uri noteUri = ContentUris.withAppendedId(uri, rowId); // Notifies observers registered against this provider that the data // changed. getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } // If the insert didn't succeed, then the rowID is <= 0. Throws an // exception. throw new SQLException("Failed to insert row into " + uri); } /** * This is called when a client calls * {@link android.content.ContentResolver#delete(Uri, String, String[])}. * Deletes records from the database. If the incoming URI matches the note ID * URI pattern, this method deletes the one record specified by the ID in the * URI. Otherwise, it deletes a a set of records. The record or records must * also match the input selection criteria specified by where and whereArgs. * * If rows were deleted, then listeners are notified of the change. * * @return If a "where" clause is used, the number of rows affected is * returned, otherwise 0 is returned. To delete all rows and get a row * count, use "1" as the where clause. * @throws IllegalArgumentException if the incoming URI pattern is invalid. */ @Override public int delete(Uri uri, String where, String[] whereArgs) { // Opens the database object in "write" mode. SQLiteDatabase db = mOpenHelper.getWritableDatabase(); String finalWhere = NotePad.Notes.COLUMN_NAME_ACCOUNT + " = " + "\"" + uri.getPathSegments().get(NotePad.Notes.NOTE_ACCOUNT_PATH_POSITION) + "\""; int count; // Does the delete based on the incoming URI pattern. switch (sUriMatcher.match(uri)) { // If the incoming pattern matches the general pattern for notes, does a // delete based on the incoming "where" columns and arguments. case NOTES: break; // If the incoming URI matches a single note ID, does the delete based on // the incoming data, but modifies the where clause to restrict it to the // particular note ID. case NOTE_ID: /* * Starts a final WHERE clause by restricting it to the desired note ID. */ finalWhere = finalWhere + " AND " + NotePad.Notes._ID + // The ID column name " = " + // test for equality uri.getPathSegments().get(NotePad.Notes.NOTE_FILE_ID_PATH_POSITION); // the incoming note ID break; // If the incoming URI matches a single file ID, does the delete based on // the incoming data, but modifies the where clause to restrict it to the // particular note ID. case FILE_ID: /* * Starts a final WHERE clause by restricting it to the desired note ID. */ finalWhere = finalWhere + " AND " + NotePad.Notes.COLUMN_NAME_FILE_ID + // The ID column name " = " + // test for equality "\"" + uri.getPathSegments().get(NotePad.Notes.NOTE_FILE_ID_PATH_POSITION) + "\""; break; // If the incoming pattern is invalid, throws an exception. default: throw new IllegalArgumentException("Unknown URI " + uri); } // If there were additional selection criteria, append them to the final // WHERE clause if (where != null) { finalWhere = finalWhere + " AND " + where; } // Performs the delete. count = db.delete(NotePad.Notes.TABLE_NAME, // The database table name. finalWhere, // The final WHERE clause whereArgs // The incoming where clause values. ); /* * Gets a handle to the content resolver object for the current context, and * notifies it that the incoming URI changed. The object passes this along * to the resolver framework, and observers that have registered themselves * for the provider are notified. */ getContext().getContentResolver().notifyChange(uri, null); // Returns the number of rows deleted. return count; } /** * This is called when a client calls * {@link android.content.ContentResolver#update(Uri,ContentValues,String,String[])} * Updates records in the database. The column names specified by the keys in * the values map are updated with new data specified by the values in the * map. If the incoming URI matches the note ID URI pattern, then the method * updates the one record specified by the ID in the URI; otherwise, it * updates a set of records. The record or records must match the input * selection criteria specified by where and whereArgs. If rows were updated, * then listeners are notified of the change. * * @param uri The URI pattern to match and update. * @param values A map of column names (keys) and new values (values). * @param where An SQL "WHERE" clause that selects records based on their * column values. If this is null, then all records that match the URI * pattern are selected. * @param whereArgs An array of selection criteria. If the "where" param * contains value placeholders ("?"), then each placeholder is replaced * by the corresponding element in the array. * @return The number of rows updated. * @throws IllegalArgumentException if the incoming URI pattern is invalid. */ @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { // Opens the database object in "write" mode. SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count; String finalWhere = NotePad.Notes.COLUMN_NAME_ACCOUNT + " = " + "\"" + uri.getPathSegments().get(NotePad.Notes.NOTE_ACCOUNT_PATH_POSITION) + "\""; // Does the update based on the incoming URI pattern switch (sUriMatcher.match(uri)) { // If the incoming URI matches the general notes pattern, does the update // based on the incoming data. case NOTES: break; // If the incoming URI matches a single note ID, does the update based on // the incoming data, but modifies the where clause to restrict it to the // particular note ID. case NOTE_ID: /* * Starts creating the final WHERE clause by restricting it to the * incoming note ID. */ finalWhere = finalWhere + " AND " + NotePad.Notes._ID + // The ID column name " = " + // test for equality uri.getPathSegments(). // the incoming note ID get(NotePad.Notes.NOTE_FILE_ID_PATH_POSITION); break; // If the incoming URI matches a single note ID, does the update based on // the incoming data, but modifies the where clause to restrict it to the // particular note ID. case FILE_ID: /* * Starts creating the final WHERE clause by restricting it to the * incoming note ID. */ finalWhere = finalWhere + " AND " + NotePad.Notes.COLUMN_NAME_FILE_ID + // The ID column name " = " + // test for equality "\"" + uri.getPathSegments().get(NotePad.Notes.NOTE_FILE_ID_PATH_POSITION) + "\""; break; // If the incoming pattern is invalid, throws an exception. default: throw new IllegalArgumentException("Unknown URI " + uri); } // If there were additional selection criteria, append them to the final // WHERE clause if (where != null) { finalWhere = finalWhere + " AND " + where; } // Does the update and returns the number of rows updated. count = db.update(NotePad.Notes.TABLE_NAME, // The database table name. values, // A map of column names and new values to use. finalWhere, // The final WHERE clause to use // placeholders for whereArgs whereArgs // The where clause column values to select on, or // null if the values are in the where argument. ); /* * Gets a handle to the content resolver object for the current context, and * notifies it that the incoming URI changed. The object passes this along * to the resolver framework, and observers that have registered themselves * for the provider are notified. */ getContext().getContentResolver().notifyChange(uri, null); // Returns the number of rows updated. return count; } /** * A test package can call this to get a handle to the database underlying * NotePadProvider, so it can insert test data into the database. The test * case class is responsible for instantiating the provider in a test context; * {@link android.test.ProviderTestCase2} does this during the call to setUp() * * @return a handle to the database helper object for the provider's data. */ DatabaseHelper getOpenHelperForTest() { return mOpenHelper; } }
Java
// Copyright 2012 Google Inc. All Rights Reserved. package com.example.android.notepad; import android.app.Activity; import android.app.LoaderManager; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.EditText; /** * This Activity allows the user to edit a note's title. It displays a floating * window containing an EditText. * * NOTE: Notice that the provider operations in this Activity are taking place * on the UI thread. This is not a good practice. It is only done here to make * the code more readable. A real application should use the * {@link android.content.AsyncQueryHandler} or {@link android.os.AsyncTask} * object to perform operations asynchronously on a separate thread. */ public class TitleEditor extends Activity implements LoaderManager.LoaderCallbacks<Cursor> { /** * This is a special intent action that means "edit the title of a note". */ public static final String EDIT_TITLE_ACTION = "com.android.notepad.action.EDIT_TITLE"; // Creates a projection that returns the note ID and the note contents. private static final String[] PROJECTION = new String[] {NotePad.Notes._ID, // 0 NotePad.Notes.COLUMN_NAME_TITLE, // 1 }; // The position of the title column in a Cursor returned by the provider. private static final int COLUMN_INDEX_TITLE = 1; // A Cursor object that will contain the results of querying the provider for // a note. private Cursor mCursor; // An EditText object for preserving the edited title. private EditText mText; // A URI object for the note whose title is being edited. private Uri mUri; private ProgressDialog mProgressBar = null; /** * This method is called by Android when the Activity is first started. From * the incoming Intent, it determines what kind of editing is desired, and * then does it. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the View for this Activity object's UI. setContentView(R.layout.title_editor); // Get the Intent that activated this Activity, and from it get the URI of // the note whose // title we need to edit. mUri = getIntent().getData(); // Gets the View ID for the EditText box mText = (EditText) this.findViewById(R.id.title); } /** * This method is called when the Activity is about to come to the foreground. * This happens when the Activity comes to the top of the task stack, OR when * it is first starting. * * Displays the current title for the selected note. */ @Override protected void onResume() { super.onResume(); getLoaderManager().initLoader(0, null, this); mProgressBar = ProgressDialog.show(this, null, "Loading title...", true); } /** * This method is called when the Activity loses focus. * * For Activity objects that edit information, onPause() may be the one place * where changes are saved. The Android application model is predicated on the * idea that "save" and "exit" aren't required actions. When users navigate * away from an Activity, they shouldn't have to go back to it to complete * their work. The act of going away should save everything and leave the * Activity in a state where Android can destroy it if necessary. * * Updates the note with the text currently in the text box. */ @Override protected void onPause() { super.onPause(); } public void onClickOk(View v) { // Verifies that the query made in onCreate() actually worked. If it worked, // then the Cursor object is not null. If it is *empty*, then // mCursor.getCount() == 0. if (mCursor != null) { // Creates a values map for updating the provider. ContentValues values = new ContentValues(); // In the values map, sets the title to the current contents of the // edit // box. values.put(NotePad.Notes.COLUMN_NAME_TITLE, mText.getText().toString()); values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, System.currentTimeMillis()); /* * Updates the provider with the note's new title. * * Note: This is being done on the UI thread. It will block the thread * until the update completes. In a sample app, going against a simple * provider based on a local database, the block will be momentary, but in * a real app you should use android.content.AsyncQueryHandler or * android.os.AsyncTask. */ getContentResolver().update(mUri, // The URI for the note to update. values, // The values map containing the columns to update and the values to use. null, // No selection criteria is used, so no "where" columns are needed. null // No "where" columns are used, so no "where" values are needed. ); finish(); } } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { /* * Using the URI passed in with the triggering Intent, gets the note. * * Note: This is being done on the UI thread. It will block the thread until * the query completes. In a sample app, going against a simple provider * based on a local database, the block will be momentary, but in a real app * you should use android.content.AsyncQueryHandler or android.os.AsyncTask. */ return new CursorLoader(this, mUri, PROJECTION, // The columns to retrieve null, // No selection criteria are used, so no where columns are needed. null, // No where columns are used, so no where values are needed. null // No sort order is needed. ); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { mCursor = cursor; // Verifies that the query made in onCreate() actually worked. If it worked, // then the Cursor object is not null. If it is *empty*, then // mCursor.getCount() == 0. if (mCursor != null) { // The Cursor was just retrieved, so its index is set to one record // *before* the first record retrieved. This moves it to the first record. mCursor.moveToFirst(); // Displays the current title text in the EditText object. mText.setText(mCursor.getString(COLUMN_INDEX_TITLE)); } if (mProgressBar != null) { mProgressBar.dismiss(); mProgressBar = null; } } @Override public void onLoaderReset(Loader<Cursor> arg0) { } }
Java
// Copyright 2012 Google Inc. All Rights Reserved. package com.example.android.notepad; import android.accounts.Account; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.Context; import android.content.SyncResult; import android.os.Bundle; /** * SymcAdapter that will keep NotePad notes on the device in sync on Google Drive. */ public class DriveSyncAdapter extends AbstractThreadedSyncAdapter { /** The context in which the Sync Adapter runs. */ private Context mContext; /** * Constructs a new DriveSyncAdapter. * @see AbstractThreadedSyncAdapter */ public DriveSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); mContext = context; } @Override public void onPerformSync(Account account, Bundle bundle, String authority, ContentProviderClient provider, SyncResult syncResult) { DriveSyncer syncer = new DriveSyncer(mContext, provider, account); syncer.performSync(); } }
Java
// Copyright 2012 Google Inc. All Rights Reserved. package com.example.android.notepad; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.common.AccountPicker; import com.google.api.client.googleapis.extensions.android.accounts.GoogleAccountManager; import android.accounts.Account; import android.accounts.AccountManager; import android.content.ContentResolver; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.util.Log; import java.util.List; /** * @author alainv * */ public class Preferences extends PreferenceActivity { /** * Populate the activity with the top-level headers. */ @Override public void onBuildHeaders(List<Header> target) { loadHeadersFromResource(R.layout.preferences_headers, target); } @Override public Intent getIntent() { final Intent modIntent = new Intent(super.getIntent()); modIntent.putExtra(EXTRA_SHOW_FRAGMENT, PreferencesFragment.class.getName()); modIntent.putExtra(EXTRA_NO_HEADERS, true); return modIntent; } /** * This fragment shows the preferences for the main header. */ public static class PreferencesFragment extends PreferenceFragment { public static final String[] ACCOUNT_TYPE = new String[] {GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}; private static final int CHOOSE_ACCOUNT = 0; private static final int STATE_INITIAL = 0; private static final int STATE_CHOOSING_ACCOUNT = 1; private static final int STATE_DONE = 3; private GoogleAccountManager mAccountManager; private Preference mAccountPreference; private ListPreference mSyncPreference; private SharedPreferences mPreferences; private int mState; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mState = STATE_INITIAL; mAccountManager = new GoogleAccountManager(getActivity()); mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // Load the preferences from an XML resource addPreferencesFromResource(R.layout.preferences_screen); // Initialize the preferred account setting. mAccountPreference = this.findPreference("selected_account_preference"); mAccountPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { chooseAccount(); return true; } }); mSyncPreference = (ListPreference) this.findPreference("sync_frequency_preference"); mSyncPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit(); editor.putString("sync_frequency_preference", (String) newValue); editor.commit(); setSyncFrequency(getPreferenceAccount()); return true; } }); } @Override public void onResume() { super.onResume(); Account preferenceAccount = getPreferenceAccount(); if (preferenceAccount != null) { mAccountPreference.setSummary(preferenceAccount.name); mState = STATE_DONE; } else { if (mState == STATE_INITIAL) { chooseAccount(); } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CHOOSE_ACCOUNT: if (data != null) { Log.e( "Preferences", "SELECTED ACCOUNT WITH EXTRA: " + data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME)); Bundle b = data.getExtras(); String accountName = b.getString(AccountManager.KEY_ACCOUNT_NAME); Log.d("Preferences", "Selected account: " + accountName); if (accountName != null && accountName.length() > 0) { Account account = mAccountManager.getAccountByName(accountName); setAccount(account); } } else { mState = STATE_INITIAL; } break; } } /** * Start an intent to prompt the user to choose the account to use with the * app. */ private void chooseAccount() { mState = STATE_CHOOSING_ACCOUNT; Intent intent = AccountPicker.newChooseAccountIntent(getPreferenceAccount(), null, ACCOUNT_TYPE, false, null, null, null, null); startActivityForResult(intent, CHOOSE_ACCOUNT); } /** * Set the new account to use with the app. * * @param account New account to use. */ private void setAccount(Account account) { if (account != null) { Account oldAccount = getPreferenceAccount(); // Stop syncing for the previously selected account. if (oldAccount != null) { ContentResolver.setSyncAutomatically(oldAccount, "com.google.provider.NotePad", false); } SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit(); editor.putString("selected_account_preference", account.name); editor.commit(); mAccountPreference.setSummary(account.name); setSyncFrequency(account); mState = STATE_DONE; } } /** * Set the sync frequency for the selected account. * * @param account Account to set sync frequency for. */ private void setSyncFrequency(Account account) { if (account != null) { String syncValue = mPreferences.getString("sync_frequency_preference", "900"); mSyncPreference.setSummary("Sync every " + mSyncPreference.getEntries()[mSyncPreference.findIndexOfValue(syncValue)]); ContentResolver.setSyncAutomatically(account, "com.google.provider.NotePad", true); ContentResolver.addPeriodicSync(account, "com.google.provider.NotePad", new Bundle(), Long.parseLong(syncValue)); } } /** * Get the currently preferred account to use with the app. * * @return The preferred account if available, {@code null} otherwise. */ private Account getPreferenceAccount() { return mAccountManager.getAccountByName(mPreferences.getString("selected_account_preference", "")); } } }
Java
/* * Copyright (C) 2007 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.example.android.notepad; import android.net.Uri; import android.provider.BaseColumns; /** * Defines a contract between the Note Pad content provider and its clients. A * contract defines the information that a client needs to access the provider * as one or more data tables. A contract is a public, non-extendable (final) * class that contains constants defining column names and URIs. A well-written * client depends only on the constants in the contract. */ public final class NotePad { public static final String AUTHORITY = "com.google.provider.NotePad"; // This class cannot be instantiated private NotePad() { } /** * Notes table contract */ public static final class Notes implements BaseColumns { // This class cannot be instantiated private Notes() { } /** * The table name offered by this provider */ public static final String TABLE_NAME = "notes"; /* * URI definitions */ /** * The scheme part for this provider's URI */ private static final String SCHEME = "content://"; /** * Path parts for the URIs */ /** * Path part for the Notes URI */ private static final String PATH_NOTES = "/notes"; /** * Path part for the Note ID URI */ private static final String PATH_NOTE_ID = "/notes/"; /** * 0-relative position of a note ID segment in the path part of a note ID * URI */ public static final int NOTE_ID_PATH_POSITION = 1; /** * 0-relative position of a note account segment in the path part of a note * ID URI */ public static final int NOTE_ACCOUNT_PATH_POSITION = 0; /** * 0-relative position of a note file ID segment in the path part of a note * ID URI */ public static final int NOTE_FILE_ID_PATH_POSITION = 2; /** * Path part for the Live Folder URI */ private static final String PATH_LIVE_FOLDER = "/live_folders/notes"; /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_NOTES); /** * The content URI base for a single note. Callers must append a numeric * note id to this Uri to retrieve a note */ public static final Uri CONTENT_ID_URI_BASE = Uri.parse(SCHEME + AUTHORITY + PATH_NOTE_ID); /** * The content URI match pattern for a single note, specified by its ID. Use * this to match incoming URIs or to construct an Intent. */ public static final Uri CONTENT_ID_URI_PATTERN = Uri.parse(SCHEME + AUTHORITY + PATH_NOTE_ID + "/#"); /** * The content Uri pattern for a notes listing for live folders */ public static final Uri LIVE_FOLDER_URI = Uri.parse(SCHEME + AUTHORITY + PATH_LIVE_FOLDER); /* * MIME type definitions */ /** * The MIME type of {@link #CONTENT_URI} providing a directory of notes. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note"; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single note. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.note"; /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "modified DESC"; /* * Column definitions */ /** * Column name for the title of the note * <P> * Type: TEXT * </P> */ public static final String COLUMN_NAME_TITLE = "title"; /** * Column name of the note content * <P> * Type: TEXT * </P> */ public static final String COLUMN_NAME_NOTE = "note"; /** * Column name for the creation timestamp * <P> * Type: INTEGER (long from System.curentTimeMillis()) * </P> */ public static final String COLUMN_NAME_CREATE_DATE = "created"; /** * Column name for the modification timestamp * <P> * Type: INTEGER (long from System.curentTimeMillis()) * </P> */ public static final String COLUMN_NAME_MODIFICATION_DATE = "modified"; /** * Column name for the Drive File ID * <P> * Type: TEXT * </P> */ public static final String COLUMN_NAME_FILE_ID = "fileId"; /** * Column name for the account * <P> * Type: TEXT * </P> */ public static final String COLUMN_NAME_ACCOUNT = "account"; /** * Column name for the trashed attribute * <P> * Type: BOOL * </P> */ public static final String COLUMN_NAME_DELETED = "deleted"; } }
Java
/* * Copyright (C) 2007 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.example.android.notepad; import com.google.android.gms.common.AccountPicker; import com.google.api.client.googleapis.extensions.android.accounts.GoogleAccountManager; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.LoaderManager; import android.app.ProgressDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.util.AttributeSet; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.EditText; /** * This Activity handles "editing" a note, where editing is responding to * {@link Intent#ACTION_VIEW} (request to view data), edit a note * {@link Intent#ACTION_EDIT}, create a note {@link Intent#ACTION_INSERT}, or * create a new note from the current contents of the clipboard * {@link Intent#ACTION_PASTE}. * * NOTE: Notice that the provider operations in this Activity are taking place * on the UI thread. This is not a good practice. It is only done here to make * the code more readable. A real application should use the * {@link android.content.AsyncQueryHandler} or {@link android.os.AsyncTask} * object to perform operations asynchronously on a separate thread. */ public class NoteEditor extends Activity implements LoaderManager.LoaderCallbacks<Cursor> { /** For logging and debugging purposes */ private static final String TAG = "NoteEditor"; /** Projection that returns the note ID and the note contents. */ private static final String[] PROJECTION = new String[] {NotePad.Notes.COLUMN_NAME_TITLE, NotePad.Notes.COLUMN_NAME_NOTE, NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE}; /** Label for the saved state of the activity. */ private static final String ORIGINAL_CONTENT = "origContent"; /** This Activity can be started by more than one action. Each action is represented as a "state" constant */ private static final int STATE_EDIT = 0; private static final int STATE_INSERT = 1; private static final int CHOOSE_ACCOUNT = 0; // Global mutable variables private int mState; private Uri mUri; private Cursor mCursor; private EditText mText; private String mOriginalContent; private String mFileId; private String mAccountName = null; private ProgressDialog mProgressBar = null; private boolean mInserted = false; /** * Defines a custom EditText View that draws lines between each line of text * that is displayed. */ public static class LinedEditText extends EditText { private Rect mRect; private Paint mPaint; // This constructor is used by LayoutInflater public LinedEditText(Context context, AttributeSet attrs) { super(context, attrs); // Creates a Rect and a Paint object, and sets the style and color of the // Paint object. mRect = new Rect(); mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(0x800000FF); } /** * This is called to draw the LinedEditText object * * @param canvas The canvas on which the background is drawn. */ @Override protected void onDraw(Canvas canvas) { // Gets the number of lines of text in the View. int count = getLineCount(); // Gets the global Rect and Paint objects Rect r = mRect; Paint paint = mPaint; // Draws one line in the rectangle for every line of text in the EditText for (int i = 0; i < count; i++) { // Gets the baseline coordinates for the current line of text int baseline = getLineBounds(i, r); /* * Draws a line in the background from the left of the rectangle to the * right, at a vertical position one dip below the baseline, using the * "paint" object for details. */ canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint); } // Finishes up by calling the parent method super.onDraw(canvas); } } /** * This method is called by Android when the Activity is first started. From * the incoming Intent, it determines what kind of editing is desired, and * then does it. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * Creates an Intent to use when the Activity object's result is sent back * to the caller. */ final Intent intent = getIntent(); /* * Sets up for the edit, based on the action specified for the incoming * Intent. */ // Gets the action that triggered the intent filter for this Activity final String action = intent.getAction(); // For an edit action: if (Intent.ACTION_EDIT.equals(action)) { // Sets the Activity state to EDIT, and gets the URI for the data to be // edited. mState = STATE_EDIT; mUri = intent.getData(); mAccountName = mUri.getPathSegments().get(NotePad.Notes.NOTE_ACCOUNT_PATH_POSITION); requestSync(); // For an insert or paste action: } else if (Intent.ACTION_INSERT.equals(action) || Intent.ACTION_PASTE.equals(action)) { // Sets the Activity state to INSERT, gets the general note URI, and // inserts an // empty record in the provider mState = STATE_INSERT; mUri = getContentResolver().insert(intent.getData(), null); /* * If the attempt to insert the new note fails, shuts down this Activity. * The originating Activity receives back RESULT_CANCELED if it requested * a result. Logs that the insert failed. */ if (mUri == null) { // Writes the log identifier, a message, and the URI that // failed. Log.e(TAG, "Failed to insert new note into " + getIntent().getData()); // Closes the activity. finish(); return; } // Since the new entry was created, this sets the result to be // returned // set the result to be returned. setResult(RESULT_OK, (new Intent()).setAction(mUri.toString())); getLoaderManager().initLoader(0, null, NoteEditor.this); // If the action was other than EDIT or INSERT: } else if ("com.google.android.apps.drive.DRIVE_OPEN".equals(action)) { mFileId = intent.getStringExtra("resourceId"); if (mFileId == null || mFileId.length() == 0) { Log.e(TAG, "Failed to retrieve the Drive file ID."); finish(); return; } else { Intent accountPickerIntent = AccountPicker.newChooseAccountIntent(null, null, Preferences.PreferencesFragment.ACCOUNT_TYPE, false, null, null, null, null); startActivityForResult(accountPickerIntent, CHOOSE_ACCOUNT); } } else { // Logs an error that the action was not understood, finishes the // Activity, and // returns RESULT_CANCELED to an originating Activity. Log.e(TAG, "Unknown action, exiting: " + action + " (uri: " + intent.getData() + ")"); finish(); return; } // For a paste, initializes the data from clipboard. // (Must be done after mCursor is initialized.) if (Intent.ACTION_PASTE.equals(action)) { // Does the paste performPaste(); // Switches the state to EDIT so the title can be modified. mState = STATE_EDIT; } // Sets the layout for this Activity. See res/layout/note_editor.xml setContentView(R.layout.note_editor); // Gets a handle to the EditText in the the layout. mText = (EditText) findViewById(R.id.note); /* * If this Activity had stopped previously, its state was written the * ORIGINAL_CONTENT location in the saved Instance state. This gets the * state. */ if (savedInstanceState != null) { mOriginalContent = savedInstanceState.getString(ORIGINAL_CONTENT); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CHOOSE_ACCOUNT: if (resultCode == RESULT_OK) { mAccountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); } if (mAccountName != null && mAccountName.length() > 0) { // Try retrieving existing file. mUri = Uri.parse("content://com.google.provider.NotePad/" + mAccountName + "/files/" + mFileId); mState = STATE_EDIT; } else { setResult(RESULT_CANCELED); finish(); } break; } } /** * This method is called when the Activity is about to come to the foreground. * This happens when the Activity comes to the top of the task stack, OR when * it is first starting. * * Moves to the first note in the list, sets an appropriate title for the * action chosen by the user, puts the note contents into the TextView, and * saves the original text as a backup. */ @Override protected void onResume() { super.onResume(); if (mState == STATE_EDIT) { /* * mCursor is initialized, since onCreate() always precedes onResume for * any running process. This tests that it's not null, since it should * always contain data. */ if (mCursor != null) { Log.d(TAG, "Destroying loader"); getLoaderManager().destroyLoader(0); } if (mUri != null) { Log.d(TAG, "Initializing loader"); getLoaderManager().initLoader(0, null, NoteEditor.this); } if (mProgressBar == null) { mProgressBar = ProgressDialog.show(this, null, "Loading note...", true); } } } /** * This method is called when an Activity loses focus during its normal * operation, and is then later on killed. The Activity has a chance to save * its state so that the system can restore it. * * Notice that this method isn't a normal part of the Activity lifecycle. It * won't be called if the user simply navigates away from the Activity. */ @Override protected void onSaveInstanceState(Bundle outState) { // Save away the original text, so we still have it if the activity // needs to be killed while paused. outState.putString(ORIGINAL_CONTENT, mOriginalContent); } /** * This method is called when the Activity loses focus. * * For Activity objects that edit information, onPause() may be the one place * where changes are saved. The Android application model is predicated on the * idea that "save" and "exit" aren't required actions. When users navigate * away from an Activity, they shouldn't have to go back to it to complete * their work. The act of going away should save everything and leave the * Activity in a state where Android can destroy it if necessary. * * If the user hasn't done anything, then this deletes or clears out the note, * otherwise it writes the user's work to the provider. */ @Override protected void onPause() { super.onPause(); /* * Tests to see that the query operation didn't fail (see onCreate()). The * Cursor object will exist, even if no records were returned, unless the * query failed because of some exception or error. */ if (mCursor != null) { // Get the current note text. String text = mText.getText().toString(); int length = text.length(); /* * If the Activity is in the midst of finishing and there is no text in * the current note, returns a result of CANCELED to the caller, and * deletes the note. This is done even if the note was being edited, the * assumption being that the user wanted to "clear out" (delete) the note. */ if (isFinishing() && (length == 0)) { setResult(RESULT_CANCELED); deleteNote(); /* * Writes the edits to the provider. The note has been edited if an * existing note was retrieved into the editor *or* if a new note was * inserted. In the latter case, onCreate() inserted a new empty note * into the provider, and it is this new note that is being edited. */ } else if (mState == STATE_EDIT) { // Creates a map to contain the new values for the columns updateNote(text, null); } else if (mState == STATE_INSERT) { updateNote(text, text); mState = STATE_EDIT; } } } /** * This method is called when the user clicks the device's Menu button the * first time for this Activity. Android passes in a Menu object that is * populated with items. * * Builds the menus for editing and inserting, and adds in alternative actions * that registered themselves to handle the MIME types for this application. * * @param menu A Menu object to which items should be added. * @return True to display the menu. */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu from XML resource MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.editor_options_menu, menu); // Only add extra menu items for a saved note if (mState == STATE_EDIT) { // Append to the // menu items for any other activities that can do stuff with it // as well. This does a query on the system for any activities that // implement the ALTERNATIVE_ACTION for our data, adding a menu item // for each one that is found. Intent intent = new Intent(null, mUri); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, new ComponentName(this, NoteEditor.class), null, intent, 0, null); } return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (mCursor != null && mCursor.getCount() > 0) { // Check if note has changed and enable/disable the revert option int colNoteIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE); String savedNote = mCursor.getString(colNoteIndex); String currentNote = mText.getText().toString(); if (savedNote != null && savedNote.equals(currentNote)) { menu.findItem(R.id.menu_revert).setVisible(false); } else { menu.findItem(R.id.menu_revert).setVisible(true); } } return super.onPrepareOptionsMenu(menu); } /** * This method is called when a menu item is selected. Android passes in the * selected item. The switch statement in this method calls the appropriate * method to perform the action the user chose. * * @param item The selected MenuItem * @return True to indicate that the item was processed, and no further work * is necessary. False to proceed to further processing as indicated * in the MenuItem object. */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle all of the possible menu actions. switch (item.getItemId()) { case R.id.menu_save: String text = mText.getText().toString(); updateNote(text, null); finish(); break; case R.id.menu_delete: deleteNote(); finish(); break; case R.id.menu_revert: cancelNote(); break; } return super.onOptionsItemSelected(item); } /** * A helper method that replaces the note's data with the contents of the * clipboard. */ private final void performPaste() { // Gets a handle to the Clipboard Manager ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); // Gets a content resolver instance ContentResolver cr = getContentResolver(); // Gets the clipboard data from the clipboard ClipData clip = clipboard.getPrimaryClip(); if (clip != null) { String text = null; String title = null; // Gets the first item from the clipboard data ClipData.Item item = clip.getItemAt(0); // Tries to get the item's contents as a URI pointing to a note Uri uri = item.getUri(); // Tests to see that the item actually is an URI, and that the URI // is a content URI pointing to a provider whose MIME type is the same // as the MIME type supported by the Note pad provider. if (uri != null && NotePad.Notes.CONTENT_ITEM_TYPE.equals(cr.getType(uri))) { // The clipboard holds a reference to data with a note MIME type. This // copies it. Cursor orig = cr.query(uri, // URI for the content provider PROJECTION, // Get the columns referred to in the projection null, // No selection variables null, // No selection variables, so no criteria are needed null // Use the default sort order ); // If the Cursor is not null, and it contains at least one record // (moveToFirst() returns true), then this gets the note data from it. if (orig != null) { if (orig.moveToFirst()) { int colNoteIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE); int colTitleIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE); text = orig.getString(colNoteIndex); title = orig.getString(colTitleIndex); } // Closes the cursor. orig.close(); } } // If the contents of the clipboard wasn't a reference to a note, then // this converts whatever it is to text. if (text == null) { text = item.coerceToText(this).toString(); } // Updates the current note with the retrieved title and text. updateNote(text, title); } } /** * Replaces the current note contents with the text and title provided as * arguments. * * @param text The new note contents to use. * @param initialTitle The new note title to use */ private final void updateNote(final String text, final String initialTitle) { ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, System.currentTimeMillis()); String title = initialTitle; // If the action is to insert a new note, this creates an initial title // for // it. if (mState == STATE_INSERT) { // If no title was provided as an argument, create one from the note // text. if (title == null) { // Get the note's length int length = text.length(); // Sets the title by getting a substring of the text that is 31 // characters long // or the number of characters in the note plus one, whichever is // smaller. title = text.substring(0, Math.min(30, length)); // If the resulting length is more than 30 characters, chops off any // trailing spaces if (length > 30) { int lastSpace = title.lastIndexOf(' '); if (lastSpace > 0) { title = title.substring(0, lastSpace); } } } // In the values map, sets the value of the title values.put(NotePad.Notes.COLUMN_NAME_TITLE, title); } else if (title != null) { // In the values map, sets the value of the title values.put(NotePad.Notes.COLUMN_NAME_TITLE, title); } // This puts the desired notes text into the map. values.put(NotePad.Notes.COLUMN_NAME_NOTE, text); /* * Updates the provider with the new values in the map. The ListView is * updated automatically. The provider sets this up by setting the * notification URI for query Cursor objects to the incoming URI. The * content resolver is thus automatically notified when the Cursor for the * URI changes, and the UI is updated. Note: This is being done on the UI * thread. It will block the thread until the update completes. In a sample * app, going against a simple provider based on a local database, the block * will be momentary, but in a real app you should use * android.content.AsyncQueryHandler or android.os.AsyncTask. */ getContentResolver().update(mUri, // The URI for the record to update. values, // The map of column names and new values to apply to them. null, // No selection criteria are used, so no where columns are // necessary. null // No where columns are used, so no where arguments are // necessary. ); requestSync(); } /** * This helper method cancels the work done on a note. It deletes the note if * it was newly created, or reverts to the original text of the note i */ private final void cancelNote() { if (mCursor != null) { if (mState == STATE_EDIT) { // Put the original note text back into the database mCursor.close(); mCursor = null; ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_NOTE, mOriginalContent); getContentResolver().update(mUri, values, null, null); } else if (mState == STATE_INSERT) { // We inserted an empty note, make sure to delete it deleteNote(); } } setResult(RESULT_CANCELED); mText.setText(""); finish(); } /** * Take care of deleting a note. Simply deletes the entry. */ private final void deleteNote() { if (mCursor != null) { mCursor.close(); mCursor = null; // Set the note deleted status to 1. ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_DELETED, 1); values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, System.currentTimeMillis()); getContentResolver().update(mUri, values, null, null); } mText.setText(""); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { if (mUri != null) { return new CursorLoader(this, mUri, PROJECTION, null, null, null); } else { return null; } } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { boolean closeProgressBar = true; mCursor = cursor; if (mCursor != null && mCursor.getCount() > 0) { /* * Moves to the first record. Always call moveToFirst() before accessing * data in a Cursor for the first time. The semantics of using a Cursor * are that when it is created, its internal index is pointing to a * "place" immediately before the first record. */ mCursor.moveToFirst(); int colModifiedDateIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE); if (mCursor.getLong(colModifiedDateIndex) != -1) { // Modifies the window title for the Activity according to the current // Activity state. if (mState == STATE_EDIT) { // Set the title of the Activity to include the note title int colTitleIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE); String title = mCursor.getString(colTitleIndex); Resources res = getResources(); String text = String.format(res.getString(R.string.title_edit), title); setTitle(text); // Sets the title to "create" for inserts } else if (mState == STATE_INSERT) { setTitle(getText(R.string.title_create)); } /* * onResume() may have been called after the Activity lost focus (was * paused). The user was either editing or creating a note when the * Activity paused. The Activity should re-display the text that had * been retrieved previously, but it should not move the cursor. This * helps the user to continue editing or entering. */ // Gets the note text from the Cursor and puts it in the TextView, but // doesn't change // the text cursor's position. int colNoteIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE); String note = mCursor.getString(colNoteIndex); if (note == null) { mText.setTextKeepState(""); } else if (!note.equals(mOriginalContent)) { mText.setTextKeepState(note); } // Stores the original note text, to allow the user to revert changes. if (mOriginalContent == null) { mOriginalContent = note; } } else { closeProgressBar = false; } } else if (mFileId != null && mFileId.length() > 0) { if (!mInserted) { // File does not exist in database yet, add it. Uri insertUri = Uri.parse("content://com.google.provider.NotePad/" + mAccountName + "/notes/"); ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_ACCOUNT, mAccountName); values.put(NotePad.Notes.COLUMN_NAME_FILE_ID, mFileId); values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, -1); mUri = getContentResolver().insert(insertUri, values); // Request a sync from the SyncAdapter to retrieve the data from Google // Drive. requestSync(); setResult(RESULT_OK, (new Intent()).setAction(mUri.toString())); mInserted = true; getLoaderManager().initLoader(0, null, this); } else { Log.d(TAG, "File already inserted"); } closeProgressBar = false; } else { // Something is wrong. The Cursor should always contain data. Report an // error in the note. setTitle(getText(R.string.error_title)); mText.setText(getText(R.string.error_message)); } if (closeProgressBar && mProgressBar != null) { mProgressBar.dismiss(); mProgressBar = null; // Redraw the option menu. invalidateOptionsMenu(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mCursor = null; } private void requestSync() { if (mAccountName != null && mAccountName.length() > 0) { final GoogleAccountManager accountManager = new GoogleAccountManager(this); Account account = accountManager.getAccountByName(mAccountName); if (account != null) { Bundle options = new Bundle(); options.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(account, "com.google.provider.NotePad", options); } } } }
Java
// Copyright 2012 Google Inc. All Rights Reserved. package com.example.android.notepad; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpResponse; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; import com.google.api.services.drive.Drive.Changes; import com.google.api.services.drive.Drive.Files; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.About; import com.google.api.services.drive.model.Change; import com.google.api.services.drive.model.ChangeList; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import android.accounts.Account; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentProviderClient; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * Holds logic for performing sync from Google Drive to the database using the * provided user's credentials. */ public class DriveSyncer { /** For logging and debugging purposes */ private static final String TAG = "DriveSyncAdapter"; /** Projection used for querying the database. */ private static final String[] PROJECTION = new String[] {NotePad.Notes._ID, NotePad.Notes.COLUMN_NAME_TITLE, NotePad.Notes.COLUMN_NAME_NOTE, NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, NotePad.Notes.COLUMN_NAME_FILE_ID, NotePad.Notes.COLUMN_NAME_DELETED}; /** The index of the projection columns */ private static final int COLUMN_INDEX_ID = 0; private static final int COLUMN_INDEX_TITLE = 1; private static final int COLUMN_INDEX_NOTE = 2; private static final int COLUMN_INDEX_MODIFICATION_DATE = 3; private static final int COLUMN_INDEX_FILE_ID = 4; private static final int COLUMN_INDEX_DELETED = 5; /** Field query parameter used on request to the drive.about.get endpoint. */ private static final String ABOUT_GET_FIELDS = "largestChangeId"; /** text/plain MIME type. */ private static final String TEXT_PLAIN = "text/plain"; private Context mContext; private ContentProviderClient mProvider; private Account mAccount; private Drive mService; private long mLargestChangeId; /** * Instantiate a new DriveSyncer. * * @param context Context to use on credential requests. * @param provider Provider to use for database requests. * @param account Account to perform sync for. */ public DriveSyncer(Context context, ContentProviderClient provider, Account account) { mContext = context; mProvider = provider; mAccount = account; mService = getDriveService(); mLargestChangeId = getLargestChangeId(); } /** * Perform a synchronization for the current account. */ public void performSync() { if (mService == null) { return; } Log.d(TAG, "Performing sync for " + mAccount.name); if (mLargestChangeId == -1) { // First time the sync adapter is run for the provided account. performFullSync(); } else { Map<String, File> files = getChangedFiles(mLargestChangeId); Uri uri = getNotesUri(mAccount.name); try { Cursor cursor = mProvider.query(uri, PROJECTION, NotePad.Notes.COLUMN_NAME_FILE_ID + " IS NOT NULL", null, null); Log.d(TAG, "Got local files: " + cursor.getCount()); for (boolean more = cursor.moveToFirst(); more; more = cursor.moveToNext()) { // Merge. String fileId = cursor.getString(COLUMN_INDEX_FILE_ID); Uri localFileUri = getFileUri(mAccount.name, fileId); Log.d(TAG, "Processing local file with drive ID: " + fileId); if (files.containsKey(fileId)) { File driveFile = files.get(fileId); if (driveFile != null) { // Merge the files. mergeFiles(localFileUri, cursor, driveFile); } else { Log.d(TAG, " > Deleting local file: " + fileId); // The file does not exist in Drive anymore, delete it. mProvider.delete(localFileUri, null, null); } files.remove(fileId); } else { // The file has not been updated on Drive, eventually update the Drive file. File driveFile = mService.files().get(fileId).execute(); mergeFiles(localFileUri, cursor, driveFile); } mContext.getContentResolver().notifyChange(localFileUri, null, false); } // Any remaining files in the map are files that do not exist in the local database. insertNewDriveFiles(files.values()); storeLargestChangeId(mLargestChangeId + 1); } catch (IOException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } } // Insert new local files. insertNewLocalFiles(); Log.d(TAG, "Done performing sync for " + mAccount.name); } /** * Merge a local file with a Google Drive File. * * The last modification is used to check which file to sync from. Then, the * md5 checksum of the file is used to check whether or not the file's content * should be sync'ed. * * @param localFileUri Local file URI to save local changes against. * @param localFile Local file cursor to retrieve data from. * @param driveFile Google Drive file. */ private void mergeFiles(Uri localFileUri, Cursor localFile, File driveFile) { long localFileModificationDate = localFile.getLong(COLUMN_INDEX_MODIFICATION_DATE); Log.d(TAG, "Modification dates: " + localFileModificationDate + " - " + driveFile.getModifiedDate().getValue()); if (localFileModificationDate > driveFile.getModifiedDate().getValue()) { try { if (localFile.getShort(COLUMN_INDEX_DELETED) != 0) { Log.d(TAG, " > Deleting Drive file."); mService.files().delete(driveFile.getId()).execute(); mProvider.delete(localFileUri, null, null); } else { String localNote = localFile.getString(COLUMN_INDEX_NOTE); File updatedFile = null; // Update drive file. Log.d(TAG, " > Updating Drive file."); driveFile.setTitle(localFile.getString(COLUMN_INDEX_TITLE)); if (md5(localNote) != driveFile.getMd5Checksum()) { // Update both content and metadata. ByteArrayContent content = ByteArrayContent.fromString(TEXT_PLAIN, localNote); updatedFile = mService.files().update(driveFile.getId(), driveFile, content).execute(); } else { // Only update the metadata. updatedFile = mService.files().update(driveFile.getId(), driveFile).execute(); } ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, updatedFile.getModifiedDate() .getValue()); mProvider.update(localFileUri, values, null, null); } } catch (IOException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } } else if (localFileModificationDate < driveFile.getModifiedDate().getValue()) { // Update local file. Log.d(TAG, " > Updating local file."); ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_TITLE, driveFile.getTitle()); values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, driveFile.getModifiedDate() .getValue()); // Only download the content if it has changed. if (md5(localFile.getString(COLUMN_INDEX_NOTE)) != driveFile.getMd5Checksum()) { values.put(NotePad.Notes.COLUMN_NAME_NOTE, getFileContent(driveFile)); } try { mProvider.update(localFileUri, values, null, null); } catch (RemoteException e) { e.printStackTrace(); } } } /** * Insert all new local files in Google Drive. */ private void insertNewLocalFiles() { Uri uri = getNotesUri(mAccount.name); try { Cursor cursor = mProvider.query(uri, PROJECTION, NotePad.Notes.COLUMN_NAME_FILE_ID + " is NULL", null, null); Log.d(TAG, "Inserting new local files: " + cursor.getCount()); if (cursor.moveToFirst()) { do { Uri localFileUri = getNoteUri(mAccount.name, cursor.getString(COLUMN_INDEX_ID)); if (cursor.getShort(COLUMN_INDEX_DELETED) != 0) { mProvider.delete(localFileUri, null, null); } else { File newFile = new File(); newFile.setTitle(cursor.getString(COLUMN_INDEX_TITLE)); newFile.setMimeType(TEXT_PLAIN); String content = cursor.getString(COLUMN_INDEX_NOTE); try { File insertedFile = null; if (content != null && content.length() > 0) { insertedFile = mService.files() .insert(newFile, ByteArrayContent.fromString(TEXT_PLAIN, content)) .execute(); } else { insertedFile = mService.files().insert(newFile).execute(); } // Update the local file to add the file ID. ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, insertedFile .getModifiedDate().getValue()); values.put(NotePad.Notes.COLUMN_NAME_CREATE_DATE, insertedFile.getCreatedDate() .getValue()); values.put(NotePad.Notes.COLUMN_NAME_FILE_ID, insertedFile.getId()); mProvider.update(localFileUri, values, null, null); } catch (IOException e) { e.printStackTrace(); } } } while (cursor.moveToNext()); } } catch (RemoteException e) { e.printStackTrace(); } } /** * Insert new Google Drive files in the local database. * * @param driveFiles Collection of Google Drive files to insert. */ private void insertNewDriveFiles(Collection<File> driveFiles) { Uri uri = getNotesUri(mAccount.name); Log.d(TAG, "Inserting new Drive files: " + driveFiles.size()); for (File driveFile : driveFiles) { if (driveFile != null) { ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_ACCOUNT, mAccount.name); values.put(NotePad.Notes.COLUMN_NAME_FILE_ID, driveFile.getId()); values.put(NotePad.Notes.COLUMN_NAME_TITLE, driveFile.getTitle()); values.put(NotePad.Notes.COLUMN_NAME_NOTE, getFileContent(driveFile)); values.put(NotePad.Notes.COLUMN_NAME_CREATE_DATE, driveFile.getCreatedDate().getValue()); values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, driveFile.getModifiedDate() .getValue()); try { mProvider.insert(uri, values); } catch (RemoteException e) { e.printStackTrace(); } } } mContext.getContentResolver().notifyChange(uri, null, false); } /** * Retrieve a Google Drive file's content. * * @param driveFile Google Drive file to retrieve content from. * @return Google Drive file's content if successful, {@code null} otherwise. */ public String getFileContent(File driveFile) { String result = ""; if (driveFile.getDownloadUrl() != null && driveFile.getDownloadUrl().length() > 0) { try { GenericUrl downloadUrl = new GenericUrl(driveFile.getDownloadUrl()); HttpResponse resp = mService.getRequestFactory().buildGetRequest(downloadUrl).execute(); InputStream inputStream = null; try { inputStream = resp.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder content = new StringBuilder(); char[] buffer = new char[1024]; int num; while ((num = reader.read(buffer)) > 0) { content.append(buffer, 0, num); } result = content.toString(); } finally { if (inputStream != null) { inputStream.close(); } } } catch (IOException e) { // An error occurred. e.printStackTrace(); return null; } } else { // The file doesn't have any content stored on Drive. return null; } return result; } /** * Retrieve a authorized service object to send requests to the Google Drive * API. On failure to retrieve an access token, a notification is sent to the * user requesting that authorization be granted for the * {@code https://www.googleapis.com/auth/drive.file} scope. * * @return An authorized service object. */ private Drive getDriveService() { if (mService == null) { try { GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(mContext, DriveScopes.DRIVE_FILE); credential.setSelectedAccountName(mAccount.name); // Trying to get a token right away to see if we are authorized credential.getToken(); mService = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build(); } catch (Exception e) { Log.e(TAG, "Failed to get token"); // If the Exception is User Recoverable, we display a notification that will trigger the // intent to fix the issue. if (e instanceof UserRecoverableAuthException) { UserRecoverableAuthException exception = (UserRecoverableAuthException) e; NotificationManager notificationManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); Intent authorizationIntent = exception.getIntent(); authorizationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags( Intent.FLAG_FROM_BACKGROUND); PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, authorizationIntent, 0); Notification notification = new Notification.Builder(mContext) .setSmallIcon(android.R.drawable.ic_dialog_alert) .setTicker("Permission requested") .setContentTitle("Permission requested") .setContentText("for account " + mAccount.name) .setContentIntent(pendingIntent).setAutoCancel(true).build(); notificationManager.notify(0, notification); } else { e.printStackTrace(); } } } return mService; } /** * Performs a full sync, usually occurs the first time a sync occurs for the * account. */ private void performFullSync() { Log.d(TAG, "Performing first sync"); Long largestChangeId = (long) -1; try { // Get the largest change Id first to avoid race conditions. About about = mService.about().get().setFields(ABOUT_GET_FIELDS).execute(); largestChangeId = about.getLargestChangeId(); } catch (IOException e) { e.printStackTrace(); } storeAllDriveFiles(); storeLargestChangeId(largestChangeId); Log.d(TAG, "Done performing first sync: " + largestChangeId); } /** * Store all text/plain files from Drive that the app has access to. This is * called the first time the app synchronize the database with Google Drive * for the current user. */ private void storeAllDriveFiles() { try { Files.List request = mService.files().list().setQ("mimeType = '" + TEXT_PLAIN +"'"); Map<String, File> textFiles = new HashMap<String, File>(); do { try { FileList files = request.execute(); for (File file : files.getItems()) { textFiles.put(file.getId(), file); } request.setPageToken(files.getNextPageToken()); } catch (IOException e) { System.out.println("An error occurred: " + e); request.setPageToken(null); } } while (request.getPageToken() != null && request.getPageToken().length() > 0); // Merge with files that are already in the database. try { Uri uri = getNotesUri(mAccount.name); Cursor cursor = mProvider.query(uri, PROJECTION, NotePad.Notes.COLUMN_NAME_FILE_ID + " IS NOT NULL", null, null); if (cursor.moveToFirst()) { do { String fileId = cursor.getString(COLUMN_INDEX_FILE_ID); if (textFiles.containsKey(fileId)) { Uri localFileUri = getNoteUri(mAccount.name, cursor.getString(COLUMN_INDEX_ID)); mergeFiles(localFileUri, cursor, textFiles.get(fileId)); textFiles.remove(fileId); } } while (cursor.moveToNext()); } } catch (RemoteException e) { e.printStackTrace(); } insertNewDriveFiles(textFiles.values()); } catch (IOException e) { e.printStackTrace(); } } /** * Retrieve a collection of files that have changed since the provided * {@code changeId}. * * @param changeId Change ID to retrieve changed files from. * @return Map of changed files key'ed by their file ID. */ private Map<String, File> getChangedFiles(long changeId) { Map<String, File> result = new HashMap<String, File>(); try { Changes.List request = mService.changes().list().setStartChangeId(changeId); do { ChangeList changes = request.execute(); long largestChangeId = changes.getLargestChangeId().longValue(); for (Change change : changes.getItems()) { if (change.getDeleted()) { result.put(change.getFileId(), null); } else if (TEXT_PLAIN.equals(change.getFile().getMimeType())) { result.put(change.getFileId(), change.getFile()); } } if (largestChangeId > mLargestChangeId) { mLargestChangeId = largestChangeId; } request.setPageToken(changes.getNextPageToken()); } while (request.getPageToken() != null && request.getPageToken().length() > 0); } catch (IOException e) { e.printStackTrace(); } Log.d(TAG, "Got changed Drive files: " + result.size() + " - " + mLargestChangeId); return result; } /** * Retrieve the largest change ID for the current user if available. * * @return The largest change ID, {@code -1} if not available. */ private long getLargestChangeId() { return PreferenceManager.getDefaultSharedPreferences(mContext).getLong( "largest_change_" + mAccount.name, -1); } /** * Store the largest change ID for the current user. * * @param changeId The largest change ID to store. */ private void storeLargestChangeId(long changeId) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.putLong("largest_change_" + mAccount.name, changeId); editor.commit(); mLargestChangeId = changeId; } /** * Compute the MD5 checksum of the provided string data from <a * href="http://stackoverflow.com/a/304350/1106381" * >http://stackoverflow.com/a/304350/1106381</a>. * * @param string Data to compute the MD5 checksum from. * @return The MD5 checksum as string. */ public static String md5(String string) { byte[] hash; try { hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Huh, MD5 should be supported?", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Huh, UTF-8 should be supported?", e); } StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) hex.append("0"); hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString(); } private static Uri getNotesUri(String accountName) { return Uri.parse("content://com.google.provider.NotePad/" + accountName + "/notes/"); } private static Uri getNoteUri(String accountName, String noteId) { return Uri.parse("content://com.google.provider.NotePad/" + accountName + "/notes/" + noteId); } private static Uri getFileUri(String accountName, String fileId) { return Uri.parse("content://com.google.provider.NotePad/" + accountName + "/files/" + fileId); } }
Java
/* * Copyright (C) 2007 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.example.android.notepad; import com.google.api.client.googleapis.extensions.android.accounts.GoogleAccountManager; import android.accounts.Account; import android.app.ListActivity; import android.app.LoaderManager; import android.app.ProgressDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.ComponentName; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; /** * Displays a list of notes. Will display notes from the {@link Uri} provided in * the incoming Intent if there is one, otherwise it defaults to displaying the * contents of the {@link NotePadProvider}. * * NOTE: Notice that the provider operations in this Activity are taking place * on the UI thread. This is not a good practice. It is only done here to make * the code more readable. A real application should use the * {@link android.content.AsyncQueryHandler} or {@link android.os.AsyncTask} * object to perform operations asynchronously on a separate thread. */ public class NotesList extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> { // For logging and debugging private static final String TAG = "NotesList"; /** * The columns needed by the cursor adapter */ private static final String[] PROJECTION = new String[] {NotePad.Notes._ID, // 0 NotePad.Notes.COLUMN_NAME_TITLE, // 1 }; /** The index of the title column */ private static final int COLUMN_INDEX_TITLE = 1; private SimpleCursorAdapter mAdapter; private Account mAccount; private ProgressDialog mProgressBar = null; /** * onCreate is called when Android starts this Activity from scratch. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // The user does not need to hold down the key to use menu shortcuts. setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); /* * Sets the callback for context menu activation for the ListView. The * listener is set to be this Activity. The effect is that context menus are * enabled for items in the ListView, and the context menu is handled by a * method in NotesList. */ getListView().setOnCreateContextMenuListener(this); // The names of the cursor columns to display in the view, initialized to // the title column String[] dataColumns = {NotePad.Notes.COLUMN_NAME_TITLE}; // The view IDs that will display the cursor columns, initialized to the // TextView in noteslist_item.xml int[] viewIDs = {android.R.id.text1}; // Creates the backing adapter for the ListView. mAdapter = new SimpleCursorAdapter(this, // The Context for the ListView R.layout.noteslist_item, // Points to the XML for a list item null, // The cursor to get items from dataColumns, viewIDs, 0); // Sets the ListView's adapter to be the cursor adapter that was just // created. setListAdapter(mAdapter); } @Override public void onResume() { super.onResume(); mAccount = new GoogleAccountManager(this).getAccountByName(PreferenceManager .getDefaultSharedPreferences(this).getString("selected_account_preference", "")); if (mAccount == null) { // Show the Preferences screen. startActivity(new Intent(getApplicationContext(), Preferences.class)); } else { loadNotes(); } } /** * Called when the user clicks the device's Menu button the first time for * this Activity. Android passes in a Menu object that is populated with * items. * * Sets up a menu that provides the Insert option plus a list of alternative * actions for this Activity. Other applications that want to handle notes can * "register" themselves in Android by providing an intent filter that * includes the category ALTERNATIVE and the mimeTYpe * NotePad.Notes.CONTENT_TYPE. If they do this, the code in * onCreateOptionsMenu() will add the Activity that contains the intent filter * to its list of options. In effect, the menu will offer the user other * applications that can handle notes. * * @param menu A Menu object, to which menu items should be added. * @return True, always. The menu should be displayed. */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu from XML resource MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_options_menu, menu); // Generate any additional actions that can be performed on the // overall list. In a normal install, there are no additional // actions found here, but this allows other applications to extend // our menu with their own actions. Intent intent = new Intent(null, getIntent().getData()); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, new ComponentName(this, NotesList.class), null, intent, 0, null); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); // The paste menu item is enabled if there is data on the clipboard. ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); MenuItem mPasteItem = menu.findItem(R.id.menu_paste); // If the clipboard contains an item, enables the Paste option on the menu. if (clipboard.hasPrimaryClip()) { mPasteItem.setEnabled(true); } else { // If the clipboard is empty, disables the menu's Paste option. mPasteItem.setEnabled(false); } // Gets the number of notes currently being displayed. final boolean haveItems = getListAdapter() != null && getListAdapter().getCount() > 0; // If there are any notes in the list (which implies that one of // them is selected), then we need to generate the actions that // can be performed on the current selection. This will be a combination // of our own specific actions along with any extensions that can be found. if (haveItems) { // This is the selected item. Uri uri = ContentUris.withAppendedId(getIntent().getData(), getSelectedItemId()); // Creates an array of Intents with one element. This will be used to send // an Intent based on the selected menu item. Intent[] specifics = new Intent[1]; // Sets the Intent in the array to be an EDIT action on the URI of the // selected note. specifics[0] = new Intent(Intent.ACTION_EDIT, uri); // Creates an array of menu items with one element. This will contain the // EDIT option. MenuItem[] items = new MenuItem[1]; // Creates an Intent with no specific action, using the URI of the // selected note. Intent intent = new Intent(null, uri); /* * Adds the category ALTERNATIVE to the Intent, with the note ID URI as * its data. This prepares the Intent as a place to group alternative * options in the menu. */ intent.addCategory(Intent.CATEGORY_ALTERNATIVE); /* * Add alternatives to the menu */ menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, // Add the Intents as // options in the // alternatives group. Menu.NONE, // A unique item ID is not required. Menu.NONE, // The alternatives don't need to be in order. null, // The caller's name is not excluded from the group. specifics, // These specific options must appear first. intent, // These Intent objects map to the options in specifics. Menu.NONE, // No flags are required. items // The menu items generated from the specifics-to- // Intents mapping ); // If the Edit menu item exists, adds shortcuts for it. if (items[0] != null) { // Sets the Edit menu item shortcut to numeric "1", letter "e" items[0].setShortcut('1', 'e'); } } else { // If the list is empty, removes any existing alternative actions from the // menu menu.removeGroup(Menu.CATEGORY_ALTERNATIVE); } // Displays the menu return true; } /** * This method is called when the user selects an option from the menu, but no * item in the list is selected. If the option was INSERT, then a new Intent * is sent out with action ACTION_INSERT. The data from the incoming Intent is * put into the new Intent. In effect, this triggers the NoteEditor activity * in the NotePad application. * * If the item was not INSERT, then most likely it was an alternative option * from another application. The parent method is called to process the item. * * @param item The menu item that was selected by the user * @return True, if the INSERT menu item was selected; otherwise, the result * of calling the parent method. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_add: /* * Launches a new Activity using an Intent. The intent filter for the * Activity has to have action ACTION_INSERT. No category is set, so * DEFAULT is assumed. In effect, this starts the NoteEditor Activity in * NotePad. */ startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData())); return true; case R.id.menu_paste: /* * Launches a new Activity using an Intent. The intent filter for the * Activity has to have action ACTION_PASTE. No category is set, so * DEFAULT is assumed. In effect, this starts the NoteEditor Activity in * NotePad. */ startActivity(new Intent(Intent.ACTION_PASTE, getIntent().getData())); return true; case R.id.menu_preferences: startActivity(new Intent(getApplicationContext(), Preferences.class)); return true; default: return super.onOptionsItemSelected(item); } } /** * This method is called when the user context-clicks a note in the list. * NotesList registers itself as the handler for context menus in its ListView * (this is done in onCreate()). * * The only available options are COPY and DELETE. * * Context-click is equivalent to long-press. * * @param menu A ContexMenu object to which items should be added. * @param view The View for which the context menu is being constructed. * @param menuInfo Data associated with view. * @throws ClassCastException */ @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { // The data from the menu item. AdapterView.AdapterContextMenuInfo info; // Tries to get the position of the item in the ListView that was // long-pressed. try { // Casts the incoming data object into the type for AdapterView objects. info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { // If the menu object can't be cast, logs an error. Log.e(TAG, "bad menuInfo", e); return; } /* * Gets the data associated with the item at the selected position. * getItem() returns whatever the backing adapter of the ListView has * associated with the item. In NotesList, the adapter associated all of the * data for a note with its list item. As a result, getItem() returns that * data as a Cursor. */ Cursor cursor = (Cursor) getListAdapter().getItem(info.position); // If the cursor is empty, then for some reason the adapter can't get the // data from the provider, so returns null to the caller. if (cursor == null) { // For some reason the requested item isn't available, do nothing return; } // Inflate menu from XML resource MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_context_menu, menu); // Sets the menu header to be the title of the selected note. menu.setHeaderTitle(cursor.getString(COLUMN_INDEX_TITLE)); // Append to the // menu items for any other activities that can do stuff with it // as well. This does a query on the system for any activities that // implement the ALTERNATIVE_ACTION for our data, adding a menu item // for each one that is found. Intent intent = new Intent(null, Uri.withAppendedPath(getIntent().getData(), Integer.toString((int) info.id))); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, new ComponentName(this, NotesList.class), null, intent, 0, null); } /** * This method is called when the user selects an item from the context menu * (see onCreateContextMenu()). The only menu items that are actually handled * are DELETE and COPY. Anything else is an alternative option, for which * default handling should be done. * * @param item The selected menu item * @return True if the menu item was DELETE, and no default processing is * need, otherwise false, which triggers the default handling of the * item. * @throws ClassCastException */ @Override public boolean onContextItemSelected(MenuItem item) { // The data from the menu item. AdapterView.AdapterContextMenuInfo info; /* * Gets the extra info from the menu item. When an note in the Notes list is * long-pressed, a context menu appears. The menu items for the menu * automatically get the data associated with the note that was * long-pressed. The data comes from the provider that backs the list. * * The note's data is passed to the context menu creation routine in a * ContextMenuInfo object. * * When one of the context menu items is clicked, the same data is passed, * along with the note ID, to onContextItemSelected() via the item * parameter. */ try { // Casts the data object in the item into the type for AdapterView // objects. info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { // If the object can't be cast, logs an error Log.e(TAG, "bad menuInfo", e); // Triggers default processing of the menu item. return false; } // Appends the selected note's ID to the URI sent with the incoming Intent. Uri noteUri = ContentUris.withAppendedId(getIntent().getData(), info.id); /* * Gets the menu item's ID and compares it to known actions. */ switch (item.getItemId()) { case R.id.context_open: // Launch activity to view/edit the currently selected item startActivity(new Intent(Intent.ACTION_EDIT, noteUri)); return true; case R.id.context_copy: // Gets a handle to the clipboard service. ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); // Copies the notes URI to the clipboard. In effect, this copies the // note itself clipboard.setPrimaryClip(ClipData.newUri( // new clipboard item holding // a URI getContentResolver(), // resolver to retrieve URI info "Note", // label for the clip noteUri) // the URI ); // Returns to the caller and skips further processing. return true; case R.id.context_delete: // Deletes the note from the provider by passing in a URI in note ID // format. // Please see the introductory note about performing provider operations // on the // UI thread. // Set the note deleted status to 1. ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_DELETED, 1); values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, System.currentTimeMillis()); getContentResolver().update(noteUri, values, null, null); // Returns to the caller and skips further processing. return true; default: return super.onContextItemSelected(item); } } /** * This method is called when the user clicks a note in the displayed list. * * This method handles incoming actions of either PICK (get data from the * provider) or GET_CONTENT (get or create data). If the incoming action is * EDIT, this method sends a new Intent to start NoteEditor. * * @param l The ListView that contains the clicked item * @param v The View of the individual item * @param position The position of v in the displayed list * @param id The row ID of the clicked item */ @Override protected void onListItemClick(ListView l, View v, int position, long id) { Cursor cursor = (Cursor) getListAdapter().getItem(position); if (cursor == null) { return; } // Constructs a new URI from the incoming URI and the row ID Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); // Gets the action from the incoming Intent String action = getIntent().getAction(); // Handles requests for note data if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { // Sets the result to return to the component that called this Activity. // The result contains the new URI setResult(RESULT_OK, new Intent().setData(uri)); } else { // Sends out an Intent to start an Activity that can handle ACTION_EDIT. // The Intent's data is the note ID URI. The effect is to call NoteEdit. startActivity(new Intent(Intent.ACTION_EDIT, uri)); } } /** * This method is called when the OAuthManager has successfully authorized the * application for the requested scopes. */ private void loadNotes() { /* * If no data is given in the Intent that started this Activity, then this * Activity was started when the intent filter matched a MAIN action. We * should use the default provider URI. */ // Gets the intent that started this Activity. Intent intent = getIntent(); intent.setData(Uri.parse("content://com.google.provider.NotePad/" + mAccount.name + "/notes/")); getLoaderManager().destroyLoader(0); getLoaderManager().initLoader(0, null, this); if (mProgressBar == null) { mProgressBar = ProgressDialog.show(this, null, "Loading notes...", true); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { return new CursorLoader(this, getIntent().getData(), PROJECTION, NotePad.Notes.COLUMN_NAME_DELETED + " = 0" /* where */, null /* columns */, NotePad.Notes.DEFAULT_SORT_ORDER); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { mAdapter.swapCursor(cursor); if (mProgressBar != null) { mProgressBar.dismiss(); mProgressBar = null; } // Redraw the option menu. invalidateOptionsMenu(); } @Override public void onLoaderReset(Loader<Cursor> arg0) { mAdapter.swapCursor(null); if (mProgressBar != null) { mProgressBar.dismiss(); mProgressBar = null; } } }
Java
/* * Copyright (c) 2012 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.drive.samples.dredit; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.auth.oauth2.CredentialStore; import com.google.api.client.extensions.appengine.auth.oauth2.AppEngineCredentialStore; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.services.oauth2.Oauth2; import com.google.api.services.oauth2.model.Userinfo; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import javax.servlet.http.HttpServletRequest; /** * Object that manages credentials associated with this Drive application and * its users. Performs all OAuth 2.0 authorization, authorization code * upgrades, and token storage/retrieval. * * @author vicfryzel@google.com (Vic Fryzel) */ public class CredentialMediator { /** * The HTTP request used to make a request to this Drive application. * Required so that we can manage a session for the active user, and keep * track of their email address which is used to identify their credentials. * We also need this in order to access a bunch of request parameters like * {@code state} and {@code code}. */ private HttpServletRequest request; /** * Scopes for which to request authorization. */ private Collection<String> scopes; /** * Loaded data from war/WEB-INF/client_secrets.json. */ private GoogleClientSecrets secrets; /** * CredentialStore at which Credential objects are stored. */ private CredentialStore credentialStore; /** * JsonFactory to use in parsing JSON. */ private static final JsonFactory JSON_FACTORY = new JacksonFactory(); /** * HttpTransport to use for external requests. */ private static final HttpTransport TRANSPORT = new NetHttpTransport(); /** * Key of session variable to store user IDs. */ private static final String USER_ID_KEY = "userId"; /** * Key of session variable to store user email addresses. */ private static final String EMAIL_KEY = "emailAddress"; /** * Creates a new CredentialsManager for the given HTTP request. * * @param request Request in which session credentials are stored. * @param clientSecretsStream Stream of client_secrets.json. * @throws InvalidClientSecretsException */ public CredentialMediator(HttpServletRequest request, InputStream clientSecretsStream, Collection<String> scopes) throws InvalidClientSecretsException { this.request = request; this.scopes = scopes; this.credentialStore = new AppEngineCredentialStore(); try { secrets = GoogleClientSecrets.load( JSON_FACTORY, clientSecretsStream); } catch (IOException e) { throw new InvalidClientSecretsException( "client_secrets.json is missing or invalid."); } } /** * @return Client information parsed from client_secrets.json. */ protected GoogleClientSecrets getClientSecrets() { return secrets; } /** * Builds an empty GoogleCredential, configured with appropriate * HttpTransport, JsonFactory, and client information. */ private Credential buildEmptyCredential() { return new GoogleCredential.Builder() .setClientSecrets(this.secrets) .setTransport(TRANSPORT) .setJsonFactory(JSON_FACTORY) .build(); } /** * Retrieves stored credentials for the provided email address. * * @param userId User's Google ID. * @return Stored GoogleCredential if found, {@code null} otherwise. * @throws IOException */ private Credential getStoredCredential(String userId) throws IOException { Credential credential = buildEmptyCredential(); if(credentialStore.load(userId, credential)) { return credential; } return null; } /** * Deletes stored credentials for the provided email address. * * @param userId User's Google ID. * @throws IOException */ private void deleteStoredCredential(String userId) throws IOException { if (userId != null) { Credential credential = getStoredCredential(userId); credentialStore.delete(userId, credential); } } /** * Exchange an authorization code for a credential. * * @param authorizationCode Authorization code to exchange for OAuth 2.0 * credentials. * @return Credential representing the upgraded authorizationCode. * @throws CodeExchangeException An error occurred. */ private Credential exchangeCode(String authorizationCode) throws CodeExchangeException { // Talk to Google and upgrade the given authorization code to an access // token and hopefully a refresh token. try { GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest( TRANSPORT, JSON_FACTORY, secrets.getWeb().getClientId(), secrets.getWeb().getClientSecret(), authorizationCode, secrets.getWeb().getRedirectUris().get(0)).execute(); return buildEmptyCredential().setFromTokenResponse(response); } catch (IOException e) { e.printStackTrace(); throw new CodeExchangeException(); } } /** * Send a request to the UserInfo API to retrieve user e-mail address * associated with the given credential. * * @param credential Credential to authorize the request. * @return User's e-mail address. * @throws NoUserIdException An error occurred, and the retrieved email * address was null. */ private Userinfo getUserInfo(Credential credential) throws NoUserIdException { Userinfo userInfo = null; // Create a user info service, and make a request to get the user's info. Oauth2 userInfoService = new Oauth2.Builder(TRANSPORT, JSON_FACTORY, credential).build(); try { userInfo = userInfoService.userinfo().get().execute(); if (userInfo == null) { throw new NoUserIdException(); } } catch (IOException e) { e.printStackTrace(); } return userInfo; } /** * Retrieve the authorization URL to authorize the user with the given * email address. * * @param emailAddress User's e-mail address. * @return Authorization URL to redirect the user to. */ private String getAuthorizationUrl(String emailAddress) { // Generate an authorization URL based on our client settings, // the user's email address, and the state parameter, if present. GoogleAuthorizationCodeRequestUrl urlBuilder = new GoogleAuthorizationCodeRequestUrl( secrets.getWeb().getClientId(), secrets.getWeb().getRedirectUris().get(0), scopes) .setAccessType("offline") .setApprovalPrompt("force"); // Propagate through the current state parameter, so that when the // user gets redirected back to our app, they see the file(s) they // were originally supposed to see before we realized we weren't // authorized. if (request.getParameter("state") != null) { urlBuilder.set("state", request.getParameter("state")); } if (emailAddress != null) { urlBuilder.set("user_id", emailAddress); } return urlBuilder.build(); } /** * Deletes the credential of the active session. * @throws IOException */ public void deleteActiveCredential() throws IOException { String userId = (String) request.getSession().getAttribute(USER_ID_KEY); this.deleteStoredCredential(userId); } /** * Retrieve credentials using the provided authorization code. * * This function exchanges the authorization code for an access token and * queries the UserInfo API to retrieve the user's e-mail address. If a * refresh token has been retrieved along with an access token, it is stored * in the application database using the user's e-mail address as key. If no * refresh token has been retrieved, the function checks in the application * database for one and returns it if found or throws a * NoRefreshTokenException with the authorization URL to redirect the user * to. * * @return Credential containing an access and refresh token. * @throws NoRefreshTokenException No refresh token could be retrieved from * the available sources. * @throws IOException */ public Credential getActiveCredential() throws NoRefreshTokenException, IOException { String userId = (String) request.getSession().getAttribute(USER_ID_KEY); Credential credential = null; try { // Only bother looking for a Credential if the user has an existing // session with their email address stored. if (userId != null) { credential = getStoredCredential(userId); } // No Credential was stored for the current user or no refresh token is // available. // If an authorizationCode is present, upgrade it into an // access token and hopefully a refresh token. if ((credential == null || credential.getRefreshToken() == null) && request.getParameter("code") != null) { credential = exchangeCode(request.getParameter("code")); if (credential != null) { Userinfo userInfo = getUserInfo(credential); userId = userInfo.getId(); request.getSession().setAttribute(USER_ID_KEY, userId); request.getSession().setAttribute(EMAIL_KEY, userInfo.getEmail()); // Sometimes we won't get a refresh token after upgrading a code. // This won't work for our app, because the user can land directly // at our app without first visiting Google Drive. Therefore, // only bother to store the Credential if it has a refresh token. // If it doesn't, we'll get one below. if (credential.getRefreshToken() != null) { credentialStore.store(userId, credential); } } } if (credential == null || credential.getRefreshToken() == null) { // No refresh token has been retrieved. // Start a "fresh" OAuth 2.0 flow so that we can get a refresh token. String email = (String) request.getSession().getAttribute(EMAIL_KEY); String authorizationUrl = getAuthorizationUrl(email); throw new NoRefreshTokenException(authorizationUrl); } } catch (CodeExchangeException e) { // The code the user arrived here with was bad. This pretty much never // happens. In a production application, we'd either redirect the user // somewhere like a home page, or show them a vague error mentioning // that they probably didn't arrive to our app from Google Drive. e.printStackTrace(); } catch (NoUserIdException e) { // This is bad because it means the user either denied us access // to their email address, or we couldn't fetch it for some reason. // This is unrecoverable. In a production application, we'd show the // user a message saying that we need access to their email address // to work. e.printStackTrace(); } return credential; } /** * Exception thrown when no refresh token has been found. */ @SuppressWarnings("serial") public static class NoRefreshTokenException extends Exception { /** * Authorization URL to which to redirect the user. */ private String authorizationUrl; /** * Construct a NoRefreshTokenException. * * @param authorizationUrl The authorization URL to redirect the user to. */ public NoRefreshTokenException(String authorizationUrl) { this.authorizationUrl = authorizationUrl; } /** * @return Authorization URL to which to redirect the user. */ public String getAuthorizationUrl() { return authorizationUrl; } } /** * Exception thrown when client_secrets.json is missing or invalid. */ @SuppressWarnings("serial") public static class InvalidClientSecretsException extends Exception { /** * Construct an InvalidClientSecretsException with a message. * * @param message Message to escalate. */ public InvalidClientSecretsException(String message) { super(message); } } /** * Exception thrown when no email address could be retrieved. */ @SuppressWarnings("serial") private static class NoUserIdException extends Exception {} /** * Exception thrown when a code exchange has failed. */ @SuppressWarnings("serial") private static class CodeExchangeException extends Exception {} }
Java
/* * Copyright (c) 2012 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.drive.samples.dredit; import com.google.drive.samples.dredit.model.State; import com.google.gson.Gson; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet to check that the current user is authorized and to serve the * start page for DrEdit. * * @author vicfryzel@google.com (Vic Fryzel) * @author nivco@google.com (Nicolas Garnier) */ @SuppressWarnings("serial") public class StartPageServlet extends DrEditServlet { /** * Ensure that the user is authorized, and setup the required values for * index.jsp. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Making sure the code gets processed req.setAttribute("client_id", new Gson().toJson(getClientId(req, resp))); // Deserialize the state in order to specify some values to the DrEdit // JavaScript client below. if (req.getParameter("state") != null) { State state = new State(req.getParameter("state")); if (state.ids != null && state.ids.size() > 0) { resp.sendRedirect("/#/edit/" + state.ids.toArray()[0]); return; } else if (state.parentId != null) { resp.sendRedirect("/#/create/" + state.parentId); return; } } req.getRequestDispatcher("/WEB-INF/templates/index.jsp").forward(req, resp); } }
Java
/* * Copyright (c) 2012 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.drive.samples.dredit; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.About; import com.google.gson.Gson; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that simply return the JSON of Drive's user About feed. * * @author nivco@google.com (Nicolas Garnier) */ @SuppressWarnings("serial") public class AboutServlet extends DrEditServlet { /** * Returns a JSON representation of Drive's user's About feed. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Drive service = getDriveService(req, resp); try { About about = service.about().get().execute(); resp.setContentType(JSON_MIMETYPE); resp.getWriter().print(new Gson().toJson(about)); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 401) { // The user has revoked our token or it is otherwise bad. // Delete the local copy so that their next page load will recover. deleteCredential(req, resp); sendError(resp, 401, "Unauthorized"); return; } } } /** * Build and return a Drive service object based on given request parameters. * * @param req Request to use to fetch code parameter or accessToken session * attribute. * @param resp HTTP response to use for redirecting for authorization if * needed. * @return Drive service object that is ready to make requests, or null if * there was a problem. */ private Drive getDriveService(HttpServletRequest req, HttpServletResponse resp) { Credential credentials = getCredential(req, resp); return new Drive.Builder(TRANSPORT, JSON_FACTORY, credentials).build(); } }
Java
/* * Copyright (c) 2012 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.drive.samples.dredit; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.oauth2.Oauth2; import com.google.api.services.oauth2.model.Userinfo; import com.google.gson.Gson; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that returns the profile of the currently logged-in user. * * @author nivco@google.com (Nicolas Garnier) */ @SuppressWarnings("serial") public class UserServlet extends DrEditServlet { /** * Returns a JSON representation of the user's profile. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Oauth2 service = getOauth2Service(req, resp); try { Userinfo about = service.userinfo().get().execute(); resp.setContentType(JSON_MIMETYPE); resp.getWriter().print(new Gson().toJson(about)); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 401) { // The user has revoked our token or it is otherwise bad. // Delete the local copy so that their next page load will recover. deleteCredential(req, resp); sendError(resp, 401, "Unauthorized"); return; } } } /** * Build and return an Oauth2 service object based on given request parameters. * * @param req Request to use to fetch code parameter or accessToken session * attribute. * @param resp HTTP response to use for redirecting for authorization if * needed. * @return Drive service object that is ready to make requests, or null if * there was a problem. */ private Oauth2 getOauth2Service(HttpServletRequest req, HttpServletResponse resp) { Credential credentials = getCredential(req, resp); return new Oauth2.Builder(TRANSPORT, JSON_FACTORY, credentials).build(); } }
Java
/* * Copyright (c) 2012 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.drive.samples.dredit; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.drive.samples.dredit.CredentialMediator.InvalidClientSecretsException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Abstract servlet that sets up credentials and provides some convenience * methods. * * @author vicfryzel@google.com (Vic Fryzel) */ @SuppressWarnings("serial") public abstract class DrEditServlet extends HttpServlet { protected static final HttpTransport TRANSPORT = new NetHttpTransport(); protected static final JsonFactory JSON_FACTORY = new JacksonFactory(); /** * Default MIME type of files created or handled by DrEdit. * * This is also set in the Google APIs Console under the Drive SDK tab. */ public static final String DEFAULT_MIMETYPE = "text/plain"; /** * MIME type to use when sending responses back to DrEdit JavaScript client. */ public static final String JSON_MIMETYPE = "application/json"; /** * Path component under war/ to locate client_secrets.json file. */ public static final String CLIENT_SECRETS_FILE_PATH = "/WEB-INF/client_secrets.json"; /** * Scopes for which to request access from the user. */ public static final List<String> SCOPES = Arrays.asList( // Required to access and manipulate files. "https://www.googleapis.com/auth/drive.file", // Required to identify the user in our data store. "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"); protected void sendError(HttpServletResponse resp, int code, String message) { try { resp.sendError(code, message); } catch (IOException e) { throw new RuntimeException(message); } } protected InputStream getClientSecretsStream() { return getServletContext().getResourceAsStream(CLIENT_SECRETS_FILE_PATH); } protected CredentialMediator getCredentialMediator( HttpServletRequest req, HttpServletResponse resp) { // Authorize or fetch credentials. Required here to ensure this happens // on first page load. Then, credentials will be stored in the user's // session. CredentialMediator mediator; try { mediator = new CredentialMediator(req, getClientSecretsStream(), SCOPES); mediator.getActiveCredential(); return mediator; } catch (CredentialMediator.NoRefreshTokenException e) { try { resp.sendRedirect(e.getAuthorizationUrl()); } catch (IOException ioe) { throw new RuntimeException("Failed to redirect user for authorization"); } throw new RuntimeException("No refresh token found. Re-authorizing."); } catch (InvalidClientSecretsException e) { String message = String.format( "This application is not properly configured: %s", e.getMessage()); sendError(resp, 500, message); throw new RuntimeException(message); } catch (IOException e) { String message = String.format( "An error happened while reading credentials: %s", e.getMessage()); sendError(resp, 500, message); throw new RuntimeException(message); } } protected Credential getCredential( HttpServletRequest req, HttpServletResponse resp) { try { CredentialMediator mediator = getCredentialMediator(req, resp); return mediator.getActiveCredential(); } catch(CredentialMediator.NoRefreshTokenException e) { try { resp.sendRedirect(e.getAuthorizationUrl()); } catch (IOException ioe) { ioe.printStackTrace(); throw new RuntimeException("Failed to redirect for authorization."); } } catch (IOException e) { String message = String.format( "An error happened while reading credentials: %s", e.getMessage()); sendError(resp, 500, message); throw new RuntimeException(message); } return null; } protected String getClientId( HttpServletRequest req, HttpServletResponse resp) { return getCredentialMediator(req, resp).getClientSecrets().getWeb() .getClientId(); } protected void deleteCredential(HttpServletRequest req, HttpServletResponse resp) { CredentialMediator mediator = getCredentialMediator(req, resp); try { mediator.deleteActiveCredential(); } catch (IOException e) { String message = String.format( "An error happened while reading credentials: %s", e.getMessage()); sendError(resp, 500, message); throw new RuntimeException(message); } } }
Java
/* * Copyright (c) 2012 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.drive.samples.dredit; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpResponse; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; import com.google.drive.samples.dredit.model.ClientFile; import com.google.gson.Gson; import java.io.IOException; import java.util.Scanner; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet providing a small API for the DrEdit JavaScript client to use in * manipulating files. Each operation (GET, POST, PUT) issues requests to the * Google Drive API. * * @author vicfryzel@google.com (Vic Fryzel) */ @SuppressWarnings("serial") public class FileServlet extends DrEditServlet { /** * Given a {@code file_id} URI parameter, return a JSON representation * of the given file. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Drive service = getDriveService(req, resp); String fileId = req.getParameter("file_id"); if (fileId == null) { sendError(resp, 400, "The `file_id` URI parameter must be specified."); return; } File file = null; try { file = service.files().get(fileId).execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 401) { // The user has revoked our token or it is otherwise bad. // Delete the local copy so that their next page load will recover. deleteCredential(req, resp); sendError(resp, 401, "Unauthorized"); return; } } if (file != null) { String content = downloadFileContent(service, file); if (content == null) { content = ""; } resp.setContentType(JSON_MIMETYPE); resp.getWriter().print(new ClientFile(file, content).toJson()); } else { sendError(resp, 404, "File not found"); } } /** * Create a new file given a JSON representation, and return the JSON * representation of the created file. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Drive service = getDriveService(req, resp); ClientFile clientFile = new ClientFile(req.getReader()); File file = clientFile.toFile(); if (!clientFile.content.equals("")) { file = service.files().insert(file, ByteArrayContent.fromString(clientFile.mimeType, clientFile.content)) .execute(); } else { file = service.files().insert(file).execute(); } resp.setContentType(JSON_MIMETYPE); resp.getWriter().print(new Gson().toJson(file.getId()).toString()); } /** * Update a file given a JSON representation, and return the JSON * representation of the created file. */ @Override public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { boolean newRevision = req.getParameter("newRevision").equals(Boolean.TRUE); Drive service = getDriveService(req, resp); ClientFile clientFile = new ClientFile(req.getReader()); File file = clientFile.toFile(); // If there is content we update the given file if (clientFile.content != null) { file = service.files().update(clientFile.resource_id, file, ByteArrayContent.fromString(clientFile.mimeType, clientFile.content)) .setNewRevision(newRevision).execute(); } else { // If there is no content we patch the metadata only file = service.files().patch(clientFile.resource_id, file).setNewRevision(newRevision).execute(); } resp.setContentType(JSON_MIMETYPE); resp.getWriter().print(new Gson().toJson(file.getId()).toString()); } /** * Download the content of the given file. * * @param service Drive service to use for downloading. * @param file File metadata object whose content to download. * @return String representation of file content. String is returned here * because this app is setup for text/plain files. * @throws IOException Thrown if the request fails for whatever reason. */ private String downloadFileContent(Drive service, File file) throws IOException { GenericUrl url = new GenericUrl(file.getDownloadUrl()); HttpResponse response = service.getRequestFactory().buildGetRequest(url) .execute(); try { return new Scanner(response.getContent()).useDelimiter("\\A").next(); } catch (java.util.NoSuchElementException e) { return ""; } } /** * Build and return a Drive service object based on given request parameters. * * @param req Request to use to fetch code parameter or accessToken session * attribute. * @param resp HTTP response to use for redirecting for authorization if * needed. * @return Drive service object that is ready to make requests, or null if * there was a problem. */ private Drive getDriveService(HttpServletRequest req, HttpServletResponse resp) { Credential credentials = getCredential(req, resp); return new Drive.Builder(TRANSPORT, JSON_FACTORY, credentials).build(); } }
Java
/* * Copyright (c) 2012 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.drive.samples.dredit.model; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Collection; /** * An object representing the state parameter passed into this application * from the Drive UI integration (i.e. Open With or Create New). Required * for Gson to deserialize the JSON into POJO form. * * @author vicfryzel@google.com (Vic Fryzel) */ public class State { /** * Action intended by the state. */ public String action; /** * IDs of files on which to take action. */ public Collection<String> ids; /** * Parent ID related to the given action. */ public String parentId; /** * Empty constructor required by Gson. */ public State() {} /** * Create a new State given its JSON representation. * * @param json Serialized representation of a State. */ public State(String json) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); State other = gson.fromJson(json, State.class); this.action = other.action; this.ids = other.ids; this.parentId = other.parentId; } }
Java