code
stringlengths
3
1.18M
language
stringclasses
1 value
package DBComm; public class DBExample{ private java.sql.Connection con = null; private final String url = "jdbc:mysql://"; private final String serverName= "192.168.0.102"; //Robert's IP 192.168.0.102 private final String portNumber = "3306"; //MySQL: 3306. SQL Server 2008: 50479 private final String databaseName= "pIMp"; private final String userName = "pIMpAdmin"; private final String password = "ainteasy"; private final String selectMethod = "cursor"; // Constructor public DBExample(){} private String getConnectionUrl(){ //return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";"; return url+serverName+":"+portNumber+"/"+databaseName+"?"; } private java.sql.Connection getConnection(){ try{ //Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); //Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); Class.forName("com.mysql.jdbc.Driver").newInstance(); con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password); if(con!=null) System.out.println("Connection Successful!"); }catch(Exception e){ e.printStackTrace(); System.out.println("Error Trace in getConnection() : " + e.getMessage()); } return con; } public void part1(){ java.sql.DatabaseMetaData dm = null; java.sql.ResultSet rs = null; java.sql.Statement st = null; String query = "SELECT * FROM client"; try{ con= this.getConnection(); //con.createStatement(); //System.out.println("empno \tname \tsalary"); if(con!=null){ st = con.createStatement(); rs = st.executeQuery(query); while(rs.next()){ System.out.print(rs.getString(1)); System.out.print("\t"+ rs.getString(2)); System.out.print("\t"+ rs.getString(3) + "\n"); System.out.print("\t"+ rs.getString(4) + "\n"); System.out.print("\t"+ rs.getString(5) + "\n"); } System.out.println(); rs.close(); rs = null; closeConnection(); }else System.out.println("Error: No active Connection"); }catch(Exception e){ e.printStackTrace(); } dm=null; } public void part2(){ java.sql.DatabaseMetaData dm = null; java.sql.ResultSet rs = null; java.sql.Statement st = null; String query = "SELECT distinct e.name FROM employee e inner join loan l on e.empno = l.empno, book b " + "Where b.isbn = l.isbn " + "And b.publisher = 'McGraw-Hill' " + "Group By e.name " + "Having count(b.isbn) = (Select count(isbn) from book where publisher = 'McGraw-Hill' ) "; try{ con= this.getConnection(); con.createStatement(); //Title bar System.out.println("name"); if(con!=null){ st = con.createStatement(); rs = st.executeQuery(query); while(rs.next()){ System.out.print(rs.getString(1) + "\n"); } System.out.println(); rs.close(); rs = null; closeConnection(); }else System.out.println("Error: No active Connection"); }catch(Exception e){ e.printStackTrace(); } dm=null; } public void part3(){ java.sql.DatabaseMetaData dm = null; java.sql.ResultSet rs = null; java.sql.Statement st = null; String query = "SELECT e.salary FROM employee e Order By e.salary"; try{ con= this.getConnection(); con.createStatement(); //Title bar System.out.println("salary"); if(con!=null){ st = con.createStatement(); rs = st.executeQuery(query); while(rs.next()){ System.out.print(rs.getString(1) + "\n"); } System.out.println(); rs.close(); rs = null; closeConnection(); }else System.out.println("Error: No active Connection"); }catch(Exception e){ e.printStackTrace(); } dm=null; } private void closeConnection(){ try{ if(con!=null) con.close(); con=null; }catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args) throws Exception { DBExample myDbTest = new DBExample(); myDbTest.part1(); //myDbTest.part2(); //myDbTest.part3(); } }
Java
package DBComm; public class Scrubber { static public String scrub(String str) { str = replaceString(str,"&","&amp;"); str = replaceString(str,"<","&lt;"); str = replaceString(str,">","&gt;"); str = replaceString(str,"\"","&quot;"); str = replaceString(str,"'","&apos;"); return str; } // from StringW static public String replaceString(String text, String repl, String with) { return replaceString(text, repl, with, -1); } /** * Replace a string with another string inside a larger string, for * the first n values of the search string. * * @param text String to do search and replace in * @param repl String to search for * @param with String to replace with * @param n int values to replace * * @return String with n values replacEd */ static public String replaceString(String text, String repl, String with, int max) { if(text == null) { return null; } StringBuffer buffer = new StringBuffer(text.length()); int start = 0; int end = 0; while( (end = text.indexOf(repl, start)) != -1 ) { buffer.append(text.substring(start, end)).append(with); start = end + repl.length(); if(--max == 0) { break; } } buffer.append(text.substring(start)); return buffer.toString(); } }
Java
package DBComm; //Dan Morgan import java.util.ArrayList; public class BuddyList { private ArrayList<Buddy> buddyList = new ArrayList<Buddy>(); // private Buddy myBuddy; public BuddyList(){ // this.myBuddy = new Buddy(); } public void addBuddy(Buddy myBuddy ){ buddyList.add(myBuddy); } public ArrayList<Buddy> getBuddyList(){ return buddyList; } }
Java
package DBComm; public class Buddy { private String buddy; private int status; public Buddy(){ this.buddy = ""; this.status = 0; } public Buddy(String buddyName, int status){ this.buddy = buddyName; this.status = status; } public String toString() { return this.buddy + ":" + this.status; } public void setBuddy(String buddyName){ this.buddy = buddyName; } public String getBuddy(){ return this.buddy; } public void setStatus(int status){ this.status = status; } public int getStatus(){ return this.status; } }
Java
package DBComm; public class RobertsClass { }
Java
package DBComm; public class Core { }
Java
package messages; public class AwayMessage extends Message { private String mySender; private String myReciever; private String myText; private Long mySrvTimeStamp; private Long myClintTimeStamp; public AwayMessage(){ super("Away"); this.mySender = ""; this.setMyReciever(""); this.myText = ""; this.mySrvTimeStamp = System.currentTimeMillis(); } public AwayMessage(String sender, String reciever, String text){ super("Away"); this.mySender = sender; this.setMyReciever(reciever); this.myText = text; this.mySrvTimeStamp = System.currentTimeMillis(); } public String getMessage(){ return this.myText; } public void setMessage(String text){ this.myText = text; } public String getSender(){ return this.mySender; } public void setSender(String sender){ this.mySender = sender; } public Long getClientTimeStamp(){ return this.myClintTimeStamp; } public void setReciever(Long timeStamp){ this.myClintTimeStamp = timeStamp; } public Long getServerTimeStamp(){ return this.mySrvTimeStamp; } public void setMyReciever(String myReciever) { this.myReciever = myReciever; } public String getMyReciever() { return myReciever; } // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>Away</type>"; message += "<users>"; message += "<from><username>" + mySender + "</username></from>"; message += "<to><username>" + myReciever + "</username></to>"; message += "</users>"; message += "<timestamp>" + mySrvTimeStamp + "</timestamp>"; message += "<text>" + myText + "</text>"; message += "</message>\n\0"; return message; } }
Java
// ResultMessage.java // Provides a message-formatted XML response package messages; import java.util.ArrayList; public class ResultMessage extends Message { private int value = 0; // return value private ArrayList<String> details = new ArrayList<String>(); // <details> <first>, <second>, <third>, etc. </details> public ResultMessage() {super("Result");} public ResultMessage(int value, ArrayList<String> details) { super("Result"); this.value = value; this.details = details; } public void addToDetails(String detail) { details.add(detail); } public int getValue() {return value;} public ArrayList<String> getDetails() {return details;} public String getDetail(int index) {return details.get(index);} public void setValue(int value) {this.value = value;} public void setDetails(ArrayList<String> details) {this.details = details;} // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>Result</type>"; message += "<value>" + value + "</value>"; message += "<details>"; for(String detail : details) { message += "<detail>" + detail + "</detail>"; } message += "</details>"; message += "</message>\n\0"; return message; } }
Java
package messages; import java.util.Date; public class ChatMessage extends Message { private String mySender; private String myReciever; private String myText; private Long mySrvTimeStamp; private Long myClintTimeStamp; public ChatMessage(){ super("Chat"); this.mySender = ""; this.setMyReciever(""); this.myText = ""; this.mySrvTimeStamp = System.currentTimeMillis(); } public ChatMessage(String sender, String reciever, String text){ super("Chat"); this.mySender = sender; this.setMyReciever(reciever); this.myText = text; this.mySrvTimeStamp = System.currentTimeMillis(); } public String getMessage(){ return this.myText; } public void setMessage(String text){ this.myText = text; } public String getSender(){ return this.mySender; } public void setSender(String sender){ this.mySender = sender; } public Long getClientTimeStamp(){ return this.myClintTimeStamp; } public void setReciever(Long timeStamp){ this.myClintTimeStamp = timeStamp; } public Long getServerTimeStamp(){ return this.mySrvTimeStamp; } public void setMyReciever(String myReciever) { this.myReciever = myReciever; } public String getMyReciever() { return myReciever; } // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>Chat</type>"; message += "<users>"; message += "<from><username>" + mySender + "</username></from>"; message += "<to><username>" + myReciever + "</username></to>"; message += "</users>"; message += "<timestamp>" + mySrvTimeStamp + "</timestamp>"; message += "<text>" + myText + "</text>"; message += "</message>\n\0"; return message; } }
Java
package messages; public class ReturnStatusMessage extends Message { private String type; private String username; private int status; public ReturnStatusMessage() {super("ReturnStatus");} public ReturnStatusMessage(String type, String username, int status) { super("ReturnStatus"); this.type = type; this.username = username; this.status = status; } public void setType(String type) {this.type = type;} public void setUsername(String username) {this.username = username;} public void setStatus(int status) {this.status = status;} public String getType() {return type;} public String getUsername() {return username;} public int getStatus() {return status;} public void printMessage() { System.out.println("Message (username: " + username + ") (status: " + status + ")"); // System.out.println("Sent at: " + timestamp); // System.out.println("Text: " + text); // System.out.println("User: " + username + " updated his/her status : " + from + " Added Buddy - " + to); System.out.println(); } // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>ReturnStatus</type>"; message += "<username>" + username + "</username>"; message += "<status>" + status + "</status>"; message += "</message>"; return message; } }
Java
package messages; public class RemoveBuddyMessage extends Message { private String type; private String from; private String to; public RemoveBuddyMessage() {super("RemoveBuddy");} public RemoveBuddyMessage(String type, String from, String to) { super("RemoveBuddy"); this.type = type; this.from = from; this.to = to; } public void setType(String type) {this.type = type;} public void setFrom(String from) {this.from = from;} public void setTo(String to) {this.to = to;} public String getType() {return type;} public String getFrom() {return from;} public String getTo() {return to;} public void printMessage() { System.out.println("Message (from: " + from + ") (to: " + to + ")"); // System.out.println("Sent at: " + timestamp); // System.out.println("Text: " + text); System.out.println("Text: " + from + " Added Buddy - " + to); System.out.println(); } // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>RemoveBuddy</type>"; message += "<from><username>" + from + "</username></from>"; message += "<to><username>" + to + "</username></to>"; message += "</message>"; return message; } }
Java
package messages; public class GetHistoryMessage extends Message { private String username; public GetHistoryMessage() { super("GetHistory"); this.username = ""; } public GetHistoryMessage(String type, String username) { super("GetHistory"); this.username = username; } public void setUsername(String username) { this.username = username; } public String getUsername() { return this.username; } public String toXML() { String message = "<message>"; message += "<type>GetHistory</type>"; message += "<username>" + username + "</username>"; message += "</message>"; return message; } }
Java
package messages; public class AddBuddyMessage extends Message { private String type; private String from; private String to; public AddBuddyMessage() {super("AddBuddy");} public AddBuddyMessage(String type, String from, String to) { super("AddBuddy"); this.type = type; this.from = from; this.to = to; } public void setType(String type) {this.type = type;} public void setFrom(String from) {this.from = from;} public void setTo(String to) {this.to = to;} public String getType() {return type;} public String getFrom() {return from;} public String getTo() {return to;} public void printMessage() { System.out.println("Message (from: " + from + ") (to: " + to + ")"); // System.out.println("Sent at: " + timestamp); // System.out.println("Text: " + text); System.out.println("Text: " + from + " Added Buddy - " + to); System.out.println(); } // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>AddBuddy</type>"; message += "<from><username>" + from + "</username></from>"; message += "<to><username>" + to + "</username></to>"; message += "</message>"; return message; } }
Java
package messages; public class GetBuddyListMessage extends Message { private String type; private String username; public GetBuddyListMessage() {super("GetBuddyList");} public GetBuddyListMessage(String type, String username) { super("GetBuddyList"); // this.type = type; this.username = username; } public void setType(String type) {this.type = type;} public void setUsername(String username) {this.username = username;} public String getType() {return type;} public String getUsername() {return username;} public void printMessage() { System.out.println("Message (username: " + username + ") (BuddyList requested)"); // System.out.println("Sent at: " + timestamp); // System.out.println("Text: " + text); // System.out.println("User: " + username + " updated his/her status : " + from + " Added Buddy - " + to); System.out.println(); } // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>GetBuddyList</type>"; message += "<username>" + username + "</username>"; message += "</message>"; return message; } }
Java
package messages; import java.io.*; import java.net.*; public class Client { public static void main(String[] args) throws IOException { String host = "169.234.14.7"; // String host = "169.234.15.29"; int port = 4444; String username = ""; String destination = ""; Socket kkSocket = null; PrintWriter out = null; BufferedReader in = null; try { kkSocket = new Socket(host, port); kkSocket.setKeepAlive(true); out = new PrintWriter(kkSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + host); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: " + host); System.exit(1); } System.out.println("Connected to host " + host + " on port " + port); // print out the server address InetAddress i = InetAddress.getLocalHost(); System.out.println("Your computer name: " + i.getHostName()); System.out.println("Your computer IP: " + i.getHostAddress()); System.out.println(); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String fromServer = ""; String fromUser = ""; // set the user's name System.out.print("What is your name? "); username = stdIn.readLine(); out.println("SETNAME:" + username); // set the user's destination System.out.print("Who are you chatting with? "); destination = stdIn.readLine(); System.out.println("Type \"Bye\" to quit"); while(!fromUser.equals("Bye")) { System.out.print(username + ": "); fromUser = stdIn.readLine(); String message = ""; if (fromUser.equals("addb")) { AddBuddyMessage adm = new AddBuddyMessage("Chat", username, destination); message += adm.toXML(); // message += "<type>AddBuddy</type>"; // message += "<users>"; // message += "<from><username>" + username + "</username></from>"; // message += "<to><username>" + destination + "</username></to>"; // message += "</users>"; // message += "</message>"; } else if (fromUser.equals("getb")) { GetBuddyListMessage gblm = new GetBuddyListMessage("GetBuddyList", username); message += gblm.toXML(); } else { // send a Chat message message += "<message>"; message += "<type>Chat</type>"; message += "<users>"; message += "<from><username>" + username + "</username></from>"; message += "<to><username>" + destination + "</username></to>"; message += "</users>"; message += "<timestamp>right now</timestamp>"; message += "<text>" + fromUser + "</text>"; message += "</message>"; } // pipe the message out to the socket out.println(message); fromServer = in.readLine(); // read a line from the server if(fromServer != null) { System.out.println(fromServer); } } System.out.println("Messaging socket terminated"); out.close(); in.close(); stdIn.close(); kkSocket.close(); } }
Java
package messages; import java.util.ArrayList; import DBComm.Buddy; public class ReturnBuddyListMessage extends Message { private String username; private ArrayList<Buddy> buddies = new ArrayList<Buddy>(); public ReturnBuddyListMessage() {super("ReturnBuddyList");} public ReturnBuddyListMessage(String username) { super("ReturnBuddyList"); this.username = username; } public void setUsername(String username) {this.username = username;} public String getUsername() {return username;} public void printMessage() { System.out.println("Message (username: " + username + ") (BuddyList requested)"); // System.out.println("Sent at: " + timestamp); // System.out.println("Text: " + text); // System.out.println("User: " + username + " updated his/her status : " + from + " Added Buddy - " + to); System.out.println(); } public void addBuddy(Buddy b) {buddies.add(b);} public void setBuddyList(ArrayList<Buddy> buddyList) {this.buddies = buddyList;} // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>ReturnBuddyList</type>"; message += "<username>" + username + "</username>"; message += "<buddies>"; for(Buddy b : buddies) { message += "<buddy>"; message += "<username>" + b.getBuddy() + "</username>"; message += "<status>" + b.getStatus() + "</status>"; message += "</buddy>"; } message += "</buddies>"; message += "</message>\n\0"; return message; } }
Java
package messages; public class LoginMessage extends Message { private String username; private String password; private String version; public LoginMessage(){ super("Login"); this.username = ""; this.password = ""; this.version = ""; } public LoginMessage(String username, String password, String version) { super("Login"); this.username = username; this.password = password; this.version = version; } public String getUsername(){ return this.username; } public void setUsername(String username){ this.username = username; } public String getPassword(){ return this.password; } public void setPassword(String password){ this.password = password; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>Login</type>"; message += "<username>" + username + "</username>"; message += "<password>" + password + "</password>"; message += "<version>" + version + "</version>"; message += "</message>"; return message; } }
Java
package messages; public class RegistrationMessage extends Message { private String username; private String password; public RegistrationMessage(){ super("Registration"); this.username = ""; this.password = ""; } public RegistrationMessage(String type, String username, String password) { super("Registration"); this.username = username; this.password = password; } public String getUsername(){ return this.username; } public void setUsername(String username){ this.username = username; } public String getPassword(){ return this.password; } public void setPassword(String password){ this.password = password; } // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>Registration</type>"; message += "<username>" + username + "</username>"; message += "<password>" + password + "</password>"; message += "</message>"; return message; } }
Java
package messages; public class ReturnAvailabilityMessage extends Message { private String username; private String availability; public ReturnAvailabilityMessage() { super("ReturnAvailability"); this.username = ""; this.availability = ""; } public ReturnAvailabilityMessage(String type, String username, String availability) { super("ReturnAvailability"); this.username = username; this.availability = availability; } public void setAvailability(String availability) { this.availability = availability; } public String getAvailability() { return this.availability; } public void setUsername(String username) { this.username = username; } public String getUsername() { return this.getUsername(); } public String toXML() { String message = "<message>"; message += "<type>UpdateAvailability</type>"; message += "<user><username>" + username + "</username></user>"; message += "<availability>" + availability + "</availability>"; message += "</message>"; return message; } }
Java
package messages; public class GetStatusMessage extends Message { private String username; public GetStatusMessage() { super("GetStatus"); this.username = ""; } public GetStatusMessage(String type, String username) { super("GetStatus"); this.username = username; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String toXML() { String message = "<message>"; message += "<type>Getstatus</type>"; message += "<user><username>" + username + "</username></user>"; message += "</message>"; return message; } }
Java
// Message.java // Generic Message class that all messages extend from package messages; public class Message { private String type = "Chat"; // default if no type is given public Message() {} public Message(String type) {} public String getType() {return type;} public void setType(String type) {this.type = type;} }
Java
package messages; public class WhoIsMessage extends Message { private String username; private String password; public WhoIsMessage(){ super("Whois"); this.username = ""; } public WhoIsMessage(String username) { super("whois"); this.username = username; } public String getUsername(){ return this.username; } public void setUsername(String username){ this.username = username; } // return an XML-formatted version of the message public String toXML() { String message = "<message>"; message += "<type>Whois</type>"; message += "<user><username>" + username + "</username></user>"; message += "</message>"; return message; } }
Java
package parser; import messages.AddBuddyMessage; import messages.AwayMessage; import messages.ChatMessage; import messages.GetBuddyListMessage; import messages.LoginMessage; import messages.RegistrationMessage; import messages.RemoveBuddyMessage; import messages.ReturnAvailabilityMessage; import messages.ReturnStatusMessage; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Parser { public Parser() {} public LoginMessage getLoginMessage(Element docEle) { // get the "username" tag //NodeList userTag = docEle.getElementsByTagName("username"); //Element user = (Element)userTag.item(0); String username = getTextValue(docEle,"username"); // get the "password" tag //NodeList passTag = docEle.getElementsByTagName("password"); //Element pass = (Element)passTag.item(0); String password = getTextValue(docEle,"password"); // get the "version" tag //NodeList versionTag = docEle.getElementsByTagName("version"); //Element ver = (Element)versionTag.item(0); String version = getTextValue(docEle,"version"); // construct a LoginMessage and return it LoginMessage loginMessage = new LoginMessage(username,password,version); return loginMessage; } public ChatMessage getChatMessage(Element docEle) { // get the "from" tag NodeList users = docEle.getElementsByTagName("from"); Element userFrom = (Element)users.item(0); // get the "to" tag NodeList users2 = docEle.getElementsByTagName("to"); Element userTo = (Element)users2.item(0); // get the "username" tag values from the "from" and "to" tags String from = getTextValue(userFrom,"username"); String to = getTextValue(userTo,"username"); // get the "timestamp" tag value long timestamp = System.currentTimeMillis(); // get the "text" tag value String text = getTextValue(docEle, "text"); // construct a ChatMessage and return it ChatMessage chatMessage = new ChatMessage(from,to,text); return chatMessage; } public AwayMessage getAwayMessage(Element docEle) { // get the "from" tag NodeList users = docEle.getElementsByTagName("from"); Element userFrom = (Element)users.item(0); // get the "to" tag NodeList users2 = docEle.getElementsByTagName("to"); Element userTo = (Element)users2.item(0); // get the "username" tag values from the "from" and "to" tags String from = getTextValue(userFrom,"username"); String to = getTextValue(userTo,"username"); // get the "timestamp" tag value long timestamp = System.currentTimeMillis(); // get the "text" tag value String text = getTextValue(docEle, "text"); // construct a ChatMessage and return it AwayMessage awayMessage = new AwayMessage(from,to,text); return awayMessage; } public AddBuddyMessage getAddBuddyMessage(Element docEle) { // get the "from" tag NodeList user = docEle.getElementsByTagName("from"); Element userFrom = (Element)user.item(0); // get the "to" tag NodeList user2 = docEle.getElementsByTagName("to"); Element userTo = (Element)user2.item(0); // get the "username" tag values from the "from" and "to" tags String from = getTextValue(userFrom,"username"); String to = getTextValue(userTo,"username"); // get the "text" tag value // String text = getTextValue(docEle, "text"); // construct a AddBuddyMessage and return it AddBuddyMessage adMessage = new AddBuddyMessage("AddBuddy",from,to); return adMessage; } public RemoveBuddyMessage getRemoveBuddyMessage(Element docEle) { // get the "from" tag NodeList user = docEle.getElementsByTagName("from"); Element userFrom = (Element)user.item(0); // get the "to" tag NodeList user2 = docEle.getElementsByTagName("to"); Element userTo = (Element)user2.item(0); // get the "username" tag values from the "from" and "to" tags String from = getTextValue(userFrom,"username"); String to = getTextValue(userTo,"username"); // get the "text" tag value // String text = getTextValue(docEle, "text"); // construct a AddBuddyMessage and return it RemoveBuddyMessage rmMessage = new RemoveBuddyMessage("RemoveBuddy",from,to); return rmMessage; } public ReturnStatusMessage getReturnStatusMessage(Element docEle) { // get the "from" tag NodeList userTag = docEle.getElementsByTagName("username"); Element user = (Element)userTag.item(0); // get the "to" tag NodeList statusTag = docEle.getElementsByTagName("status"); Element status = (Element)statusTag.item(0); // get the "username" tag values from the "from" and "to" tags String userstr = getTextValue(user,"username"); String statusstr = getTextValue(status,"status"); // get the "text" tag value // String text = getTextValue(docEle, "text"); // construct a AddBuddyMessage and return it if(statusstr == null || statusstr.equals("")) {statusstr = "1";} ReturnStatusMessage rsMessage = new ReturnStatusMessage("ReturnStatus", userstr, Integer.parseInt(statusstr)); return rsMessage; } public GetBuddyListMessage getBuddyListMessage(Element docEle) { // get the "from" tag // NodeList userTag = docEle.getElementsByTagName("username"); // Element user = (Element)userTag.item(0); // get the "username" tag values from the "from" and "to" tags // String userstr = getTextValue(user,"username"); String user = getTextValue(docEle, "username"); // System.out.println(user); // get the "text" tag value // String text = getTextValue(docEle, "text"); // construct a AddBuddyMessage and return it GetBuddyListMessage gblMessage = new GetBuddyListMessage("GetBuddyList", user); return gblMessage; } public RegistrationMessage getRegistrationMessage(Element docEle) { String userstr = getTextValue(docEle, "username"); String passwordstr = getTextValue(docEle, "password"); RegistrationMessage regMessage = new RegistrationMessage("Registration", userstr, passwordstr); return regMessage; } public ReturnAvailabilityMessage getReturnAvailabilityMessage(Element docEle) { NodeList userTag = docEle.getElementsByTagName("user"); Element user = (Element)userTag.item(0); NodeList availabilityTag = docEle.getElementsByTagName("availability"); Element availability = (Element)availabilityTag.item(0); String userstr = getTextValue(user,"username"); String availabilitystr = getTextValue(availability,"availability"); ReturnAvailabilityMessage raMessage = new ReturnAvailabilityMessage("UpdateAvailability", userstr, availabilitystr); return raMessage; } /** * I take a xml element and the tag name, look for the tag and get * the text content * i.e for <employee><name>John</name></employee> xml snippet if * the Element points to employee node and tagName is name I will return John * @param ele * @param tagName * @return */ public String getTextValue(Element ele, String tagName) { String textVal = null; NodeList nl = ele.getElementsByTagName(tagName); if(nl != null && nl.getLength() > 0) { Element el = (Element)nl.item(0); textVal = el.getFirstChild().getNodeValue(); } return textVal; } /** * Calls getTextValue and returns a int value * @param ele * @param tagName * @return */ public int getIntValue(Element ele, String tagName) { //in production application you would catch the exception return Integer.parseInt(getTextValue(ele,tagName)); } }
Java
// ServerThreadStaticHash.java // Static HashMap that holds client threads for the standalone clients package serverSocket; import java.util.HashMap; public class ServerThreadStaticHash { private static HashMap<String,ServerThread> hashtable = new HashMap<String,ServerThread>(); public static void addServerThread(String key, ServerThread st) { hashtable.put(key, st); } public static ServerThread getServerThread(String key) { return hashtable.get(key); } public static void removeServerThread(String key) { if(hashtable.containsKey(key)) { hashtable.remove(key); } } }
Java
package serverSocket; import java.net.*; import java.util.ArrayList; import java.io.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import messages.AddBuddyMessage; import messages.AwayMessage; import messages.ChatMessage; import messages.GetBuddyListMessage; import messages.LoginMessage; import messages.RemoveBuddyMessage; import messages.ResultMessage; import messages.ReturnBuddyListMessage; import messages.ReturnStatusMessage; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import DBComm.Buddy; import DBComm.BuddyList; import DBComm.DBComm; import DBComm.ReturnCodes; import parser.Parser; //import Server.DBComm; public class ServerThread extends Thread { private Socket socket = null; private String username = "Client"; private boolean running = true; PrintWriter out; BufferedReader in; Parser messageParser = new Parser(); // XML message parser DBComm dbc = new DBComm(); public ServerThread(Socket socket) { super("ServerThread"); this.socket = socket; } private void setUserName(String username) {this.username = username;} public String getUserName() {return username;} public void run() { try { dbc.updateStatus(getUserName(), 1); out = new PrintWriter(socket.getOutputStream(), true); // server socket output in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // client socket input String outputLine = ""; String inputLine = ""; getShitThread getST = new getShitThread(getUserName()); getST.start(); while(running) { // check for data in the database and pipe it out to the client(s) int result = dbc.getWebEvent(getUserName()); dbc.clearEvent(getUserName()); /* ArrayList<ChatMessage> chatMessages = dbc.getMessage(getUserName()); // send the messages out for(ChatMessage c : chatMessages) { // send the message directly to the client sendMessageDirectlyTo(c.getSender(), c.getMyReciever(), c.toXML()); } */ /* // check to see if the client is present in the ServerThreadStaticHash // if the client is not there, it is a Web Client if(ServerThreadStaticHash.getServerThread(getUserName()) != null) { if(result == 1) { // get messages for the web client ArrayList<ChatMessage> chatMessages = dbc.getMessage(getUserName()); // send the messages out for(ChatMessage c : chatMessages) { // send the message directly to the client sendMessageDirectlyTo(c.getSender(), c.getMyReciever(), c.toXML()); } } else if(result == 2) { // get the buddy list for the web client BuddyList theBuddyList = dbc.getBuddyList(getUserName()); ArrayList<Buddy> buddyArrayList = theBuddyList.getBuddyList(); // send out the buddy list for(Buddy b : buddyArrayList) { //b. } } else if(result == 3) { // do both // get messages for the web client ArrayList<ChatMessage> chatMessages = dbc.getMessage(getUserName()); // send the messages out for(ChatMessage c : chatMessages) { // send the message directly to the client sendMessageDirectlyTo(c.getSender(), c.getMyReciever(), c.toXML()); } } } */ if((inputLine = in.readLine()) != null) // read lines in from the client input { // remove null-byte entries inputLine = inputLine.replaceAll("\0", ""); // remove newline entries inputLine = inputLine.replaceAll("\n", ""); // escape single-quote entries inputLine = inputLine.replaceAll("\'", "\\'"); inputLine = inputLine.replaceAll("&apos;", "\\'"); System.out.println(username + " sent a message: " + inputLine); if(inputLine.contains("\0")) {System.out.println("NULL BYTE SENT");} // check input if(inputLine.equals("Bye")) { System.out.println("Client connection terminated"); socket.close(); break; } else if(inputLine.startsWith("SETNAME:")) { // set the name inputLine = inputLine.replace("SETNAME:", ""); System.out.println("\"" + username + "\" has changed his name to \"" + inputLine + "\""); setUserName(inputLine); // add this client to the HashMap ServerThreadStaticHash.addServerThread(inputLine, this); } else if(inputLine.startsWith("<message>") && inputLine.endsWith("</message>")) { // parse out the message parseMessage(inputLine); System.out.println(inputLine); } else { // process input and create an output response outputLine = inputLine; // echo back what the client sent out.println("Server: " + outputLine); // send the output back through the output socket } } /* chatMessages = dbc.getMessage(getUserName()); // send the messages out for(ChatMessage c : chatMessages) { // send the message directly to the client sendMessageDirectlyTo(c.getSender(), c.getMyReciever(), c.toXML()); } */ } out.close(); in.close(); //socket.close(); } catch(SocketException e) { // often thrown when the Client is stopped without typing the "Bye" command System.out.println("Client (" + username + ") connection lost: SocketException - " + e.getMessage()); } catch (Exception e) { e.printStackTrace(); } dbc.updateStatus(getUserName(), 0); } private void parseMessage(String inputLine) { Document dom; //get the factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML String dom = db.parse(new InputSource(new StringReader(inputLine))); // parse the document parseDocument(dom); }catch(ParserConfigurationException pce) { pce.printStackTrace(); }catch(SAXException se) { se.printStackTrace(); }catch(IOException ioe) { ioe.printStackTrace(); } } private void parseDocument(Document dom) { //get the root element Element docEle = dom.getDocumentElement(); // get the "type" tag to figure out the type of message String type = messageParser.getTextValue(docEle, "type"); if(type.equals("Login")) // login message { LoginMessage l = messageParser.getLoginMessage(docEle); // verify the login int result = dbc.verifyLogin(l.getUsername(), l.getPassword()); // create the response message ResultMessage r = new ResultMessage(); r.addToDetails("login"); // check the return code if(result == ReturnCodes.SUCCESS) { // successful login // add this client to the HashMap ServerThreadStaticHash.addServerThread(l.getUsername(), this); setUserName(l.getUsername()); System.out.println("Client \"" + l.getUsername() + "\" has logged in"); // set the response code r.setValue(ReturnCodes.SUCCESS); // mark the user as online dbc.updateStatus(l.getUsername(), 1); // send the response message sendMessageDirectlyTo(l.getUsername(),l.getUsername(),r.toXML()); System.out.println(l.getUsername() + " removed from HashMap"); } else if(result == ReturnCodes.BAD_PASSWORD) { // add this client to the HashMap ServerThreadStaticHash.addServerThread(l.getUsername(), this); // invalid password System.err.println("Client \"" + l.getUsername() + "\" supplied a bad password: " + l.getPassword()); // set the response code r.setValue(ReturnCodes.BAD_PASSWORD); // send the response message sendMessageDirectlyTo(l.getUsername(),l.getUsername(),r.toXML()); // remove this client from the HashMap ServerThreadStaticHash.removeServerThread(l.getUsername()); System.out.println(l.getUsername() + " removed from HashMap"); } else if(result == ReturnCodes.INVALID_LOGIN) { // add this client to the HashMap ServerThreadStaticHash.addServerThread(l.getUsername(), this); // invalid login (user does not exist) System.err.println("Client \"" + l.getUsername() + "\" supplied an invalid username: " + l.getUsername()); // set the response code r.setValue(ReturnCodes.INVALID_LOGIN); // send the response message sendMessageDirectlyTo(l.getUsername(),l.getUsername(),r.toXML()); // remove this client from the HashMap ServerThreadStaticHash.removeServerThread(l.getUsername()); } } else if(type.equals("Chat")) // Chat message { ChatMessage c = messageParser.getChatMessage(docEle); // send the message directly to the recipient sendMessageDirectlyTo(c.getSender(), c.getMyReciever(), c.toXML()); dbc.addMessage(c.getSender(), c.getMessage(), c.getMyReciever()); } else if(type.equals("Away")) // Away message { AwayMessage away = messageParser.getAwayMessage(docEle); // send the message directly to the recipient sendMessageDirectlyTo(away.getSender(), away.getMyReciever(), away.toXML()); dbc.addMessage(away.getSender(), away.getMessage(), away.getMyReciever()); } else if(type.equals("AddBuddy")) // Chat message { AddBuddyMessage abm = messageParser.getAddBuddyMessage(docEle); // send the message directly to the recipient //sendMessageDirectlyTo(abm.getFrom(), abm.getTo(), "Text: " + abm.getFrom() + " Added Buddy - " + abm.getTo()); dbc.addBuddy(abm.getFrom(), abm.getTo(), "Buddies"); } else if(type.equals("RemoveBuddy")) // Chat message { RemoveBuddyMessage rbm = messageParser.getRemoveBuddyMessage(docEle); // send the message directly to the recipient //sendMessageDirectlyTo(rbm.getFrom(), rbm.getTo(), "Text: " + rbm.getFrom() + " Removed Buddy - " + rbm.getTo()); dbc.removeBuddy(rbm.getFrom(), rbm.getTo(), "Buddies"); } else if(type.equals("UpdateStatus")) // Chat message { ReturnStatusMessage rsm = messageParser.getReturnStatusMessage(docEle); // send the message directly to the recipient // sendMessageDirectlyTo(rsm.getFrom(), rsm.getTo(), "Text: " + rsm.getFrom() + " Removed Buddy - " + rsm.getTo()); dbc.updateStatus(rsm.getUsername(), rsm.getStatus()); } else if(type.equals("GetBuddyList")) // Chat message { GetBuddyListMessage gmlm = messageParser.getBuddyListMessage(docEle); // send the message directly to the recipient // sendMessageDirectlyTo(rsm.getFrom(), rsm.getTo(), "Text: " + rsm.getFrom() + " Removed Buddy - " + rsm.getTo()); // System.out.println(gmlm.getUsername()); //sendMessage(gmlm.getUsername(), "Retrieving Buddy List: " + dbc.getBuddyList(gmlm.getUsername()).getBuddyList()); BuddyList bl = dbc.getBuddyList(gmlm.getUsername()); // construct the response message ReturnBuddyListMessage rblm = new ReturnBuddyListMessage(gmlm.getUsername()); rblm.setBuddyList(bl.getBuddyList()); // send the response message sendMessageDirectlyTo(rblm.getUsername(),rblm.getUsername(),rblm.toXML()); } } // send a message directly through this thread's socket to the connected client public void sendMessage(String userFrom, String message) { try { //out.println(userFrom + ": " + message); out.println(message); if(message != null && !message.equals("")) { System.out.println("Message sent to " + this.getUserName() + "'s socket: " + message); } } catch(Exception e) { System.out.println("Exception in sendMessage: " + e.getClass().getSimpleName() + " - " + e.getMessage()); } } // send a message from a given user (ServerThread) directly to a given user (ServerThread) // HashMap-based message re-routing public static void sendMessageDirectlyTo(String userFrom, String userTo, String message) { // get the HashMap entry for this client (based upon username) ServerThread theRecipient = ServerThreadStaticHash.getServerThread(userTo); if(theRecipient != null) { // send the message to the recipient's client socket theRecipient.sendMessage(userFrom, message); } } // send a message from a given user (ServerThread) directly to a given user (ServerThread) // Thread-based enumeration re-routing /*public void sendMessageDirectlyTo(String userFrom, String userTo, String message) { // get a count of currently active threads in this ThreadGroup and create // an empty array of the same size as the count int activeThreads = this.getThreadGroup().activeCount(); Thread[] threadList = new Thread[activeThreads]; // copy all currently active threads in this ThreadGroup into the array this.getThreadGroup().enumerate(threadList); ServerThread theClient = this; // get the current client by default for(Thread t : threadList) // look through the threads to find ServerThread classes { if(t instanceof ServerThread) // make sure we're looking at the clients (ServerThread classes) { ServerThread s = (ServerThread)t; if(s.getUserName().equals(userTo)) { // found the desired recipient theClient = s; break; } } } if(theClient != null) { // pipe the message out to the client socket theClient.sendMessage(userFrom, message); } }*/ public class getShitThread extends Thread{ DBComm dbc; private String username = ""; boolean alive; public getShitThread(String username){ //System.out.println("Starting Web Listener."); dbc = new DBComm(); this.username = username; } public void run(){ ArrayList<ChatMessage> chatMessages; alive = true; while(alive){ int result = dbc.getWebEvent(getUserName()); chatMessages = dbc.getMessage(this.username); // send the messages out // send the message directly to the client if(result == 1) { // get messages for the web client // send the messages out for(ChatMessage c : chatMessages) { // send the message directly to the client sendMessageDirectlyTo(c.getSender(), c.getMyReciever(), c.toXML()); } } else if(result == 2) { // get the buddy list for the web client BuddyList theBuddyList = dbc.getBuddyList(getUserName()); ArrayList<Buddy> buddyArrayList = theBuddyList.getBuddyList(); // send out the buddy list for(Buddy b : buddyArrayList) { //b. } } else if(result == 3) { // do both // get messages for the web client chatMessages = dbc.getMessage(getUserName()); // send the messages out for(ChatMessage c : chatMessages) { // send the message directly to the client sendMessageDirectlyTo(c.getSender(), c.getMyReciever(), c.toXML()); } } //System.out.println("checking web"); try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
Java
package serverSocket; import java.net.*; import java.util.Scanner; import java.io.*; import DBComm.DBComm; public class Server { public static void main(String[] args) { /* ServerProcess s1 = new ServerProcess(); s1.start(); Scanner s = new Scanner(System.in); while(s.hasNextLine()){ if(s.equals("stats")){ DBComm.outStats(); } } }*/ ServerSocket serverSocket = null; boolean listening = true; int port = 4444; try { serverSocket = new ServerSocket(port); // print out the server address InetAddress i = InetAddress.getLocalHost(); System.out.println("Server host name: " + i.getHostName()); System.out.println("Server host IP: " + i.getHostAddress()); System.out.println("Listening for connections on port " + port); } catch (IOException e) { System.err.println("Could not listen on port " + port); System.exit(-1); } try { while (listening) // listen for connections { // accept a new connection Socket s = serverSocket.accept(); s.setKeepAlive(true); ServerThread clientConnection = new ServerThread(s); // add the new thread to the HashMap ServerThreadStaticHash.addServerThread("Client", clientConnection); clientConnection.start(); //new ServerThread(serverSocket.accept()).start(); System.out.println("Connection accepted"); } System.out.println("Server socket closed"); serverSocket.close(); } catch(Exception e) { System.err.println("Server exception: " + e.getClass().getSimpleName() + " - " + e.getMessage()); e.printStackTrace(); } } }
Java
/* * Copyright 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.android.apps.iosched.gcm.server; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A servlet that pushes a GCM message to all registered devices. This servlet creates multicast * entities consisting of 1000 devices each, and creates tasks to send individual GCM messages to * each device in the multicast. * * This servlet must be authenticated against with an administrator's Google account, ideally a * shared role account. */ public class SendMessageToAllServlet extends BaseServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Queue queue = QueueFactory.getQueue("MulticastMessagesQueue"); String announcement = req.getParameter("announcement"); if (announcement == null) { announcement = ""; } List<String> devices = Datastore.getDevices(); // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == Datastore.MULTICAST_SIZE || counter == total) { String multicastKey = Datastore.createMulticast(partialDevices, announcement); logger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey); TaskOptions taskOptions = TaskOptions.Builder .withUrl("/send") .param("multicastKey", multicastKey) .method(Method.POST); queue.add(taskOptions); partialDevices.clear(); } } logger.fine("Queued message to " + counter + " devices"); resp.sendRedirect("/success.html"); } }
Java
/* * Copyright 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.android.apps.iosched.gcm.server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A servlet that shows a simple admin console for sending multicast messages. This servlet is * visible to administrators only. */ public class AdminServlet extends BaseServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head><title>IOSched GCM Server</title>"); out.print("</head>"); String status = (String) req.getAttribute("status"); if (status != null) { out.print(status); } out.print("</body></html>"); int total = Datastore.getTotalDevices(); out.print("<h2>" + total + " device(s) registered!</h2>"); out.print("<form method='POST' action='/sendall'>"); out.print("<table>"); out.print("<tr>"); out.print("<td>Announcement:</td>"); out.print("<td><input type='text' name='announcement' size='80'/></td>"); out.print("</tr>"); out.print("</table>"); out.print("<br/>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); resp.addHeader("X-FRAME-OPTIONS", "DENY"); resp.setStatus(HttpServletResponse.SC_OK); } }
Java
/* * Copyright 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.android.apps.iosched.gcm.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from the App Engine datastore. */ public class ApiKeyInitializer implements ServletContextListener { private final Logger logger = Logger.getLogger(ApiKeyInitializer.class.getSimpleName()); // Don't actually hard code your key here; rather, edit the entity in the App Engine console. static final String FAKE_API_KEY = "ENTER_KEY_HERE"; static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; @Override public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch (EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, FAKE_API_KEY); datastore.put(entity); logger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } /** * Gets the access key. */ protected String getKey() { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); String apiKey = ""; try { Entity entity = datastore.get(key); apiKey = (String) entity.getProperty(ACCESS_KEY_FIELD); } catch (EntityNotFoundException e) { logger.severe("Exception while retrieving the API Key" + e.toString()); } return apiKey; } @Override public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 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.android.apps.iosched.gcm.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by {@link * #PARAMETER_REG_ID}. * * The client app should call this servlet every time it receives a {@code * com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an error or {@code unregistered} * extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 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.android.apps.iosched.gcm.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by {@link * #PARAMETER_REG_ID}. The client app should call this servlet every time it receives a {@code * com.google.android.c2dm.intent.REGISTRATION} with an {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 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.android.apps.iosched.gcm.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Transaction; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. This class is neither * persistent (it will lost the data when the app is restarted) nor thread safe. */ public final class Datastore { private static final Logger logger = Logger.getLogger(Datastore.class.getSimpleName()); static final String MULTICAST_TYPE = "Multicast"; static final String MULTICAST_REG_IDS_PROPERTY = "regIds"; static final String MULTICAST_ANNOUNCEMENT_PROPERTY = "announcement"; static final int MULTICAST_SIZE = 1000; static final String DEVICE_TYPE = "Device"; static final String DEVICE_REG_ID_PROPERTY = "regid"; private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder .withPrefetchSize(MULTICAST_SIZE) .chunkSize(MULTICAST_SIZE); private static final DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. */ public static void register(String regId) { logger.info("Registering " + regId); Transaction txn = ds.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity != null) { logger.fine(regId + " is already registered; ignoring."); return; } entity = new Entity(DEVICE_TYPE); entity.setProperty(DEVICE_REG_ID_PROPERTY, regId); ds.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Unregisters a device. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); Transaction txn = ds.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity == null) { logger.warning("Device " + regId + " already unregistered"); } else { Key key = entity.getKey(); ds.delete(key); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); Transaction txn = ds.beginTransaction(); try { Entity entity = findDeviceByRegId(oldId); if (entity == null) { logger.warning("No device for registration id " + oldId); return; } entity.setProperty(DEVICE_REG_ID_PROPERTY, newId); ds.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets the number of total devices. */ public static int getTotalDevices() { Transaction txn = ds.beginTransaction(); try { Query query = new Query(DEVICE_TYPE).setKeysOnly(); List<Entity> allKeys = ds.prepare(query).asList(DEFAULT_FETCH_OPTIONS); int total = allKeys.size(); logger.fine("Total number of devices: " + total); txn.commit(); return total; } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets all registered devices. */ public static List<String> getDevices() { List<String> devices; Transaction txn = ds.beginTransaction(); try { Query query = new Query(DEVICE_TYPE); Iterable<Entity> entities = ds.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS); devices = new ArrayList<String>(); for (Entity entity : entities) { String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY); devices.add(device); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return devices; } /** * Returns the device object with the given registration ID. */ private static Entity findDeviceByRegId(String regId) { Query query = new Query(DEVICE_TYPE) .addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId); PreparedQuery preparedQuery = ds.prepare(query); List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS); Entity entity = null; if (!entities.isEmpty()) { entity = entities.get(0); } int size = entities.size(); if (size > 0) { logger.severe( "Found " + size + " entities for regId " + regId + ": " + entities); } return entity; } /** * Creates a persistent record with the devices to be notified using a multicast message. * * @param devices registration ids of the devices. * @param announcement announcement messageage * @return encoded key for the persistent record. */ public static String createMulticast(List<String> devices, String announcement) { String type = (announcement == null || announcement.trim().length() == 0) ? "sync" : ("announcement: " + announcement); logger.info("Storing multicast (" + type + ") for " + devices.size() + " devices"); String encodedKey; Transaction txn = ds.beginTransaction(); try { Entity entity = new Entity(MULTICAST_TYPE); entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); entity.setProperty(MULTICAST_ANNOUNCEMENT_PROPERTY, announcement); ds.put(entity); Key key = entity.getKey(); encodedKey = KeyFactory.keyToString(key); logger.fine("multicast key: " + encodedKey); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return encodedKey; } /** * Gets a persistent record with the devices to be notified using a multicast message. * * @param encodedKey encoded key for the persistent record. */ public static Entity getMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = ds.beginTransaction(); try { entity = ds.get(key); txn.commit(); return entity; } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return null; } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates a persistent record with the devices to be notified using a multicast message. * * @param encodedKey encoded key for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(String encodedKey, List<String> devices) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = ds.beginTransaction(); try { try { entity = ds.get(key); } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return; } entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); ds.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Deletes a persistent record with the devices to be notified using a multicast message. * * @param encodedKey encoded key for the persistent record. */ public static void deleteMulticast(String encodedKey) { Transaction txn = ds.beginTransaction(); try { Key key = KeyFactory.stringToKey(encodedKey); ds.delete(key); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } }
Java
/* * Copyright 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.android.apps.iosched.gcm.server; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ abstract class BaseServlet extends HttpServlet { protected final Logger logger = Logger.getLogger(getClass().getSimpleName()); protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.info("parameters: " + parameters); throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(0); } }
Java
/* * Copyright 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.android.apps.iosched.gcm.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import com.google.appengine.api.datastore.Entity; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet, called from an App Engine task, that sends the given message (sync or announcement) * to all devices in a given multicast group (up to 1000). */ public class SendMessageServlet extends BaseServlet { private static final int ANNOUNCEMENT_TTL = (int) TimeUnit.MINUTES.toSeconds(300); private Sender sender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { String multicastKey = req.getParameter("multicastKey"); Entity multicast = Datastore.getMulticast(multicastKey); @SuppressWarnings("unchecked") List<String> devices = (List<String>) multicast.getProperty(Datastore.MULTICAST_REG_IDS_PROPERTY); String announcement = (String) multicast.getProperty(Datastore.MULTICAST_ANNOUNCEMENT_PROPERTY); // Build the GCM message Message.Builder builder = new Message.Builder() .delayWhileIdle(true); if (announcement != null && announcement.trim().length() > 0) { builder .collapseKey("announcement") .addData("announcement", announcement) .timeToLive(ANNOUNCEMENT_TTL); } else { builder .collapseKey("sync"); } Message message = builder.build(); // Send the GCM message. MulticastResult multicastResult; try { multicastResult = sender.sendNoRetry(message, devices); logger.info("Result: " + multicastResult); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); taskDone(resp, multicastKey); return; } // check if any registration ids must be updated if (multicastResult.getCanonicalIds() != 0) { List<Result> results = multicastResult.getResults(); for (int i = 0; i < results.size(); i++) { String canonicalRegId = results.get(i).getCanonicalRegistrationId(); if (canonicalRegId != null) { String regId = devices.get(i); Datastore.updateRegistration(regId, canonicalRegId); } } } boolean allDone = true; if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retryableRegIds = new ArrayList<String>(); for (int i = 0; i < results.size(); i++) { String error = results.get(i).getErrorCodeName(); if (error != null) { String regId = devices.get(i); logger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } else if (error.equals(Constants.ERROR_UNAVAILABLE)) { retryableRegIds.add(regId); } } } if (!retryableRegIds.isEmpty()) { // update task Datastore.updateMulticast(multicastKey, retryableRegIds); allDone = false; retryTask(resp); } } if (allDone) { taskDone(resp, multicastKey); } else { retryTask(resp); } } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp, String multicastKey) { Datastore.deleteMulticast(multicastKey); resp.setStatus(200); } }
Java
/* * Copyright 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.api.android.plus; import android.content.Context; import android.util.AttributeSet; import android.widget.Button; /** * Stub until the release of <a href="https://developers.google.com/android/google-play-services/"> * Google Play Services.</a> */ public final class PlusOneButton extends Button { public PlusOneButton(Context context) { super(context); } public PlusOneButton(Context context, AttributeSet attrs) { super(context, attrs); } public PlusOneButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setUrl(String url) { } public void setSize(Size size) { } public enum Size { SMALL, MEDIUM, TALL, STANDARD } }
Java
/* * Copyright 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.api.android.plus; import android.content.Context; /** * Stub until the release of <a href="https://developers.google.com/android/google-play-services/"> * Google Play Services.</a> */ public final class GooglePlus { public static GooglePlus initialize(Context context, String apiKey, String clientId) { return new GooglePlus(); } }
Java
/* * Copyright 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.analytics.tracking.android; import android.app.Activity; import android.content.Context; /** * Temporarily just a stub. */ public class EasyTracker { public static EasyTracker getTracker() { return new EasyTracker(); } public void trackView(String s) { } public void trackActivityStart(Activity activity) { } public void trackActivityStop(Activity activity) { } public void setContext(Context context) { } public void trackEvent(String s1, String s2, String s3, long l) { } public void dispatch() { } }
Java
/* * Copyright 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.android.apps.iosched.gcm; import com.google.android.apps.iosched.Config; import com.google.android.gcm.GCMRegistrar; import android.content.Context; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Helper class used to communicate with the demo server. */ public final class ServerUtilities { private static final String TAG = makeLogTag("GCM"); private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLIS = 2000; private static final Random sRandom = new Random(); /** * Register this account/device pair within the server. * * @param context Current context * @param regId The GCM registration ID for this device * @return whether the registration succeeded or not. */ public static boolean register(final Context context, final String regId) { LOGI(TAG, "registering device (regId = " + regId + ")"); String serverUrl = Config.GCM_SERVER_URL + "/register"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); long backoff = BACKOFF_MILLIS + sRandom.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { LOGV(TAG, "Attempt #" + i + " to register"); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, true); return true; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). LOGE(TAG, "Failed to register on attempt " + i, e); if (i == MAX_ATTEMPTS) { break; } try { LOGV(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. LOGD(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return false; } // increase backoff exponentially backoff *= 2; } } return false; } /** * Unregister this account/device pair within the server. * * @param context Current context * @param regId The GCM registration ID for this device */ static void unregister(final Context context, final String regId) { LOGI(TAG, "unregistering device (regId = " + regId + ")"); String serverUrl = Config.GCM_SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. LOGD(TAG, "Unable to unregister from application server", e); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * @throws java.io.IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); LOGV(TAG, "Posting '" + body + "' to " + url); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setChunkedStreamingMode(0); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(body.length())); // post the request OutputStream out = conn.getOutputStream(); out.write(body.getBytes()); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } }
Java
/* * Copyright 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.android.apps.iosched.gcm; import com.google.android.gcm.GCMBroadcastReceiver; import android.content.Context; /** * @author trevorjohns@google.com (Trevor Johns) */ public class GCMRedirectedBroadcastReceiver extends GCMBroadcastReceiver { /** * Gets the class name of the intent service that will handle GCM messages. * * Used to override class name, so that GCMIntentService can live in a * subpackage. */ @Override protected String getGCMIntentServiceClassName(Context context) { return GCMIntentService.class.getCanonicalName(); } }
Java
/* * Copyright 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.android.apps.iosched.gcm; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.sync.TriggerSyncReceiver; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.gcm.GCMBaseIntentService; import com.google.android.gcm.GCMRegistrar; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import java.util.Random; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * {@link android.app.IntentService} responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = makeLogTag("GCM"); private static final int TRIGGER_SYNC_MAX_JITTER_MILLIS = 3 * 60 * 1000; // 3 minutes private static final Random sRandom = new Random(); public GCMIntentService() { super(Config.GCM_SENDER_ID); } @Override protected void onRegistered(Context context, String regId) { LOGI(TAG, "Device registered: regId=" + regId); ServerUtilities.register(context, regId); } @Override protected void onUnregistered(Context context, String regId) { LOGI(TAG, "Device unregistered"); if (GCMRegistrar.isRegisteredOnServer(context)) { ServerUtilities.unregister(context, regId); } else { // This callback results from the call to unregister made on // ServerUtilities when the registration to the server failed. LOGD(TAG, "Ignoring unregister callback"); } } @Override protected void onMessage(Context context, Intent intent) { if (UIUtils.isGoogleTV(context)) { // Google TV uses SyncHelper directly. return; } String announcement = intent.getStringExtra("announcement"); if (announcement != null) { displayNotification(context, announcement); return; } int jitterMillis = (int) (sRandom.nextFloat() * TRIGGER_SYNC_MAX_JITTER_MILLIS); final String debugMessage = "Received message to trigger sync; " + "jitter = " + jitterMillis + "ms"; LOGI(TAG, debugMessage); if (BuildConfig.DEBUG) { displayNotification(context, debugMessage); } ((AlarmManager) context.getSystemService(ALARM_SERVICE)) .set( AlarmManager.RTC, System.currentTimeMillis() + jitterMillis, PendingIntent.getBroadcast( context, 0, new Intent(context, TriggerSyncReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT)); } private void displayNotification(Context context, String message) { LOGI(TAG, "displayNotification: " + message); ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)) .notify(0, new NotificationCompat.Builder(context) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.ic_stat_notification) .setTicker(message) .setContentTitle(context.getString(R.string.app_name)) .setContentText(message) .setContentIntent( PendingIntent.getActivity(context, 0, new Intent(context, HomeActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)) .setAutoCancel(true) .getNotification()); } @Override public void onError(Context context, String errorId) { LOGE(TAG, "Received error: " + errorId); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message LOGW(TAG, "Received recoverable error: " + errorId); return super.onRecoverableError(context, errorId); } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.ImageFetcher; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.googleapis.services.GoogleKeyInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.http.json.JsonHttpRequestInitializer; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.services.plus.Plus; import com.google.api.services.plus.model.Activity; import com.google.api.services.plus.model.ActivityFeed; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.net.ParseException; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.app.ShareCompat; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.text.Html; import android.text.TextUtils; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A {@link WebView}-based fragment that shows Google+ public search results for a given query, * provided as the {@link SocialStreamFragment#EXTRA_QUERY} extra in the fragment arguments. If no * search query is provided, the conference hashtag is used as the default query. * * <p>WARNING! This fragment uses the Google+ API, and is subject to quotas. If you expect to * write a wildly popular app based on this code, please check the * at <a href="https://developers.google.com/+/">Google+ Platform documentation</a> on latest * best practices and quota details. You can check your current quota at the * <a href="https://code.google.com/apis/console">APIs console</a>. */ public class SocialStreamFragment extends SherlockListFragment implements AbsListView.OnScrollListener, LoaderManager.LoaderCallbacks<List<Activity>> { private static final String TAG = makeLogTag(SocialStreamFragment.class); public static final String EXTRA_QUERY = "com.google.android.iosched.extra.QUERY"; private static final String STATE_POSITION = "position"; private static final String STATE_TOP = "top"; private static final long MAX_RESULTS_PER_REQUEST = 20; private static final int STREAM_LOADER_ID = 0; private String mSearchString; private List<Activity> mStream = new ArrayList<Activity>(); private StreamAdapter mStreamAdapter = new StreamAdapter(); private int mListViewStatePosition; private int mListViewStateTop; private ImageFetcher mImageFetcher; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); // mSearchString can be populated before onCreate() by called refresh(String) if (TextUtils.isEmpty(mSearchString)) { mSearchString = intent.getStringExtra(EXTRA_QUERY); } if (TextUtils.isEmpty(mSearchString)) { mSearchString = UIUtils.CONFERENCE_HASHTAG; } if (!mSearchString.startsWith("#")) { mSearchString = "#" + mSearchString; } mImageFetcher = UIUtils.getImageFetcher(getActivity()); setListAdapter(mStreamAdapter); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { mListViewStatePosition = savedInstanceState.getInt(STATE_POSITION, -1); mListViewStateTop = savedInstanceState.getInt(STATE_TOP, 0); } else { mListViewStatePosition = -1; mListViewStateTop = 0; } return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(getString(R.string.empty_social_stream)); // In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter // in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we do this in onActivityCreated. getLoaderManager().initLoader(STREAM_LOADER_ID, null, this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setCacheColorHint(Color.WHITE); listView.setOnScrollListener(this); listView.setDrawSelectorOnTop(true); TypedValue v = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true); listView.setSelector(v.resourceId); } @Override public void onPause() { super.onPause(); mImageFetcher.setPauseWork(false); mImageFetcher.flushCache(); } @Override public void onDestroy() { super.onDestroy(); mImageFetcher.closeCache(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.social_stream, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_compose: Intent intent = ShareCompat.IntentBuilder.from(getActivity()) .setType("text/plain") .setText(mSearchString + "\n\n") .getIntent(); UIUtils.preferPackageForIntent(getActivity(), intent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); startActivity(intent); EasyTracker.getTracker().trackEvent("Home Screen Dashboard", "Click", "Post to Google+", 0L); LOGD("Tracker", "Home Screen Dashboard: Click, post to Google+"); return true; } return super.onOptionsItemSelected(item); } @Override public void onSaveInstanceState(Bundle outState) { if (isAdded()) { View v = getListView().getChildAt(0); int top = (v == null) ? 0 : v.getTop(); outState.putInt(STATE_POSITION, getListView().getFirstVisiblePosition()); outState.putInt(STATE_TOP, top); } super.onSaveInstanceState(outState); } public void refresh(String newQuery) { mSearchString = newQuery; refresh(true); } public void refresh() { refresh(false); } public void refresh(boolean forceRefresh) { if (isStreamLoading() && !forceRefresh) { return; } // clear current items mStream.clear(); mStreamAdapter.notifyDataSetInvalidated(); if (isAdded()) { Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); ((StreamLoader) loader).init(mSearchString); } loadMoreResults(); } public void loadMoreResults() { if (isAdded()) { Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { loader.forceLoad(); } } } @Override public void onListItemClick(ListView l, View v, int position, long id) { Activity activity = mStream.get(position); Intent postDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(activity.getUrl())); postDetailIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), postDetailIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); UIUtils.safeOpenLink(getActivity(), postDetailIntent); } @Override public void onScrollStateChanged(AbsListView listView, int scrollState) { // Pause disk cache access to ensure smoother scrolling if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING || scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { mImageFetcher.setPauseWork(true); } else { mImageFetcher.setPauseWork(false); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // Simple implementation of the infinite scrolling UI pattern; loads more Google+ // search results as the user scrolls to the end of the list. if (!isStreamLoading() && streamHasMoreResults() && visibleItemCount != 0 && firstVisibleItem + visibleItemCount >= totalItemCount - 1) { loadMoreResults(); } } @Override public Loader<List<Activity>> onCreateLoader(int id, Bundle args) { return new StreamLoader(getActivity(), mSearchString); } @Override public void onLoadFinished(Loader<List<Activity>> listLoader, List<Activity> activities) { if (activities != null) { mStream = activities; } mStreamAdapter.notifyDataSetChanged(); if (mListViewStatePosition != -1 && isAdded()) { getListView().setSelectionFromTop(mListViewStatePosition, mListViewStateTop); mListViewStatePosition = -1; } } @Override public void onLoaderReset(Loader<List<Activity>> listLoader) { } private boolean isStreamLoading() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).isLoading(); } } return true; } private boolean streamHasMoreResults() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).hasMoreResults(); } } return false; } private boolean streamHasError() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).hasError(); } } return false; } /** * An {@link AsyncTaskLoader} that loads activities from the public Google+ stream for * a given search query. The loader maintains a page state with the Google+ API and thus * supports pagination. */ private static class StreamLoader extends AsyncTaskLoader<List<Activity>> { List<Activity> mActivities; private String mSearchString; private String mNextPageToken; private boolean mIsLoading; private boolean mHasError; public StreamLoader(Context context, String searchString) { super(context); init(searchString); } private void init(String searchString) { mSearchString = searchString; mHasError = false; mNextPageToken = null; mIsLoading = true; mActivities = null; } @Override public List<Activity> loadInBackground() { mIsLoading = true; // Set up the HTTP transport and JSON factory HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); JsonHttpRequestInitializer initializer = new GoogleKeyInitializer( Config.API_KEY); // Set up the main Google+ class Plus plus = Plus.builder(httpTransport, jsonFactory) .setApplicationName(Config.APP_NAME) .setJsonHttpRequestInitializer(initializer) .build(); ActivityFeed activities = null; try { activities = plus.activities().search(mSearchString) .setPageToken(mNextPageToken) .setMaxResults(MAX_RESULTS_PER_REQUEST) .execute(); mHasError = false; mNextPageToken = activities.getNextPageToken(); } catch (IOException e) { e.printStackTrace(); mHasError = true; mNextPageToken = null; } return (activities != null) ? activities.getItems() : null; } @Override public void deliverResult(List<Activity> activities) { mIsLoading = false; if (activities != null) { if (mActivities == null) { mActivities = activities; } else { mActivities.addAll(activities); } } if (isStarted()) { // Need to return new ArrayList for some reason or onLoadFinished() is not called super.deliverResult(mActivities == null ? null : new ArrayList<Activity>(mActivities)); } } @Override protected void onStartLoading() { if (mActivities != null) { // If we already have results and are starting up, deliver what we already have. deliverResult(null); } else { forceLoad(); } } @Override protected void onStopLoading() { mIsLoading = false; cancelLoad(); } @Override protected void onReset() { super.onReset(); onStopLoading(); mActivities = null; } public boolean isLoading() { return mIsLoading; } public boolean hasMoreResults() { return mNextPageToken != null; } public boolean hasError() { return mHasError; } public void setSearchString(String searchString) { mSearchString = searchString; } public void refresh(String searchString) { setSearchString(searchString); refresh(); } public void refresh() { reset(); startLoading(); } } /** * A list adapter that shows individual Google+ activities as list items. * If another page is available, the last item is a "loading" view to support the * infinite scrolling UI pattern. */ private class StreamAdapter extends BaseAdapter { private static final int VIEW_TYPE_ACTIVITY = 0; private static final int VIEW_TYPE_LOADING = 1; @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return getItemViewType(position) == VIEW_TYPE_ACTIVITY; } @Override public int getViewTypeCount() { return 2; } @Override public boolean hasStableIds() { return true; } @Override public int getCount() { return mStream.size() + ( // show the status list row if... ((isStreamLoading() && mStream.size() == 0) // ...this is the first load || streamHasMoreResults() // ...or there's another page || streamHasError()) // ...or there's an error ? 1 : 0); } @Override public int getItemViewType(int position) { return (position >= mStream.size()) ? VIEW_TYPE_LOADING : VIEW_TYPE_ACTIVITY; } @Override public Object getItem(int position) { return (getItemViewType(position) == VIEW_TYPE_ACTIVITY) ? mStream.get(position) : null; } @Override public long getItemId(int position) { // TODO: better unique ID heuristic return (getItemViewType(position) == VIEW_TYPE_ACTIVITY) ? mStream.get(position).getId().hashCode() : -1; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (getItemViewType(position) == VIEW_TYPE_LOADING) { if (convertView == null) { convertView = getLayoutInflater(null).inflate( R.layout.list_item_stream_status, parent, false); } if (streamHasError()) { convertView.findViewById(android.R.id.progress).setVisibility(View.GONE); ((TextView) convertView.findViewById(android.R.id.text1)).setText( R.string.stream_error); } else { convertView.findViewById(android.R.id.progress).setVisibility(View.VISIBLE); ((TextView) convertView.findViewById(android.R.id.text1)).setText( R.string.loading); } return convertView; } else { Activity activity = (Activity) getItem(position); if (convertView == null) { convertView = getLayoutInflater(null).inflate( R.layout.list_item_stream_activity, parent, false); } StreamRowViewBinder.bindActivityView(convertView, activity, mImageFetcher); return convertView; } } } /** * A helper class to bind data from a Google+ {@link Activity} to the list item view. */ private static class StreamRowViewBinder { private static class ViewHolder { private TextView[] detail; private ImageView[] detailIcon; private ImageView[] media; private ImageView[] mediaOverlay; private TextView originalAuthor; private View reshareLine; private View reshareSpacer; private ImageView userImage; private TextView userName; private TextView content; private View plusOneIcon; private TextView plusOneCount; private View commentIcon; private TextView commentCount; } private static void bindActivityView( final View rootView, Activity activity, ImageFetcher imageFetcher) { // Prepare view holder. ViewHolder temp = (ViewHolder) rootView.getTag(); final ViewHolder views; if (temp != null) { views = temp; } else { views = new ViewHolder(); rootView.setTag(views); views.detail = new TextView[] { (TextView) rootView.findViewById(R.id.stream_detail_text) }; views.detailIcon = new ImageView[] { (ImageView) rootView.findViewById(R.id.stream_detail_media_small) }; views.media = new ImageView[] { (ImageView) rootView.findViewById(R.id.stream_media_1_1), (ImageView) rootView.findViewById(R.id.stream_media_1_2), }; views.mediaOverlay = new ImageView[] { (ImageView) rootView.findViewById(R.id.stream_media_overlay_1_1), (ImageView) rootView.findViewById(R.id.stream_media_overlay_1_2), }; views.originalAuthor = (TextView) rootView.findViewById(R.id.stream_original_author); views.reshareLine = rootView.findViewById(R.id.stream_reshare_line); views.reshareSpacer = rootView.findViewById(R.id.stream_reshare_spacer); views.userImage = (ImageView) rootView.findViewById(R.id.stream_user_image); views.userName = (TextView) rootView.findViewById(R.id.stream_user_name); views.content = (TextView) rootView.findViewById(R.id.stream_content); views.plusOneIcon = rootView.findViewById(R.id.stream_plus_one_icon); views.plusOneCount = (TextView) rootView.findViewById(R.id.stream_plus_one_count); views.commentIcon = rootView.findViewById(R.id.stream_comment_icon); views.commentCount = (TextView) rootView.findViewById(R.id.stream_comment_count); } final Resources res = rootView.getContext().getResources(); // Hide all the array items. int detailIndex = 0; int mediaIndex = 0; for (View v : views.detail) { v.setVisibility(View.GONE); } for (View v : views.detailIcon) { v.setVisibility(View.GONE); } for (View v : views.media) { v.setVisibility(View.GONE); } for (View v : views.mediaOverlay) { v.setVisibility(View.GONE); } // Determine if this is a reshare (affects how activity fields are to be // interpreted). boolean isReshare = (activity.getObject().getActor() != null); // Set user name. views.userName.setText(activity.getActor().getDisplayName()); if (activity.getActor().getImage() != null) { imageFetcher.loadThumbnailImage(activity.getActor().getImage().getUrl(), views.userImage, R.drawable.person_image_empty); } else { views.userImage.setImageResource(R.drawable.person_image_empty); } // Set +1 and comment counts. final int plusOneCount = (activity.getObject().getPlusoners() != null) ? activity.getObject().getPlusoners().getTotalItems().intValue() : 0; if (plusOneCount == 0) { views.plusOneIcon.setVisibility(View.GONE); views.plusOneCount.setVisibility(View.GONE); } else { views.plusOneIcon.setVisibility(View.VISIBLE); views.plusOneCount.setVisibility(View.VISIBLE); views.plusOneCount.setText(Integer.toString(plusOneCount)); } final int commentCount = (activity.getObject().getReplies() != null) ? activity.getObject().getReplies().getTotalItems().intValue() : 0; if (commentCount == 0) { views.commentIcon.setVisibility(View.GONE); views.commentCount.setVisibility(View.GONE); } else { views.commentIcon.setVisibility(View.VISIBLE); views.commentCount.setVisibility(View.VISIBLE); views.commentCount.setText(Integer.toString(commentCount)); } // Set content. String selfContent = isReshare ? activity.getAnnotation() : activity.getObject().getContent(); if (!TextUtils.isEmpty(selfContent)) { views.content.setVisibility(View.VISIBLE); views.content.setText(Html.fromHtml(selfContent)); } else { views.content.setVisibility(View.GONE); } // Set original author. if (activity.getObject().getActor() != null) { views.originalAuthor.setVisibility(View.VISIBLE); views.originalAuthor.setText(res.getString(R.string.stream_originally_shared, activity.getObject().getActor().getDisplayName())); views.reshareLine.setVisibility(View.VISIBLE); views.reshareSpacer.setVisibility(View.INVISIBLE); } else { views.originalAuthor.setVisibility(View.GONE); views.reshareLine.setVisibility(View.GONE); views.reshareSpacer.setVisibility(View.GONE); } // Set document content. if (isReshare && !TextUtils.isEmpty(activity.getObject().getContent()) && detailIndex < views.detail.length) { views.detail[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setTextColor(res.getColor(R.color.stream_content_color)); views.detail[detailIndex].setText(Html.fromHtml(activity.getObject().getContent())); ++detailIndex; } // Set location. String location = activity.getPlaceName(); if (!TextUtils.isEmpty(location)) { location = activity.getAddress(); } if (!TextUtils.isEmpty(location)) { location = activity.getGeocode(); } if (!TextUtils.isEmpty(location) && detailIndex < views.detail.length) { views.detail[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setTextColor(res.getColor(R.color.stream_link_color)); views.detailIcon[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setText(location); if ("checkin".equals(activity.getVerb())) { views.detailIcon[detailIndex].setImageResource(R.drawable.stream_ic_checkin); } else { views.detailIcon[detailIndex].setImageResource(R.drawable.stream_ic_location); } ++detailIndex; } // Set media content. if (activity.getObject().getAttachments() != null) { for (Activity.PlusObject.Attachments attachment : activity.getObject().getAttachments()) { String objectType = attachment.getObjectType(); if (("photo".equals(objectType) || "video".equals(objectType)) && mediaIndex < views.media.length) { if (attachment.getImage() == null) { continue; } final ImageView mediaView = views.media[mediaIndex]; mediaView.setVisibility(View.VISIBLE); imageFetcher.loadThumbnailImage(attachment.getImage().getUrl(), mediaView); if ("video".equals(objectType)) { views.mediaOverlay[mediaIndex].setVisibility(View.VISIBLE); } ++mediaIndex; } else if (("article".equals(objectType)) && detailIndex < views.detail.length) { try { String faviconUrl = "http://www.google.com/s2/favicons?domain=" + Uri.parse(attachment.getUrl()).getHost(); final ImageView iconView = views.detailIcon[detailIndex]; iconView.setVisibility(View.VISIBLE); imageFetcher.loadThumbnailImage(faviconUrl, iconView); } catch (ParseException ignored) {} views.detail[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setTextColor( res.getColor(R.color.stream_link_color)); views.detail[detailIndex].setText(attachment.getDisplayName()); ++detailIndex; } } } } } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.TracksAdapter.TracksQuery; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; /** * A simple {@link ListFragment} that renders a list of tracks and a map button at the top. */ public class ExploreFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private TracksAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new TracksAdapter(getActivity()); setListAdapter(mAdapter); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // As of support library r8, calling initLoader for a fragment in a // FragmentPagerAdapter in the fragment's onCreate may cause the same LoaderManager to be // dealt to multiple fragments because their mIndex is -1 (haven't been added to the // activity yet). Thus, we do this in onActivityCreated. getLoaderManager().initLoader(TracksQuery._TOKEN, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate( R.layout.fragment_list_with_empty_container, container, false); root.setBackgroundColor(Color.WHITE); return root; } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(TracksQuery._TOKEN); if (loader != null) { loader.forceLoad(); } } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); getActivity().getContentResolver().unregisterContentObserver(mObserver); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { if (mAdapter.isMapItem(position)) { // Launch map of conference venue EasyTracker.getTracker().trackEvent( "Home Screen Dashboard", "Click", "Map", 0L); startActivity(new Intent(getActivity(), UIUtils.getMapActivityClass(getActivity()))); return; } final Cursor cursor = (Cursor) mAdapter.getItem(position); final String trackId; if (cursor != null) { trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); } else { trackId = ScheduleContract.Tracks.ALL_TRACK_ID; } final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.setData(trackUri); startActivity(intent); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); Uri tracksUri = intent.getData(); if (tracksUri == null) { tracksUri = ScheduleContract.Tracks.CONTENT_URI; } // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; return new CursorLoader(getActivity(), tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } mAdapter.setHasMapItem(true); mAdapter.setHasAllItem(true); mAdapter.changeCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.drawable.ColorDrawable; import android.provider.BaseColumns; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; /** * A {@link android.widget.CursorAdapter} that renders a {@link TracksQuery}, additionally showing * "Map" and/or "All tracks" list items at the top. */ public class TracksAdapter extends CursorAdapter { private static final int ALL_ITEM_ID = Integer.MAX_VALUE; private static final int MAP_ITEM_ID = Integer.MAX_VALUE - 1; private Activity mActivity; private boolean mHasAllItem; private boolean mHasMapItem; private int mPositionDisplacement; public TracksAdapter(Activity activity) { super(activity, null, false); mActivity = activity; } public void setHasAllItem(boolean hasAllItem) { mHasAllItem = hasAllItem; updatePositionDisplacement(); } public void setHasMapItem(boolean hasMapItem) { mHasMapItem = hasMapItem; updatePositionDisplacement(); } private void updatePositionDisplacement() { mPositionDisplacement = (mHasAllItem ? 1 : 0) + (mHasMapItem ? 1 : 0); } public boolean isMapItem(int position) { return mHasMapItem && position == 0; } public boolean isAllItem(int position) { return mHasAllItem && position == (mHasMapItem ? 1 : 0); } @Override public int getCount() { return super.getCount() + mPositionDisplacement; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isMapItem(position)) { if (convertView == null) { convertView = mActivity.getLayoutInflater().inflate( R.layout.list_item_track_map, parent, false); } return convertView; } else if (isAllItem(position)) { if (convertView == null) { convertView = mActivity.getLayoutInflater().inflate( R.layout.list_item_track, parent, false); } // Custom binding for the first item ((TextView) convertView.findViewById(android.R.id.text1)).setText( "(" + mActivity.getResources().getString(R.string.all_tracks) + ")"); convertView.findViewById(android.R.id.icon1).setVisibility(View.INVISIBLE); return convertView; } return super.getView(position - mPositionDisplacement, convertView, parent); } @Override public Object getItem(int position) { if (isMapItem(position) || isAllItem(position)) { return null; } return super.getItem(position - mPositionDisplacement); } @Override public long getItemId(int position) { if (isMapItem(position)) { return MAP_ITEM_ID; } else if (isAllItem(position)) { return ALL_ITEM_ID; } return super.getItemId(position - mPositionDisplacement); } @Override public boolean isEnabled(int position) { return (mHasAllItem && position == 0) || super.isEnabled(position - mPositionDisplacement); } @Override public int getViewTypeCount() { // Add an item type for the "All" and map views. return super.getViewTypeCount() + 2; } @Override public int getItemViewType(int position) { if (isMapItem(position)) { return getViewTypeCount() - 1; } else if (isAllItem(position)) { return getViewTypeCount() - 2; } return super.getItemViewType(position - mPositionDisplacement); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mActivity.getLayoutInflater().inflate(R.layout.list_item_track, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { final TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText(cursor.getString(TracksQuery.TRACK_NAME)); // Assign track color to visible block final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon1); iconView.setImageDrawable(new ColorDrawable(cursor.getInt(TracksQuery.TRACK_COLOR))); } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ public interface TracksQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, }; String[] PROJECTION_WITH_SESSIONS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.SESSIONS_COUNT, }; String[] PROJECTION_WITH_VENDORS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.VENDORS_COUNT, }; int _ID = 0; int TRACK_ID = 1; int TRACK_NAME = 2; int TRACK_ABSTRACT = 3; int TRACK_COLOR = 4; } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ImageFetcher; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragment; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows detail information for a developer sandbox company, including * company name, description, logo, etc. */ public class VendorDetailFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(VendorDetailFragment.class); private Uri mVendorUri; private TextView mName; private ImageView mLogo; private TextView mUrl; private TextView mDesc; private ImageFetcher mImageFetcher; public interface Callbacks { public void onTrackIdAvailable(String trackId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackIdAvailable(String trackId) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mVendorUri = intent.getData(); if (mVendorUri == null) { return; } mImageFetcher = UIUtils.getImageFetcher(getActivity()); mImageFetcher.setImageFadeIn(false); setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mVendorUri == null) { return; } // Start background query to load vendor details getLoaderManager().initLoader(VendorsQuery._TOKEN, null, this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onPause() { super.onPause(); mImageFetcher.flushCache(); } @Override public void onDestroy() { super.onDestroy(); mImageFetcher.closeCache(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_vendor_detail, null); mName = (TextView) rootView.findViewById(R.id.vendor_name); mLogo = (ImageView) rootView.findViewById(R.id.vendor_logo); mUrl = (TextView) rootView.findViewById(R.id.vendor_url); mDesc = (TextView) rootView.findViewById(R.id.vendor_desc); return rootView; } public void buildUiFromCursor(Cursor cursor) { if (getActivity() == null) { return; } if (!cursor.moveToFirst()) { return; } String nameString = cursor.getString(VendorsQuery.NAME); mName.setText(nameString); // Start background fetch to load vendor logo final String logoUrl = cursor.getString(VendorsQuery.LOGO_URL); if (!TextUtils.isEmpty(logoUrl)) { mImageFetcher.loadThumbnailImage(logoUrl, mLogo, R.drawable.sandbox_logo_empty); } mUrl.setText(cursor.getString(VendorsQuery.URL)); mDesc.setText(cursor.getString(VendorsQuery.DESC)); EasyTracker.getTracker().trackView("Sandbox Vendor: " + nameString); LOGD("Tracker", "Sandbox Vendor: " + nameString); mCallbacks.onTrackIdAvailable(cursor.getString(VendorsQuery.TRACK_ID)); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mVendorUri, VendorsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { buildUiFromCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} * query parameters. */ private interface VendorsQuery { int _TOKEN = 0x4; String[] PROJECTION = { ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.VENDOR_DESC, ScheduleContract.Vendors.VENDOR_URL, ScheduleContract.Vendors.VENDOR_LOGO_URL, ScheduleContract.Vendors.TRACK_ID, }; int NAME = 0; int DESC = 1; int URL = 2; int LOGO_URL = 3; int TRACK_ID = 4; } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AccountUtils; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.accounts.Account; import android.accounts.AccountManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.Arrays; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The first activity most users see. This wizard-like activity first presents an account * selection fragment ({@link ChooseAccountFragment}), and then an authentication progress fragment * ({@link AuthProgressFragment}). */ public class AccountActivity extends SherlockFragmentActivity implements AccountUtils.AuthenticateCallback { private static final String TAG = makeLogTag(AccountActivity.class); public static final String EXTRA_FINISH_INTENT = "com.google.android.iosched.extra.FINISH_INTENT"; private static final int REQUEST_AUTHENTICATE = 100; private final Handler mHandler = new Handler(); private Account mChosenAccount; private Intent mFinishIntent; private boolean mCancelAuth = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_account); if (getIntent().hasExtra(EXTRA_FINISH_INTENT)) { mFinishIntent = getIntent().getParcelableExtra(EXTRA_FINISH_INTENT); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, new ChooseAccountFragment(), "choose_account") .commit(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_AUTHENTICATE) { if (resultCode == RESULT_OK) { tryAuthenticate(); } else { // go back to previous step mHandler.post(new Runnable() { @Override public void run() { getSupportFragmentManager().popBackStack(); } }); } } else { super.onActivityResult(requestCode, resultCode, data); } } private void tryAuthenticate() { AccountUtils.tryAuthenticate(AccountActivity.this, AccountActivity.this, REQUEST_AUTHENTICATE, mChosenAccount); } @Override public boolean shouldCancelAuthentication() { return mCancelAuth; } @Override public void onAuthTokenAvailable(String authToken) { ContentResolver.setIsSyncable(mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, 1); if (mFinishIntent != null) { mFinishIntent.addCategory(Intent.CATEGORY_LAUNCHER); mFinishIntent.setAction(Intent.ACTION_MAIN); mFinishIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mFinishIntent); } finish(); } /** * A fragment that presents the user with a list of accounts to choose from. Once an account is * selected, we move on to the login progress fragment ({@link AuthProgressFragment}). */ public static class ChooseAccountFragment extends SherlockListFragment { public ChooseAccountFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); reloadAccountList(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.add_account, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_add_account) { Intent addAccountIntent = new Intent(Settings.ACTION_ADD_ACCOUNT); addAccountIntent.putExtra(Settings.EXTRA_AUTHORITIES, new String[]{ScheduleContract.CONTENT_AUTHORITY}); startActivity(addAccountIntent); return true; } return super.onOptionsItemSelected(item); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate( R.layout.fragment_login_choose_account, container, false); TextView descriptionView = (TextView) rootView.findViewById(R.id.choose_account_intro); descriptionView.setText(Html.fromHtml(getString(R.string.description_choose_account))); return rootView; } private AccountListAdapter mAccountListAdapter; private void reloadAccountList() { if (mAccountListAdapter != null) { mAccountListAdapter = null; } AccountManager am = AccountManager.get(getActivity()); Account[] accounts = am.getAccountsByType(GoogleAccountManager.ACCOUNT_TYPE); mAccountListAdapter = new AccountListAdapter(getActivity(), Arrays.asList(accounts)); setListAdapter(mAccountListAdapter); } private class AccountListAdapter extends ArrayAdapter<Account> { private static final int LAYOUT_RESOURCE = android.R.layout.simple_list_item_1; public AccountListAdapter(Context context, List<Account> accounts) { super(context, LAYOUT_RESOURCE, accounts); } private class ViewHolder { TextView text1; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = getLayoutInflater(null).inflate(LAYOUT_RESOURCE, null); holder = new ViewHolder(); holder.text1 = (TextView) convertView.findViewById(android.R.id.text1); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final Account account = getItem(position); if (account != null) { holder.text1.setText(account.name); } else { holder.text1.setText(""); } return convertView; } } @Override public void onListItemClick(ListView l, View v, int position, long id) { AccountActivity activity = (AccountActivity) getActivity(); ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork == null || !activeNetwork.isConnected()) { Toast.makeText(activity, R.string.no_connection_cant_login, Toast.LENGTH_SHORT).show(); return; } activity.mCancelAuth = false; activity.mChosenAccount = mAccountListAdapter.getItem(position); activity.getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, new AuthProgressFragment(), "loading") .addToBackStack("choose_account") .commit(); activity.tryAuthenticate(); } } /** * This fragment shows a login progress spinner. Upon reaching a timeout of 7 seconds (in case * of a poor network connection), the user can try again. */ public static class AuthProgressFragment extends SherlockFragment { private static final int TRY_AGAIN_DELAY_MILLIS = 7 * 1000; // 7 seconds private final Handler mHandler = new Handler(); public AuthProgressFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_login_loading, container, false); final View takingAWhilePanel = rootView.findViewById(R.id.taking_a_while_panel); final View tryAgainButton = rootView.findViewById(R.id.retry_button); tryAgainButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getFragmentManager().popBackStack(); } }); mHandler.postDelayed(new Runnable() { @Override public void run() { if (!isAdded()) { return; } takingAWhilePanel.setVisibility(View.VISIBLE); } }, TRY_AGAIN_DELAY_MILLIS); return rootView; } @Override public void onDetach() { super.onDetach(); ((AccountActivity) getActivity()).mCancelAuth = true; } } }
Java
/* * Copyright 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.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import android.annotation.TargetApi; import android.app.FragmentBreadCrumbs; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; /** * A multi-pane activity, where the full-screen content is a {@link MapFragment} and popup content * may be visible at any given time, containing either a {@link SessionsFragment} (representing * sessions for a given room) or a {@link SessionDetailFragment}. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MapMultiPaneActivity extends BaseActivity implements FragmentManager.OnBackStackChangedListener, MapFragment.Callbacks, SessionsFragment.Callbacks, LoaderManager.LoaderCallbacks<Cursor> { private boolean mPauseBackStackWatcher = false; private FragmentBreadCrumbs mFragmentBreadCrumbs; private String mSelectedRoomName; private MapFragment mMapFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); FragmentManager fm = getSupportFragmentManager(); fm.addOnBackStackChangedListener(this); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mMapFragment = (MapFragment) fm.findFragmentByTag("map"); if (mMapFragment == null) { mMapFragment = new MapFragment(); mMapFragment.setArguments(intentToFragmentArguments(getIntent())); fm.beginTransaction() .add(R.id.fragment_container_map, mMapFragment, "map") .commit(); } findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { clearBackStack(false); } }); updateBreadCrumbs(); onConfigurationChanged(getResources().getConfiguration()); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean landscape = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE); LinearLayout spacerView = (LinearLayout) findViewById(R.id.map_detail_spacer); spacerView.setOrientation(landscape ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); spacerView.setGravity(landscape ? Gravity.RIGHT : Gravity.BOTTOM); View popupView = findViewById(R.id.map_detail_popup); LinearLayout.LayoutParams popupLayoutParams = (LinearLayout.LayoutParams) popupView.getLayoutParams(); popupLayoutParams.width = landscape ? 0 : ViewGroup.LayoutParams.MATCH_PARENT; popupLayoutParams.height = landscape ? ViewGroup.LayoutParams.MATCH_PARENT : 0; popupView.setLayoutParams(popupLayoutParams); popupView.requestLayout(); } private void clearBackStack(boolean pauseWatcher) { if (pauseWatcher) { mPauseBackStackWatcher = true; } FragmentManager fm = getSupportFragmentManager(); while (fm.getBackStackEntryCount() > 0) { fm.popBackStackImmediate(); } if (pauseWatcher) { mPauseBackStackWatcher = false; } } public void onBackStackChanged() { if (mPauseBackStackWatcher) { return; } if (getSupportFragmentManager().getBackStackEntryCount() == 0) { showDetailPane(false); } updateBreadCrumbs(); } private void showDetailPane(boolean show) { View detailPopup = findViewById(R.id.map_detail_spacer); if (show != (detailPopup.getVisibility() == View.VISIBLE)) { detailPopup.setVisibility(show ? View.VISIBLE : View.GONE); // Pan the map left or up depending on the orientation. boolean landscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; mMapFragment.panBy( landscape ? (show ? 0.25f : -0.25f) : 0, landscape ? 0 : (show ? 0.25f : -0.25f)); } } public void updateBreadCrumbs() { final String title = (mSelectedRoomName != null) ? mSelectedRoomName : getString(R.string.title_sessions); final String detailTitle = getString(R.string.title_session_detail); if (getSupportFragmentManager().getBackStackEntryCount() >= 2) { mFragmentBreadCrumbs.setParentTitle(title, title, mFragmentBreadCrumbsClickListener); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(title, title); } } private View.OnClickListener mFragmentBreadCrumbsClickListener = new View.OnClickListener() { @Override public void onClick(View view) { getSupportFragmentManager().popBackStack(); } }; @Override public void onRoomSelected(String roomId) { // Load room details mSelectedRoomName = null; Bundle loadRoomDataArgs = new Bundle(); loadRoomDataArgs.putString("room_id", roomId); getSupportLoaderManager().restartLoader(0, loadRoomDataArgs, this); // force load // Show the sessions in the room clearBackStack(true); showDetailPane(true); SessionsFragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, ScheduleContract.Rooms.buildSessionsDirUri(roomId)))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .addToBackStack(null) .commit(); updateBreadCrumbs(); } @Override public boolean onSessionSelected(String sessionId) { // Show the session details showDetailPane(true); SessionDetailFragment fragment = new SessionDetailFragment(); Intent intent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId)); intent.putExtra(SessionDetailFragment.EXTRA_VARIABLE_HEIGHT_HEADER, true); fragment.setArguments(BaseActivity.intentToFragmentArguments(intent)); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .addToBackStack(null) .commit(); updateBreadCrumbs(); return false; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(this, ScheduleContract.Rooms.buildRoomUri(data.getString("room_id")), RoomsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } mSelectedRoomName = cursor.getString(RoomsQuery.ROOM_NAME); updateBreadCrumbs(); } finally { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } private interface RoomsQuery { String[] PROJECTION = { ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_FLOOR, }; int ROOM_ID = 0; int ROOM_NAME = 1; int ROOM_FLOOR = 2; } }
Java
/* * Copyright 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.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.TracksAdapter; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragment; import android.annotation.TargetApi; import android.app.Activity; import android.content.res.Resources; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; /** * A tablet-specific fragment that emulates a giant {@link android.widget.Spinner}-like widget. * When touched, it shows a {@link ListPopupWindow} containing a list of tracks, * using {@link TracksAdapter}. Requires API level 11 or later since {@link ListPopupWindow} is * API level 11+. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class TracksDropdownFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener, PopupWindow.OnDismissListener { public static final String VIEW_TYPE_SESSIONS = "sessions"; public static final String VIEW_TYPE_VENDORS = "vendors"; private static final String STATE_VIEW_TYPE = "viewType"; private static final String STATE_SELECTED_TRACK_ID = "selectedTrackId"; private TracksAdapter mAdapter; private String mViewType; private Handler mHandler = new Handler(); private ListPopupWindow mListPopupWindow; private ViewGroup mRootView; private TextView mTitle; private TextView mAbstract; private String mTrackId; public interface Callbacks { public void onTrackSelected(String trackId); public void onTrackNameAvailable(String trackId, String trackName); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackSelected(String trackId) { } @Override public void onTrackNameAvailable(String trackId, String trackName) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new TracksAdapter(getActivity()); if (savedInstanceState != null) { // Since this fragment doesn't rely on fragment arguments, we must // handle // state restores and saves ourselves. mViewType = savedInstanceState.getString(STATE_VIEW_TYPE); mTrackId = savedInstanceState.getString(STATE_SELECTED_TRACK_ID); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_VIEW_TYPE, mViewType); outState.putString(STATE_SELECTED_TRACK_ID, mTrackId); } public String getSelectedTrackId() { return mTrackId; } public void selectTrack(String trackId) { loadTrackList(mViewType, trackId); } public void loadTrackList(String viewType) { loadTrackList(viewType, mTrackId); } public void loadTrackList(String viewType, String selectTrackId) { // Teardown from previous arguments if (mListPopupWindow != null) { mListPopupWindow.setAdapter(null); } mViewType = viewType; mTrackId = selectTrackId; // Start background query to load tracks getLoaderManager().restartLoader(TracksAdapter.TracksQuery._TOKEN, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_tracks_dropdown, null); mTitle = (TextView) mRootView.findViewById(R.id.track_title); mAbstract = (TextView) mRootView.findViewById(R.id.track_abstract); mRootView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mListPopupWindow = new ListPopupWindow(getActivity()); mListPopupWindow.setAdapter(mAdapter); mListPopupWindow.setModal(true); mListPopupWindow.setContentWidth( getResources().getDimensionPixelSize(R.dimen.track_dropdown_width)); mListPopupWindow.setAnchorView(mRootView); mListPopupWindow.setOnItemClickListener(TracksDropdownFragment.this); mListPopupWindow.show(); mListPopupWindow.setOnDismissListener(TracksDropdownFragment.this); } }); return mRootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } /** {@inheritDoc} */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); loadTrack(cursor, true); if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } public String getTrackName() { return (String) mTitle.getText(); } private void loadTrack(Cursor cursor, boolean triggerCallback) { final int trackColor; final Resources res = getResources(); if (cursor != null) { trackColor = cursor.getInt(TracksAdapter.TracksQuery.TRACK_COLOR); mTrackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); mTitle.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_NAME)); mAbstract.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_ABSTRACT)); } else { trackColor = res.getColor(R.color.all_track_color); mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID; mTitle.setText(VIEW_TYPE_SESSIONS.equals(mViewType) ? R.string.all_tracks_sessions : R.string.all_tracks_vendors); mAbstract.setText(VIEW_TYPE_SESSIONS.equals(mViewType) ? R.string.all_tracks_subtitle_sessions : R.string.all_tracks_subtitle_vendors); } boolean isDark = UIUtils.isColorDark(trackColor); mRootView.setBackgroundColor(trackColor); if (isDark) { mTitle.setTextColor(res.getColor(R.color.body_text_1_inverse)); mAbstract.setTextColor(res.getColor(R.color.body_text_2_inverse)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_light); } else { mTitle.setTextColor(res.getColor(R.color.body_text_1)); mAbstract.setTextColor(res.getColor(R.color.body_text_2)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_dark); } mCallbacks.onTrackNameAvailable(mTrackId, mTitle.getText().toString()); if (triggerCallback) { mHandler.post(new Runnable() { @Override public void run() { mCallbacks.onTrackSelected(mTrackId); } }); } } public void onDismiss() { mListPopupWindow = null; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; if (VIEW_TYPE_SESSIONS.equals(mViewType)) { // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; } else if (VIEW_TYPE_VENDORS.equals(mViewType)) { // Only show tracks with at least one vendor projection = TracksAdapter.TracksQuery.PROJECTION_WITH_VENDORS_COUNT; selection = ScheduleContract.Tracks.VENDORS_COUNT + ">0"; } return new CursorLoader(getActivity(), ScheduleContract.Tracks.CONTENT_URI, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null || cursor == null) { return; } boolean trackLoaded = false; if (mTrackId != null) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { if (mTrackId.equals(cursor.getString(TracksAdapter.TracksQuery.TRACK_ID))) { loadTrack(cursor, false); trackLoaded = true; break; } cursor.moveToNext(); } } if (!trackLoaded) { loadTrack(null, false); } mAdapter.setHasAllItem(true); mAdapter.changeCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> cursor) { } }
Java
/* * Copyright 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.android.apps.iosched.ui.tablet; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.ui.widget.ShowHideMasterLayout; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.widget.SearchView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment} (top-left), a * {@link SessionsFragment} or {@link VendorsFragment} (bottom-left), and * a {@link SessionDetailFragment} or {@link VendorDetailFragment} (right pane). */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SessionsVendorsMultiPaneActivity extends BaseActivity implements ActionBar.TabListener, SessionsFragment.Callbacks, VendorsFragment.Callbacks, VendorDetailFragment.Callbacks, TracksDropdownFragment.Callbacks, TrackInfoHelperFragment.Callbacks { public static final String EXTRA_MASTER_URI = "com.google.android.apps.iosched.extra.MASTER_URI"; private static final String STATE_VIEW_TYPE = "view_type"; private TracksDropdownFragment mTracksDropdownFragment; private Fragment mDetailFragment; private boolean mFullUI = false; private ShowHideMasterLayout mShowHideMasterLayout; private String mViewType; private boolean mInitialTabSelect = true; @Override protected void onCreate(Bundle savedInstanceState) { if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) { BeamUtils.setBeamUnlocked(this); showFirstBeamDialog(); } BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); trySetBeamCallback(); setContentView(R.layout.activity_sessions_vendors); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mShowHideMasterLayout = (ShowHideMasterLayout) findViewById(R.id.show_hide_master_layout); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.setFlingToExposeMasterEnabled(true); } routeIntent(getIntent(), savedInstanceState != null); if (savedInstanceState != null) { if (mFullUI) { getSupportActionBar().setSelectedNavigationItem( TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals( savedInstanceState.getString(STATE_VIEW_TYPE)) ? 0 : 1); } mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail); updateDetailBackground(); } // This flag prevents onTabSelected from triggering extra master pane reloads // unless it's actually being triggered by the user (and not automatically by // the system) mInitialTabSelect = false; EasyTracker.getTracker().setContext(this); } private void routeIntent(Intent intent, boolean updateSurfaceOnly) { Uri uri = intent.getData(); if (uri == null) { return; } if (intent.hasExtra(Intent.EXTRA_TITLE)) { setTitle(intent.getStringExtra(Intent.EXTRA_TITLE)); } String mimeType = getContentResolver().getType(uri); if (ScheduleContract.Tracks.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load track details showFullUI(true); if (!updateSurfaceOnly) { // TODO: don't assume the URI will contain the track ID String selectedTrackId = ScheduleContract.Tracks.getTrackId(uri); loadTrackList(TracksDropdownFragment.VIEW_TYPE_SESSIONS, selectedTrackId); onTrackSelected(selectedTrackId); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE); } } } else if (ScheduleContract.Sessions.CONTENT_TYPE.equals(mimeType)) { // Load a session list, hiding the tracks dropdown and the tabs mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; showFullUI(false); if (!updateSurfaceOnly) { loadSessionList(uri, null); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE); } } } else if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load session details if (intent.hasExtra(EXTRA_MASTER_URI)) { mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; showFullUI(false); if (!updateSurfaceOnly) { loadSessionList((Uri) intent.getParcelableExtra(EXTRA_MASTER_URI), ScheduleContract.Sessions.getSessionId(uri)); loadSessionDetail(uri); } } else { mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; // prepare for onTrackInfo... showFullUI(true); if (!updateSurfaceOnly) { loadSessionDetail(uri); loadTrackInfoFromSessionUri(uri); } } } else if (ScheduleContract.Vendors.CONTENT_TYPE.equals(mimeType)) { // Load a vendor list mViewType = TracksDropdownFragment.VIEW_TYPE_VENDORS; showFullUI(false); if (!updateSurfaceOnly) { loadVendorList(uri, null); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE); } } } else if (ScheduleContract.Vendors.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load vendor details mViewType = TracksDropdownFragment.VIEW_TYPE_VENDORS; showFullUI(false); if (!updateSurfaceOnly) { Uri masterUri = (Uri) intent.getParcelableExtra(EXTRA_MASTER_URI); if (masterUri == null) { masterUri = ScheduleContract.Vendors.CONTENT_URI; } loadVendorList(masterUri, ScheduleContract.Vendors.getVendorId(uri)); loadVendorDetail(uri); } } updateDetailBackground(); } private void showFullUI(boolean fullUI) { mFullUI = fullUI; final ActionBar actionBar = getSupportActionBar(); final FragmentManager fm = getSupportFragmentManager(); if (fullUI) { actionBar.removeAllTabs(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(false); actionBar.addTab(actionBar.newTab() .setText(R.string.title_sessions) .setTag(TracksDropdownFragment.VIEW_TYPE_SESSIONS) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_vendors) .setTag(TracksDropdownFragment.VIEW_TYPE_VENDORS) .setTabListener(this)); fm.beginTransaction() .show(fm.findFragmentById(R.id.fragment_tracks_dropdown)) .commit(); } else { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); fm.beginTransaction() .hide(fm.findFragmentById(R.id.fragment_tracks_dropdown)) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.search, menu); MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (mShowHideMasterLayout != null && !mShowHideMasterLayout.isMasterVisible()) { // If showing the detail view, pressing Up should show the master pane. mShowHideMasterLayout.showMaster(true, 0); return true; } break; case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_VIEW_TYPE, mViewType); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { loadTrackList((String) tab.getTag()); if (!mInitialTabSelect) { onTrackSelected(mTracksDropdownFragment.getSelectedTrackId()); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, 0); } } } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } private void loadTrackList(String viewType) { loadTrackList(viewType, null); } private void loadTrackList(String viewType, String selectTrackId) { if (mDetailFragment != null && !mViewType.equals(viewType)) { getSupportFragmentManager().beginTransaction() .remove(mDetailFragment) .commit(); mDetailFragment = null; } mViewType = viewType; if (selectTrackId != null) { mTracksDropdownFragment.loadTrackList(viewType, selectTrackId); } else { mTracksDropdownFragment.loadTrackList(viewType); } updateDetailBackground(); } private void updateDetailBackground() { if (mDetailFragment == null) { if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white_empty_sessions); } else { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white_empty_sandbox); } } else { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white); } } private void loadSessionList(Uri sessionsUri, String selectSessionId) { SessionsFragment fragment = new SessionsFragment(); fragment.setSelectedSessionId(selectSessionId); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sessionsUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_master, fragment) .commit(); } private void loadSessionDetail(Uri sessionUri) { BeamUtils.setBeamSessionUri(this, sessionUri); SessionDetailFragment fragment = new SessionDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sessionUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); // If loading session details in portrait, hide the master pane if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(false, 0); } } private void loadVendorList(Uri vendorsUri, String selectVendorId) { VendorsFragment fragment = new VendorsFragment(); fragment.setSelectedVendorId(selectVendorId); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, vendorsUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_master, fragment) .commit(); } private void loadVendorDetail(Uri vendorUri) { VendorDetailFragment fragment = new VendorDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, vendorUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); // If loading session details in portrait, hide the master pane if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(false, 0); } } @Override public void onTrackNameAvailable(String trackId, String trackName) { String trackType; if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { trackType = getString(R.string.title_sessions); } else { trackType = getString(R.string.title_vendors); } EasyTracker.getTracker().trackView(trackType + ": " + getTitle()); LOGD("Tracker", trackType + ": " + mTracksDropdownFragment.getTrackName()); } @Override public void onTrackSelected(String trackId) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId)); if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { loadSessionList(allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId), null); } else { loadVendorList(allTracks ? ScheduleContract.Vendors.CONTENT_URI : ScheduleContract.Tracks.buildVendorsUri(trackId), null); } } @Override public boolean onSessionSelected(String sessionId) { loadSessionDetail(ScheduleContract.Sessions.buildSessionUri(sessionId)); return true; } @Override public boolean onVendorSelected(String vendorId) { loadVendorDetail(ScheduleContract.Vendors.buildVendorUri(vendorId)); return true; } private TrackInfoHelperFragment mTrackInfoHelperFragment; private String mTrackInfoLoadCookie; private void loadTrackInfoFromSessionUri(Uri sessionUri) { mTrackInfoLoadCookie = ScheduleContract.Sessions.getSessionId(sessionUri); Uri trackDirUri = ScheduleContract.Sessions.buildTracksDirUri( ScheduleContract.Sessions.getSessionId(sessionUri)); android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (mTrackInfoHelperFragment != null) { ft.remove(mTrackInfoHelperFragment); } mTrackInfoHelperFragment = TrackInfoHelperFragment.newFromTrackUri(trackDirUri); ft.add(mTrackInfoHelperFragment, "track_info").commit(); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { loadTrackList(mViewType, trackId); boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId)); if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { loadSessionList(allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId), mTrackInfoLoadCookie); } else { loadVendorList(allTracks ? ScheduleContract.Vendors.CONTENT_URI : ScheduleContract.Tracks.buildVendorsUri(trackId), mTrackInfoLoadCookie); } } @Override public void onTrackIdAvailable(String trackId) { } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void trySetBeamCallback() { if (UIUtils.hasICS()) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override public void onNdefPushComplete(NfcEvent event) { // Beam has been sent if (!BeamUtils.isBeamUnlocked(SessionsVendorsMultiPaneActivity.this)) { BeamUtils.setBeamUnlocked(SessionsVendorsMultiPaneActivity.this); runOnUiThread(new Runnable() { @Override public void run() { showFirstBeamDialog(); } }); } } }); } } private void showFirstBeamDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_session) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(SessionsVendorsMultiPaneActivity.this); di.dismiss(); } }) .create() .show(); } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.actionbarsherlock.app.SherlockFragment; import android.app.Activity; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; /** * A retained, non-UI helper fragment that loads track information such as name, color, etc. and * returns this information via {@link Callbacks#onTrackInfoAvailable(String, String, int)}. */ public class TrackInfoHelperFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor> { /** * The track URI for which to load data. */ public static final String ARG_TRACK = "com.google.android.iosched.extra.TRACK"; private Uri mTrackUri; // To be loaded private String mTrackId; private String mTrackName; private int mTrackColor; private Handler mHandler = new Handler(); public interface Callbacks { public void onTrackInfoAvailable(String trackId, String trackName, int trackColor); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { } }; private Callbacks mCallbacks = sDummyCallbacks; public static TrackInfoHelperFragment newFromSessionUri(Uri sessionUri) { return newFromTrackUri(ScheduleContract.Sessions.buildTracksDirUri( ScheduleContract.Sessions.getSessionId(sessionUri))); } public static TrackInfoHelperFragment newFromTrackUri(Uri trackUri) { TrackInfoHelperFragment f = new TrackInfoHelperFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_TRACK, trackUri); f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mTrackUri = getArguments().getParcelable(ARG_TRACK); if (ScheduleContract.Tracks.ALL_TRACK_ID.equals( ScheduleContract.Tracks.getTrackId(mTrackUri))) { mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID; mTrackName = getString(R.string.all_tracks); mTrackColor = getResources().getColor(android.R.color.white); mCallbacks.onTrackInfoAvailable(mTrackId, mTrackName, mTrackColor); } else { getLoaderManager().initLoader(0, null, this); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; if (mTrackId != null) { mHandler.post(new Runnable() { @Override public void run() { mCallbacks.onTrackInfoAvailable(mTrackId, mTrackName, mTrackColor); } }); } } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mTrackUri, TracksQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } mTrackId = cursor.getString(TracksQuery.TRACK_ID); mTrackName = cursor.getString(TracksQuery.TRACK_NAME); mTrackColor = cursor.getInt(TracksQuery.TRACK_COLOR); // Wrapping in a Handler.post allows users of this helper to commit fragment // transactions in the callback. new Handler().post(new Runnable() { @Override public void run() { mCallbacks.onTrackInfoAvailable(mTrackId, mTrackName, mTrackColor); } }); } finally { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { String[] PROJECTION = { ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int TRACK_ID = 0; int TRACK_NAME = 1; int TRACK_COLOR = 2; } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity; import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.apps.iosched.util.actionmodecompat.ActionMode; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows the user's customized schedule, including sessions that she has chosen, * and common conference items such as keynote sessions, lunch breaks, after hours party, etc. */ public class MyScheduleFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor>, ActionMode.Callback { private static final String TAG = makeLogTag(MyScheduleFragment.class); private SimpleSectionedListAdapter mAdapter; private MyScheduleAdapter mScheduleAdapter; private SparseArray<String> mLongClickedItemData; private View mLongClickedView; private ActionMode mActionMode; private boolean mScrollToNow; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // The MyScheduleAdapter is wrapped in a SimpleSectionedListAdapter so that // we can show list headers separating out the different days of the conference // (Wednesday/Thursday/Friday). mScheduleAdapter = new MyScheduleAdapter(getActivity()); mAdapter = new SimpleSectionedListAdapter(getActivity(), R.layout.list_item_schedule_header, mScheduleAdapter); setListAdapter(mAdapter); if (savedInstanceState == null) { mScrollToNow = true; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate( R.layout.fragment_list_with_empty_container, container, false); inflater.inflate(R.layout.empty_waiting_for_sync, (ViewGroup) root.findViewById(android.R.id.empty), true); root.setBackgroundColor(Color.WHITE); ListView listView = (ListView) root.findViewById(android.R.id.list); listView.setItemsCanFocus(true); listView.setCacheColorHint(Color.WHITE); listView.setSelector(android.R.color.transparent); //listView.setEmptyView(root.findViewById(android.R.id.empty)); return root; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // In support library r8, calling initLoader for a fragment in a // FragmentPagerAdapter in the fragment's onCreate may cause the same LoaderManager to be // dealt to multiple fragments because their mIndex is -1 (haven't been added to the // activity yet). Thus, we do this in onActivityCreated. getLoaderManager().initLoader(0, null, this); } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(0); if (loader != null) { loader.forceLoad(); } } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); getActivity().getContentResolver().unregisterContentObserver(mObserver); } // LoaderCallbacks @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, null, null, ScheduleContract.Blocks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } long currentTime = UIUtils.getCurrentTime(getActivity()); int firstNowPosition = ListView.INVALID_POSITION; List<SimpleSectionedListAdapter.Section> sections = new ArrayList<SimpleSectionedListAdapter.Section>(); cursor.moveToFirst(); long previousBlockStart = -1; long blockStart, blockEnd; while (!cursor.isAfterLast()) { blockStart = cursor.getLong(BlocksQuery.BLOCK_START); blockEnd = cursor.getLong(BlocksQuery.BLOCK_END); if (!UIUtils.isSameDay(previousBlockStart, blockStart)) { sections.add(new SimpleSectionedListAdapter.Section(cursor.getPosition(), DateUtils.formatDateTime(getActivity(), blockStart, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY))); } if (mScrollToNow && firstNowPosition == ListView.INVALID_POSITION // if we're currently in this block, or we're not in a block // and this // block is in the future, then this is the scroll position && ((blockStart < currentTime && currentTime < blockEnd) || blockStart > currentTime)) { firstNowPosition = cursor.getPosition(); } previousBlockStart = blockStart; cursor.moveToNext(); } mScheduleAdapter.changeCursor(cursor); SimpleSectionedListAdapter.Section[] dummy = new SimpleSectionedListAdapter.Section[sections.size()]; mAdapter.setSections(sections.toArray(dummy)); if (mScrollToNow && firstNowPosition != ListView.INVALID_POSITION) { firstNowPosition = mAdapter.positionToSectionedPosition(firstNowPosition); getListView().setSelectionFromTop(firstNowPosition, getResources().getDimensionPixelSize(R.dimen.list_scroll_top_offset)); mScrollToNow = false; } } @Override public void onLoaderReset(Loader<Cursor> loader) { } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); String title = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_TITLE); String hashtags = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_HASHTAGS); String url = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_URL); boolean handled = false; switch (item.getItemId()) { case R.id.menu_map: String roomId = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ROOM_ID); helper.startMapActivity(roomId); handled = true; break; case R.id.menu_star: String sessionId = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ID); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); helper.setSessionStarred(sessionUri, false, title); handled = true; break; case R.id.menu_share: // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. helper.shareSession(getActivity(), R.string.share_template, title, hashtags, url); handled = true; break; case R.id.menu_social_stream: helper.startSocialStream(hashtags); handled = true; break; default: LOGW(TAG, "Unknown action taken"); } mActionMode.finish(); return handled; } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.sessions_context, menu); MenuItem starMenuItem = menu.findItem(R.id.menu_star); starMenuItem.setTitle(R.string.description_remove_schedule); starMenuItem.setIcon(R.drawable.ic_action_remove_schedule); return true; } @Override public void onDestroyActionMode(ActionMode mode) { mActionMode = null; if (mLongClickedView != null) { UIUtils.setActivatedCompat(mLongClickedView, false); } } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } /** * A list adapter that shows schedule blocks as list items. It handles a number of different * cases, such as empty blocks where the user has not chosen a session, blocks with conflicts * (i.e. multiple sessions chosen), non-session blocks, etc. */ private class MyScheduleAdapter extends CursorAdapter { public MyScheduleAdapter(Context context) { super(context, null, false); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_schedule_block, parent, false); } @Override public void bindView(View view, Context context, final Cursor cursor) { final String type = cursor.getString(BlocksQuery.BLOCK_TYPE); final String blockId = cursor.getString(BlocksQuery.BLOCK_ID); final String blockTitle = cursor.getString(BlocksQuery.BLOCK_TITLE); final long blockStart = cursor.getLong(BlocksQuery.BLOCK_START); final long blockEnd = cursor.getLong(BlocksQuery.BLOCK_END); final String blockMeta = cursor.getString(BlocksQuery.BLOCK_META); final String blockTimeString = UIUtils.formatBlockTimeString(blockStart, blockEnd, context); final TextView timeView = (TextView) view.findViewById(R.id.block_time); final TextView titleView = (TextView) view.findViewById(R.id.block_title); final TextView subtitleView = (TextView) view.findViewById(R.id.block_subtitle); final ImageButton extraButton = (ImageButton) view.findViewById(R.id.extra_button); final View primaryTouchTargetView = view.findViewById(R.id.list_item_middle_container); final Resources res = getResources(); String subtitle; boolean isLiveStreamed = false; primaryTouchTargetView.setOnLongClickListener(null); UIUtils.setActivatedCompat(primaryTouchTargetView, false); if (ParserUtils.BLOCK_TYPE_SESSION.equals(type) || ParserUtils.BLOCK_TYPE_CODE_LAB.equals(type)) { final int numStarredSessions = cursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID); View.OnClickListener allSessionsListener = new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }; if (numStarredSessions == 0) { // 0 sessions starred titleView.setText(getString(R.string.schedule_empty_slot_title_template, TextUtils.isEmpty(blockTitle) ? "" : (" " + blockTitle.toLowerCase()))); titleView.setTextColor(res.getColorStateList(R.color.body_text_1_positive)); subtitle = getString(R.string.schedule_empty_slot_subtitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setOnClickListener(allSessionsListener); } else if (numStarredSessions == 1) { // exactly 1 session starred final String starredSessionTitle = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); titleView.setText(starredSessionTitle); titleView.setTextColor(res.getColorStateList(R.color.body_text_1)); subtitle = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (subtitle == null) { // TODO: remove this WAR for API not returning rooms for code labs subtitle = getString( starredSessionTitle.contains("Code Lab") ? R.string.codelab_room : R.string.unknown_room); } isLiveStreamed = !TextUtils.isEmpty( cursor.getString(BlocksQuery.STARRED_SESSION_LIVESTREAM_URL)); extraButton.setVisibility(View.VISIBLE); extraButton.setOnClickListener(allSessionsListener); if (mLongClickedItemData != null && mActionMode != null && mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ID, "").equals( starredSessionId)) { UIUtils.setActivatedCompat(primaryTouchTargetView, true); mLongClickedView = primaryTouchTargetView; } primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri( starredSessionId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.putExtra(SessionsVendorsMultiPaneActivity.EXTRA_MASTER_URI, ScheduleContract.Blocks.buildSessionsUri(blockId)); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }); primaryTouchTargetView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mActionMode != null) { // CAB already displayed, ignore return true; } mLongClickedView = primaryTouchTargetView; String hashtags = cursor.getString(BlocksQuery.STARRED_SESSION_HASHTAGS); String url = cursor.getString(BlocksQuery.STARRED_SESSION_URL); String roomId = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_ID); mLongClickedItemData = new SparseArray<String>(); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_ID, starredSessionId); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_TITLE, starredSessionTitle); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_HASHTAGS, hashtags); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_URL, url); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_ROOM_ID, roomId); mActionMode = ActionMode.start(getActivity(), MyScheduleFragment.this); UIUtils.setActivatedCompat(primaryTouchTargetView, true); return true; } }); } else { // 2 or more sessions starred titleView.setText(getString(R.string.schedule_conflict_title, numStarredSessions)); titleView.setTextColor(res.getColorStateList(R.color.body_text_1)); subtitle = getString(R.string.schedule_conflict_subtitle); extraButton.setVisibility(View.VISIBLE); extraButton.setOnClickListener(allSessionsListener); primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionsUri = ScheduleContract.Blocks .buildStarredSessionsUri( blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }); } subtitleView.setTextColor(res.getColorStateList(R.color.body_text_2)); primaryTouchTargetView.setEnabled(true); } else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(type)) { final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID); final String starredSessionTitle = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); long currentTimeMillis = UIUtils.getCurrentTime(context); boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < UIUtils.CONFERENCE_END_MILLIS); boolean present = !past && (currentTimeMillis >= blockStart); boolean canViewStream = present && UIUtils.hasHoneycomb(); isLiveStreamed = true; titleView.setTextColor(canViewStream ? res.getColorStateList(R.color.body_text_1) : res.getColorStateList(R.color.body_text_disabled)); subtitleView.setTextColor(canViewStream ? res.getColorStateList(R.color.body_text_2) : res.getColorStateList(R.color.body_text_disabled)); subtitle = getString(R.string.keynote_room); titleView.setText(starredSessionTitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setEnabled(canViewStream); primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri( starredSessionId); Intent livestreamIntent = new Intent(Intent.ACTION_VIEW, sessionUri); livestreamIntent.setClass(getActivity(), SessionLivestreamActivity.class); startActivity(livestreamIntent); } }); } else { titleView.setTextColor(res.getColorStateList(R.color.body_text_disabled)); subtitleView.setTextColor(res.getColorStateList(R.color.body_text_disabled)); subtitle = blockMeta; titleView.setText(blockTitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setEnabled(false); primaryTouchTargetView.setOnClickListener(null); } timeView.setText(DateUtils.formatDateTime(context, blockStart, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR)); // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, blockStart, blockEnd, isLiveStreamed, view, titleView, subtitleView, subtitle); } } private interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.BLOCK_META, ScheduleContract.Blocks.SESSIONS_COUNT, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_ID, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, ScheduleContract.Blocks.STARRED_SESSION_ROOM_ID, ScheduleContract.Blocks.STARRED_SESSION_HASHTAGS, ScheduleContract.Blocks.STARRED_SESSION_URL, ScheduleContract.Blocks.STARRED_SESSION_LIVESTREAM_URL, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int BLOCK_META = 6; int SESSIONS_COUNT = 7; int NUM_STARRED_SESSIONS = 8; int STARRED_SESSION_ID = 9; int STARRED_SESSION_TITLE = 10; int STARRED_SESSION_ROOM_NAME = 11; int STARRED_SESSION_ROOM_ID = 12; int STARRED_SESSION_HASHTAGS = 13; int STARRED_SESSION_URL = 14; int STARRED_SESSION_LIVESTREAM_URL = 15; } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.ReflectionUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.Html; import android.widget.SearchView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * An activity that shows session search results. This activity can be either single * or multi-pane, depending on the device configuration. */ public class SearchActivity extends BaseActivity implements SessionsFragment.Callbacks { private boolean mTwoPane; private SessionsFragment mSessionsFragment; private Fragment mDetailFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); mTwoPane = (findViewById(R.id.fragment_container_detail) != null); FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentById(R.id.fragment_container_master); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); fm.beginTransaction() .add(R.id.fragment_container_master, mSessionsFragment) .commit(); } mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); onNewIntent(getIntent()); } @Override public void onNewIntent(Intent intent) { setIntent(intent); String query = intent.getStringExtra(SearchManager.QUERY); setTitle(Html.fromHtml(getString(R.string.title_search_query, query))); mSessionsFragment.reloadFromArguments(intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, Sessions.buildSearchUri(query)))); EasyTracker.getTracker().trackView("Search: " + query); LOGD("Tracker", "Search: " + query); updateDetailBackground(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.search, menu); setupSearchMenuItem(menu); return true; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupSearchMenuItem(Menu menu) { final MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { ReflectionUtils.tryInvoke(searchItem, "collapseActionView"); return false; } @Override public boolean onQueryTextChange(String s) { return false; } }); searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { @Override public boolean onSuggestionSelect(int i) { return false; } @Override public boolean onSuggestionClick(int i) { ReflectionUtils.tryInvoke(searchItem, "collapseActionView"); return false; } }); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } private void updateDetailBackground() { if (mTwoPane) { findViewById(R.id.fragment_container_detail).setBackgroundResource( (mDetailFragment == null) ? R.drawable.grey_frame_on_white_empty_sessions : R.drawable.grey_frame_on_white); } } @Override public boolean onSessionSelected(String sessionId) { Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); Intent detailIntent = new Intent(Intent.ACTION_VIEW, sessionUri); if (mTwoPane) { BeamUtils.setBeamSessionUri(this, sessionUri); trySetBeamCallback(); SessionDetailFragment fragment = new SessionDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(detailIntent)); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); return true; } else { startActivity(detailIntent); return false; } } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void trySetBeamCallback() { if (UIUtils.hasICS()) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override public void onNdefPushComplete(NfcEvent event) { // Beam has been sent if (!BeamUtils.isBeamUnlocked(SearchActivity.this)) { BeamUtils.setBeamUnlocked(SearchActivity.this); runOnUiThread(new Runnable() { @Override public void run() { showFirstBeamDialog(); } }); } } }); } } private void showFirstBeamDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_session) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(SearchActivity.this); di.dismiss(); } }) .create() .show(); } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.gcm.ServerUtilities; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.gtv.GoogleTVSessionLivestreamActivity; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.HelpUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.gcm.GCMRegistrar; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.accounts.Account; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.ContentResolver; import android.content.Intent; import android.content.SyncStatusObserver; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.widget.SearchView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The landing screen for the app, once the user has logged in. * * <p>This activity uses different layouts to present its various fragments, depending on the * device configuration. {@link MyScheduleFragment}, {@link ExploreFragment}, and * {@link SocialStreamFragment} are always available to the user. {@link WhatsOnFragment} is * always available on tablets and phones in portrait, but is hidden on phones held in landscape. * * <p>On phone-size screens, the three fragments are represented by {@link ActionBar} tabs, and * can are held inside a {@link ViewPager} to allow horizontal swiping. * * <p>On tablets, the three fragments are always visible and are presented as either three panes * (landscape) or a grid (portrait). */ public class HomeActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private static final String TAG = makeLogTag(HomeActivity.class); private Object mSyncObserverHandle; private MyScheduleFragment mMyScheduleFragment; private ExploreFragment mExploreFragment; private SocialStreamFragment mSocialStreamFragment; private ViewPager mViewPager; private Menu mOptionsMenu; private AsyncTask<Void, Void, Void> mGCMRegisterTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We're on Google TV; immediately short-circuit the normal behavior and show the // Google TV-specific landing page. if (UIUtils.isGoogleTV(this)) { Intent intent = new Intent(HomeActivity.this, GoogleTVSessionLivestreamActivity.class); startActivity(intent); finish(); } if (isFinishing()) { return; } UIUtils.enableDisableActivities(this); EasyTracker.getTracker().setContext(this); setContentView(R.layout.activity_home); FragmentManager fm = getSupportFragmentManager(); mViewPager = (ViewPager) findViewById(R.id.pager); String homeScreenLabel; if (mViewPager != null) { // Phone setup mViewPager.setAdapter(new HomePagerAdapter(getSupportFragmentManager())); mViewPager.setOnPageChangeListener(this); mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); mViewPager.setPageMargin(getResources() .getDimensionPixelSize(R.dimen.page_margin_width)); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.addTab(actionBar.newTab() .setText(R.string.title_my_schedule) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_explore) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_stream) .setTabListener(this)); homeScreenLabel = getString(R.string.title_my_schedule); } else { mExploreFragment = (ExploreFragment) fm.findFragmentById(R.id.fragment_tracks); mMyScheduleFragment = (MyScheduleFragment) fm.findFragmentById( R.id.fragment_my_schedule); mSocialStreamFragment = (SocialStreamFragment) fm.findFragmentById(R.id.fragment_stream); homeScreenLabel = "Home"; } getSupportActionBar().setHomeButtonEnabled(false); EasyTracker.getTracker().trackView(homeScreenLabel); LOGD("Tracker", homeScreenLabel); // Sync data on load if (savedInstanceState == null) { triggerRefresh(); registerGCMClient(); } } private void registerGCMClient() { GCMRegistrar.checkDevice(this); if (BuildConfig.DEBUG) { GCMRegistrar.checkManifest(this); } final String regId = GCMRegistrar.getRegistrationId(this); if (TextUtils.isEmpty(regId)) { // Automatically registers application on startup. GCMRegistrar.register(this, Config.GCM_SENDER_ID); } else { // Device is already registered on GCM, check server. if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration LOGI(TAG, "Already registered on the GCM server"); } else { // Try to register again, but not on the UI thread. // It's also necessary to cancel the task in onDestroy(). mGCMRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { boolean registered = ServerUtilities.register(HomeActivity.this, regId); if (!registered) { // At this point all attempts to register with the app // server failed, so we need to unregister the device // from GCM - the app will try to register again when // it is restarted. Note that GCM will send an // unregistered callback upon completion, but // GCMIntentService.onUnregistered() will ignore it. GCMRegistrar.unregister(HomeActivity.this); } return null; } @Override protected void onPostExecute(Void result) { mGCMRegisterTask = null; } }; mGCMRegisterTask.execute(null, null, null); } } } @Override protected void onDestroy() { super.onDestroy(); if (mGCMRegisterTask != null) { mGCMRegisterTask.cancel(true); } try { GCMRegistrar.onDestroy(this); } catch (Exception e) { LOGW(TAG, "GCM unregistration error", e); } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int position) { getSupportActionBar().setSelectedNavigationItem(position); int titleId = -1; switch (position) { case 0: titleId = R.string.title_my_schedule; break; case 1: titleId = R.string.title_explore; break; case 2: titleId = R.string.title_stream; break; } String title = getString(titleId); EasyTracker.getTracker().trackView(title); LOGD("Tracker", title); } @Override public void onPageScrollStateChanged(int i) { } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Since the pager fragments don't have known tags or IDs, the only way to persist the // reference is to use putFragment/getFragment. Remember, we're not persisting the exact // Fragment instance. This mechanism simply gives us a way to persist access to the // 'current' fragment instance for the given fragment (which changes across orientation // changes). // // The outcome of all this is that the "Refresh" menu button refreshes the stream across // orientation changes. if (mSocialStreamFragment != null) { getSupportFragmentManager().putFragment(outState, "stream_fragment", mSocialStreamFragment); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (mSocialStreamFragment == null) { mSocialStreamFragment = (SocialStreamFragment) getSupportFragmentManager() .getFragment(savedInstanceState, "stream_fragment"); } } private class HomePagerAdapter extends FragmentPagerAdapter { public HomePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: return (mMyScheduleFragment = new MyScheduleFragment()); case 1: return (mExploreFragment = new ExploreFragment()); case 2: return (mSocialStreamFragment = new SocialStreamFragment()); } return null; } @Override public int getCount() { return 3; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); mOptionsMenu = menu; getSupportMenuInflater().inflate(R.menu.home, menu); setupSearchMenuItem(menu); if (!BeamUtils.isBeamUnlocked(this)) { // Only show Beam unlocked after first Beam MenuItem beamItem = menu.findItem(R.id.menu_beam); if (beamItem != null) { menu.removeItem(beamItem.getItemId()); } } return true; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupSearchMenuItem(Menu menu) { MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: triggerRefresh(); return true; case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; case R.id.menu_about: HelpUtils.showAbout(this); return true; case R.id.menu_sign_out: AccountUtils.signOut(this); finish(); return true; case R.id.menu_beam: Intent beamIntent = new Intent(this, BeamActivity.class); startActivity(beamIntent); return true; } return super.onOptionsItemSelected(item); } private void triggerRefresh() { Bundle extras = new Bundle(); extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); if (!UIUtils.isGoogleTV(this)) { ContentResolver.requestSync( new Account(AccountUtils.getChosenAccountName(this), GoogleAccountManager.ACCOUNT_TYPE), ScheduleContract.CONTENT_AUTHORITY, extras); } if (mSocialStreamFragment != null) { mSocialStreamFragment.refresh(); } } @Override protected void onPause() { super.onPause(); if (mSyncObserverHandle != null) { ContentResolver.removeStatusChangeListener(mSyncObserverHandle); mSyncObserverHandle = null; } } @Override protected void onResume() { super.onResume(); mSyncStatusObserver.onStatusChanged(0); // Watch for sync state changes final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING | ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE; mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver); } public void setRefreshActionButtonState(boolean refreshing) { if (mOptionsMenu == null) { return; } final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh); if (refreshItem != null) { if (refreshing) { refreshItem.setActionView(R.layout.actionbar_indeterminate_progress); } else { refreshItem.setActionView(null); } } } private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { @Override public void onStatusChanged(int which) { runOnUiThread(new Runnable() { @Override public void run() { String accountName = AccountUtils.getChosenAccountName(HomeActivity.this); if (TextUtils.isEmpty(accountName)) { setRefreshActionButtonState(false); return; } Account account = new Account(accountName, GoogleAccountManager.ACCOUNT_TYPE); boolean syncActive = ContentResolver.isSyncActive( account, ScheduleContract.CONTENT_AUTHORITY); boolean syncPending = ContentResolver.isSyncPending( account, ScheduleContract.CONTENT_AUTHORITY); setRefreshActionButtonState(syncActive || syncPending); } }); } }; }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.os.Bundle; import android.support.v4.app.Fragment; /** * A single-pane activity that shows a {@link SocialStreamFragment}. */ public class SocialStreamActivity extends SimpleSinglePaneActivity { @Override protected Fragment onCreatePane() { return new SocialStreamFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setTitle(getIntent().getStringExtra(SocialStreamFragment.EXTRA_QUERY)); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.social_stream_standalone, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: ((SocialStreamFragment) getFragment()).refresh(); return true; } return super.onOptionsItemSelected(item); } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.Spannable; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; /** * A {@link ListFragment} showing a list of developer sandbox companies. */ public class VendorsFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(VendorsFragment.class); private static final String STATE_SELECTED_ID = "selectedId"; private Uri mVendorsUri; private CursorAdapter mAdapter; private String mSelectedVendorId; private boolean mHasSetEmptyText = false; public interface Callbacks { /** Return true to select (activate) the vendor in the list, false otherwise. */ public boolean onVendorSelected(String vendorId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public boolean onVendorSelected(String vendorId) { return true; } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mSelectedVendorId = savedInstanceState.getString(STATE_SELECTED_ID); } reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments setListAdapter(null); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); mVendorsUri = intent.getData(); final int vendorQueryToken; if (mVendorsUri == null) { return; } mAdapter = new VendorsAdapter(getActivity()); vendorQueryToken = VendorsQuery._TOKEN; setListAdapter(mAdapter); // Start background query to load vendors getLoaderManager().initLoader(vendorQueryToken, null, this); } public void setSelectedVendorId(String id) { mSelectedVendorId = id; if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); listView.setCacheColorHint(Color.WHITE); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible // when it shouldn't be visible. setEmptyText(getString(R.string.empty_vendors)); mHasSetEmptyText = true; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSelectedVendorId != null) { outState.putString(STATE_SELECTED_ID, mSelectedVendorId); } } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); String vendorId = cursor.getString(VendorsQuery.VENDOR_ID); if (mCallbacks.onVendorSelected(vendorId)) { mSelectedVendorId = vendorId; mAdapter.notifyDataSetChanged(); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mVendorsUri, VendorsQuery.PROJECTION, null, null, ScheduleContract.Vendors.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } int token = loader.getId(); if (token == VendorsQuery._TOKEN) { mAdapter.changeCursor(cursor); } else { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> cursor) { } /** * {@link CursorAdapter} that renders a {@link VendorsQuery}. */ private class VendorsAdapter extends CursorAdapter { public VendorsAdapter(Context context) { super(context, null, false); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_vendor, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { UIUtils.setActivatedCompat(view, cursor.getString(VendorsQuery.VENDOR_ID) .equals(mSelectedVendorId)); ((TextView) view.findViewById(R.id.vendor_name)).setText( cursor.getString(VendorsQuery.NAME)); } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} * query parameters. */ private interface VendorsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Vendors.VENDOR_ID, ScheduleContract.Vendors.VENDOR_NAME, }; int _ID = 0; int VENDOR_ID = 1; int NAME = 2; } }
Java
/* * Copyright 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.android.apps.iosched.ui.widget; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A layout that supports the Show/Hide pattern for portrait tablet layouts. See <a * href="http://developer.android.com/design/patterns/multi-pane-layouts.html#orientation">Android * Design &gt; Patterns &gt; Multi-pane Layouts & gt; Compound Views and Orientation Changes</a> for * more details on this pattern. This layout should normally be used in association with the Up * button. Specifically, show the master pane using {@link #showMaster(boolean, int)} when the Up * button is pressed. If the master pane is visible, defer to normal Up behavior. * * <p>TODO: swiping should be more tactile and actually follow the user's finger. * * <p>Requires API level 11 */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class ShowHideMasterLayout extends ViewGroup implements Animator.AnimatorListener { private static final String TAG = makeLogTag(ShowHideMasterLayout.class); /** * A flag for {@link #showMaster(boolean, int)} indicating that the change in visiblity should * not be animated. */ public static final int FLAG_IMMEDIATE = 0x1; private boolean mFirstShow = true; private boolean mMasterVisible = true; private View mMasterView; private View mDetailView; private OnMasterVisibilityChangedListener mOnMasterVisibilityChangedListener; private GestureDetector mGestureDetector; private boolean mFlingToExposeMaster; private boolean mIsAnimating; private Runnable mShowMasterCompleteRunnable; // The last measured master width, including its margins. private int mTranslateAmount; public interface OnMasterVisibilityChangedListener { public void onMasterVisibilityChanged(boolean visible); } public ShowHideMasterLayout(Context context) { super(context); init(); } public ShowHideMasterLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ShowHideMasterLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { mGestureDetector = new GestureDetector(getContext(), mGestureListener); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } @Override protected LayoutParams generateLayoutParams(LayoutParams p) { return new MarginLayoutParams(p); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int count = getChildCount(); // Measure once to find the maximum child size. int maxHeight = 0; int maxWidth = 0; int childState = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0); final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); maxWidth = Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin); maxHeight = Math.max(maxHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin); childState = combineMeasuredStates(childState, child.getMeasuredState()); } // Account for padding too maxWidth += getPaddingLeft() + getPaddingRight(); maxHeight += getPaddingLeft() + getPaddingRight(); // Check against our minimum height and width maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); // Set our own measured size setMeasuredDimension( resolveSizeAndState(maxWidth, widthMeasureSpec, childState), resolveSizeAndState(maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT)); // Measure children for them to set their measured dimensions for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); int childWidthMeasureSpec; int childHeightMeasureSpec; if (lp.width == LayoutParams.MATCH_PARENT) { childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - lp.leftMargin - lp.rightMargin, MeasureSpec.EXACTLY); } else { childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, lp.width); } if (lp.height == LayoutParams.MATCH_PARENT) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() - getPaddingTop() - getPaddingBottom() - lp.topMargin - lp.bottomMargin, MeasureSpec.EXACTLY); } else { childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin, lp.height); } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { updateChildReferences(); if (mMasterView == null || mDetailView == null) { LOGW(TAG, "Master or detail is missing (need 2 children), can't layout."); return; } int masterWidth = mMasterView.getMeasuredWidth(); MarginLayoutParams masterLp = (MarginLayoutParams) mMasterView.getLayoutParams(); MarginLayoutParams detailLp = (MarginLayoutParams) mDetailView.getLayoutParams(); mTranslateAmount = masterWidth + masterLp.leftMargin + masterLp.rightMargin; mMasterView.layout( l + masterLp.leftMargin, t + masterLp.topMargin, l + masterLp.leftMargin + masterWidth, b - masterLp.bottomMargin); mDetailView.layout( l + detailLp.leftMargin + mTranslateAmount, t + detailLp.topMargin, r - detailLp.rightMargin + mTranslateAmount, b - detailLp.bottomMargin); // Update translationX values if (!mIsAnimating) { final float translationX = mMasterVisible ? 0 : -mTranslateAmount; mMasterView.setTranslationX(translationX); mDetailView.setTranslationX(translationX); } } private void updateChildReferences() { int childCount = getChildCount(); mMasterView = (childCount > 0) ? getChildAt(0) : null; mDetailView = (childCount > 1) ? getChildAt(1) : null; } /** * Allow or disallow the user to flick right on the detail pane to expose the master pane. * @param enabled Whether or not to enable this interaction. */ public void setFlingToExposeMasterEnabled(boolean enabled) { mFlingToExposeMaster = enabled; } /** * Request the given listener be notified when the master pane is shown or hidden. * * @param listener The listener to notify when the master pane is shown or hidden. */ public void setOnMasterVisibilityChangedListener(OnMasterVisibilityChangedListener listener) { mOnMasterVisibilityChangedListener = listener; } /** * Returns whether or not the master pane is visible. * * @return True if the master pane is visible. */ public boolean isMasterVisible() { return mMasterVisible; } /** * Calls {@link #showMaster(boolean, int, Runnable)} with a null runnable. */ public void showMaster(boolean show, int flags) { showMaster(show, flags, null); } /** * Shows or hides the master pane. * * @param show Whether or not to show the master pane. * @param flags {@link #FLAG_IMMEDIATE} to show/hide immediately, or 0 to animate. * @param completeRunnable An optional runnable to run when any animations related to this are * complete. */ public void showMaster(boolean show, int flags, Runnable completeRunnable) { if (!mFirstShow && mMasterVisible == show) { return; } mShowMasterCompleteRunnable = completeRunnable; mFirstShow = false; mMasterVisible = show; if (mOnMasterVisibilityChangedListener != null) { mOnMasterVisibilityChangedListener.onMasterVisibilityChanged(show); } updateChildReferences(); if (mMasterView == null || mDetailView == null) { LOGW(TAG, "Master or detail is missing (need 2 children), can't change translation."); return; } final float translationX = show ? 0 : -mTranslateAmount; if ((flags & FLAG_IMMEDIATE) != 0) { mMasterView.setTranslationX(translationX); mDetailView.setTranslationX(translationX); if (mShowMasterCompleteRunnable != null) { mShowMasterCompleteRunnable.run(); mShowMasterCompleteRunnable = null; } } else { final long duration = getResources().getInteger(android.R.integer.config_shortAnimTime); // Animate if we have Honeycomb APIs, don't animate otherwise mIsAnimating = true; AnimatorSet animatorSet = new AnimatorSet(); mMasterView.setLayerType(LAYER_TYPE_HARDWARE, null); mDetailView.setLayerType(LAYER_TYPE_HARDWARE, null); animatorSet .play(ObjectAnimator .ofFloat(mMasterView, "translationX", translationX) .setDuration(duration)) .with(ObjectAnimator .ofFloat(mDetailView, "translationX", translationX) .setDuration(duration)); animatorSet.addListener(this); animatorSet.start(); // For API level 12+, use this instead: // mMasterView.animate().translationX().setDuration(duration); // mDetailView.animate().translationX(show ? masterWidth : 0).setDuration(duration); } } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // Really bad hack... we really shouldn't do this. //super.requestDisallowInterceptTouchEvent(disallowIntercept); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (mFlingToExposeMaster && !mMasterVisible) { mGestureDetector.onTouchEvent(event); } if (event.getAction() == MotionEvent.ACTION_DOWN && mMasterView != null && mMasterVisible) { // If the master is visible, touching in the detail area should hide the master. if (event.getX() > mTranslateAmount) { return true; } } return super.onInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { if (mFlingToExposeMaster && !mMasterVisible && mGestureDetector.onTouchEvent(event)) { return true; } if (event.getAction() == MotionEvent.ACTION_DOWN && mMasterView != null && mMasterVisible) { // If the master is visible, touching in the detail area should hide the master. if (event.getX() > mTranslateAmount) { showMaster(false, 0); return true; } } return super.onTouchEvent(event); } @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { mIsAnimating = false; mMasterView.setLayerType(LAYER_TYPE_NONE, null); mDetailView.setLayerType(LAYER_TYPE_NONE, null); requestLayout(); if (mShowMasterCompleteRunnable != null) { mShowMasterCompleteRunnable.run(); mShowMasterCompleteRunnable = null; } } @Override public void onAnimationCancel(Animator animator) { mIsAnimating = false; mMasterView.setLayerType(LAYER_TYPE_NONE, null); mDetailView.setLayerType(LAYER_TYPE_NONE, null); requestLayout(); if (mShowMasterCompleteRunnable != null) { mShowMasterCompleteRunnable.run(); mShowMasterCompleteRunnable = null; } } @Override public void onAnimationRepeat(Animator animator) { } private final GestureDetector.OnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { ViewConfiguration viewConfig = ViewConfiguration.get(getContext()); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(velocityY); if (mFlingToExposeMaster && !mMasterVisible && velocityX > 0 && absVelocityX >= absVelocityY // Fling at least as hard in X as in Y && absVelocityX > viewConfig.getScaledMinimumFlingVelocity() && absVelocityX < viewConfig.getScaledMaximumFlingVelocity()) { showMaster(true, 0); return true; } return super.onFling(e1, e2, velocityX, velocityY); } }; }
Java
/* * Copyright 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.android.apps.iosched.ui.widget; import android.content.Context; import android.database.DataSetObserver; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.Arrays; import java.util.Comparator; public class SimpleSectionedListAdapter extends BaseAdapter { private boolean mValid = true; private int mSectionResourceId; private LayoutInflater mLayoutInflater; private ListAdapter mBaseAdapter; private SparseArray<Section> mSections = new SparseArray<Section>(); public static class Section { int firstPosition; int sectionedPosition; CharSequence title; public Section(int firstPosition, CharSequence title) { this.firstPosition = firstPosition; this.title = title; } public CharSequence getTitle() { return title; } } public SimpleSectionedListAdapter(Context context, int sectionResourceId, ListAdapter baseAdapter) { mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mSectionResourceId = sectionResourceId; mBaseAdapter = baseAdapter; mBaseAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { mValid = !mBaseAdapter.isEmpty(); notifyDataSetChanged(); } @Override public void onInvalidated() { mValid = false; notifyDataSetInvalidated(); } }); } public void setSections(Section[] sections) { mSections.clear(); Arrays.sort(sections, new Comparator<Section>() { @Override public int compare(Section o, Section o1) { return (o.firstPosition == o1.firstPosition) ? 0 : ((o.firstPosition < o1.firstPosition) ? -1 : 1); } }); int offset = 0; // offset positions for the headers we're adding for (Section section : sections) { section.sectionedPosition = section.firstPosition + offset; mSections.append(section.sectionedPosition, section); ++offset; } notifyDataSetChanged(); } public int positionToSectionedPosition(int position) { int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).firstPosition > position) { break; } ++offset; } return position + offset; } public int sectionedPositionToPosition(int sectionedPosition) { if (isSectionHeaderPosition(sectionedPosition)) { return ListView.INVALID_POSITION; } int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).sectionedPosition > sectionedPosition) { break; } --offset; } return sectionedPosition + offset; } public boolean isSectionHeaderPosition(int position) { return mSections.get(position) != null; } @Override public int getCount() { return (mValid ? mBaseAdapter.getCount() + mSections.size() : 0); } @Override public Object getItem(int position) { return isSectionHeaderPosition(position) ? mSections.get(position) : mBaseAdapter.getItem(sectionedPositionToPosition(position)); } @Override public long getItemId(int position) { return isSectionHeaderPosition(position) ? Integer.MAX_VALUE - mSections.indexOfKey(position) : mBaseAdapter.getItemId(sectionedPositionToPosition(position)); } @Override public int getItemViewType(int position) { return isSectionHeaderPosition(position) ? getViewTypeCount() - 1 : mBaseAdapter.getItemViewType(position); } @Override public boolean isEnabled(int position) { //noinspection SimplifiableConditionalExpression return isSectionHeaderPosition(position) ? false : mBaseAdapter.isEnabled(sectionedPositionToPosition(position)); } @Override public int getViewTypeCount() { return mBaseAdapter.getViewTypeCount() + 1; // the section headings } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean hasStableIds() { return mBaseAdapter.hasStableIds(); } @Override public boolean isEmpty() { return mBaseAdapter.isEmpty(); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isSectionHeaderPosition(position)) { TextView view = (TextView) convertView; if (view == null) { view = (TextView) mLayoutInflater.inflate(mSectionResourceId, parent, false); } view.setText(mSections.get(position).title); return view; } else { return mBaseAdapter.getView(sectionedPositionToPosition(position), convertView, parent); } } }
Java
/* * Copyright 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.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An {@link ImageView} that draws its contents inside a mask and draws a border drawable on top. * This is useful for applying a beveled look to image contents, but is also flexible enough for use * with other desired aesthetics. */ public class BezelImageView extends ImageView { private static final String TAG = makeLogTag(BezelImageView.class); private Paint mMaskedPaint; private Rect mBounds; private RectF mBoundsF; private Drawable mBorderDrawable; private Drawable mMaskDrawable; private boolean mGuardInvalidate; // prevents stack overflows public BezelImageView(Context context) { this(context, null); } public BezelImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BezelImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Attribute initialization final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BezelImageView, defStyle, 0); mMaskDrawable = a.getDrawable(R.styleable.BezelImageView_maskDrawable); if (mMaskDrawable == null) { mMaskDrawable = getResources().getDrawable(R.drawable.bezel_mask); } mMaskDrawable.setCallback(this); mBorderDrawable = a.getDrawable(R.styleable.BezelImageView_borderDrawable); if (mBorderDrawable == null) { mBorderDrawable = getResources().getDrawable(R.drawable.bezel_border_default); } mBorderDrawable.setCallback(this); a.recycle(); // Other initialization mMaskedPaint = new Paint(); mMaskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); } private Bitmap mCached; private void invalidateCache() { if (mBounds == null || mBounds.width() == 0 || mBounds.height() == 0) { return; } if (mCached != null) { mCached.recycle(); mCached = null; } mCached = Bitmap.createBitmap(mBounds.width(), mBounds.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mCached); int sc = canvas.saveLayer(mBoundsF, null, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG); mMaskDrawable.draw(canvas); canvas.saveLayer(mBoundsF, mMaskedPaint, 0); // certain drawables invalidate themselves on draw, e.g. TransitionDrawable sets its alpha // which invalidates itself. to prevent stack overflow errors, we must guard the // invalidation (see specialized behavior when guarded in invalidate() below). mGuardInvalidate = true; super.onDraw(canvas); mGuardInvalidate = false; canvas.restoreToCount(sc); mBorderDrawable.draw(canvas); } @Override protected boolean setFrame(int l, int t, int r, int b) { final boolean changed = super.setFrame(l, t, r, b); mBounds = new Rect(0, 0, r - l, b - t); mBoundsF = new RectF(mBounds); mBorderDrawable.setBounds(mBounds); mMaskDrawable.setBounds(mBounds); if (changed) { invalidateCache(); } return changed; } @Override protected void onDraw(Canvas canvas) { if (mCached == null) { invalidateCache(); } if (mCached != null) { canvas.drawBitmap(mCached, mBounds.left, mBounds.top, null); } //super.onDraw(canvas); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mBorderDrawable.isStateful()) { mBorderDrawable.setState(getDrawableState()); } if (mMaskDrawable.isStateful()) { mMaskDrawable.setState(getDrawableState()); } // TODO: may need to invalidate elsewhere invalidate(); } @Override public void invalidate() { if (mGuardInvalidate) { removeCallbacks(mInvalidateCacheRunnable); postDelayed(mInvalidateCacheRunnable, 16); } else { super.invalidate(); invalidateCache(); } } private Runnable mInvalidateCacheRunnable = new Runnable() { @Override public void run() { invalidateCache(); BezelImageView.super.invalidate(); LOGD(TAG, "delayed invalidate"); } }; }
Java
/* * Copyright 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.android.apps.iosched.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.FrameLayout; /** * A {@link Checkable} {@link FrameLayout}. When this is the root view for an item in a * {@link android.widget.ListView} and the list view has a choice mode of * {@link android.widget.ListView#CHOICE_MODE_MULTIPLE_MODAL }, the list view will * set the item's state to CHECKED and not ACTIVATED. This is important to ensure that we can * use the ACTIVATED state on tablet devices to represent the currently-viewed detail screen, while * allowing multiple-selection. */ public class CheckableFrameLayout extends FrameLayout implements Checkable { private boolean mChecked; public CheckableFrameLayout(Context context) { super(context); } public CheckableFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } public CheckableFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private static final int[] CheckedStateSet = { android.R.attr.state_checked }; @Override public boolean isChecked() { return mChecked; } @Override public void setChecked(boolean checked) { mChecked = checked; refreshDrawableState(); } @Override public void toggle() { setChecked(!mChecked); } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CheckedStateSet); } return drawableState; } }
Java
/* * Copyright 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.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; /** * An extremely simple {@link LinearLayout} descendant that simply switches the order of its child * views on Android 4.0+. The reason for this is that on Android, negative buttons should be shown * to the left of positive buttons. */ public class ButtonBar extends LinearLayout { public ButtonBar(Context context) { super(context); } public ButtonBar(Context context, AttributeSet attrs) { super(context, attrs); } public ButtonBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public View getChildAt(int index) { if (UIUtils.hasICS()) { // Flip the buttons so that we get e.g. "Cancel | OK" on ICS return super.getChildAt(getChildCount() - 1 - index); } return super.getChildAt(index); } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.youtube.api.YouTube; import com.google.android.youtube.api.YouTubePlayer; import com.google.android.youtube.api.YouTubePlayerSupportFragment; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.app.NavUtils; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.ViewPager; import android.support.v4.widget.CursorAdapter; import android.text.TextUtils; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An activity that displays the session live stream video which is pulled in from YouTube. The * UI adapts for both phone and tablet. As we want to prevent the YouTube player from restarting * and buffering again on orientation change, we handle configuration changes manually. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SessionLivestreamActivity extends BaseActivity implements LoaderCallbacks<Cursor>, YouTubePlayer.OnPlaybackEventsListener, YouTubePlayer.OnFullscreenListener, ActionBar.OnNavigationListener { private static final String TAG = makeLogTag(SessionLivestreamActivity.class); private static final String EXTRA_PREFIX = "com.google.android.iosched.extra."; public static final String EXTRA_YOUTUBE_URL = EXTRA_PREFIX + "youtube_url"; public static final String EXTRA_TRACK = EXTRA_PREFIX + "track"; public static final String EXTRA_TITLE = EXTRA_PREFIX + "title"; public static final String EXTRA_ABSTRACT = EXTRA_PREFIX + "abstract"; public static final String KEYNOTE_TRACK_NAME = "Keynote"; private static final String LOADER_SESSIONS_ARG = "futureSessions"; private static final String TAG_SESSION_SUMMARY = "session_summary"; private static final String TAG_CAPTIONS = "captions"; private static final int TABNUM_SESSION_SUMMARY = 0; private static final int TABNUM_SOCIAL_STREAM = 1; private static final int TABNUM_LIVE_CAPTIONS = 2; private static final String EXTRA_TAB_STATE = "tag"; private static final int STREAM_REFRESH_TIME = 5 * 60 * 1000; // 5 minutes private boolean mIsTablet; private boolean mIsFullscreen = false; private boolean mLoadFromExtras = false; private boolean mTrackPlay = true; private int mNormalScreenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; private TabHost mTabHost; private TabsAdapter mTabsAdapter; private YouTubePlayerSupportFragment mYouTubePlayer; private LinearLayout mPlayerContainer; private String mYouTubeVideoId; private LinearLayout mMainLayout; private LinearLayout mVideoLayout; private LinearLayout mExtraLayout; private FrameLayout mSummaryLayout; private FrameLayout mFullscreenCaptions; private MenuItem mCaptionsMenuItem; private MenuItem mShareMenuItem; private Runnable mShareMenuDeferredSetup; private Runnable mSessionSummaryDeferredSetup; private SessionShareData mSessionShareData; private boolean mSessionsFound; private boolean isKeynote = false; private Handler mHandler = new Handler(); private LivestreamAdapter mLivestreamAdapter; private Uri mSessionUri; private String mSessionId; private String mTrackName; @Override protected void onCreate(Bundle savedInstanceState) { if (UIUtils.hasICS()) { // We can't use this mode on HC as compatible ActionBar doesn't work well with the YT // player in full screen mode (no overlays allowed). requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); } super.onCreate(savedInstanceState); YouTube.initialize(this, Config.YOUTUBE_API_KEY); setContentView(R.layout.activity_session_livestream); mIsTablet = UIUtils.isHoneycombTablet(this); // Set up YouTube player mYouTubePlayer = (YouTubePlayerSupportFragment) getSupportFragmentManager() .findFragmentById(R.id.livestream_player); mYouTubePlayer.enableCustomFullscreen(this); mYouTubePlayer.setOnPlaybackEventsListener(this); int fullscreenControlFlags = YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI | YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION; if (!mIsTablet) { fullscreenControlFlags |= YouTubePlayer.FULLSCREEN_FLAG_FULLSCREEN_WHEN_DEVICE_LANDSCAPE; setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } mYouTubePlayer.setFullscreenControlFlags(fullscreenControlFlags); // Views that are common over all layouts mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout); adjustMainLayoutForActionBar(); mPlayerContainer = (LinearLayout) findViewById(R.id.livestream_player_container); mFullscreenCaptions = (FrameLayout) findViewById(R.id.fullscreen_captions); final LayoutParams params = (LayoutParams) mFullscreenCaptions.getLayoutParams(); params.setMargins(0, getActionBarHeightPx(), 0, getActionBarHeightPx()); mFullscreenCaptions.setLayoutParams(params); ViewPager viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setOffscreenPageLimit(2); viewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); viewPager.setPageMargin(getResources() .getDimensionPixelSize(R.dimen.page_margin_width)); // Set up tabs w/viewpager mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabHost.setup(); mTabsAdapter = new TabsAdapter(this, mTabHost, viewPager); if (mIsTablet) { // Tablet UI specific views getSupportFragmentManager().beginTransaction().add(R.id.livestream_summary, new SessionSummaryFragment(), TAG_SESSION_SUMMARY).commit(); mVideoLayout = (LinearLayout) findViewById(R.id.livestream_videolayout); mExtraLayout = (LinearLayout) findViewById(R.id.livestream_extralayout); mSummaryLayout = (FrameLayout) findViewById(R.id.livestream_summary); } else { // Handset UI specific views mTabsAdapter.addTab( getString(R.string.session_livestream_info), new SessionSummaryFragment(), TABNUM_SESSION_SUMMARY); } mTabsAdapter.addTab(getString(R.string.title_stream), new SocialStreamFragment(), TABNUM_SOCIAL_STREAM); mTabsAdapter.addTab(getString(R.string.session_livestream_captions), new SessionLiveCaptionsFragment(), TABNUM_LIVE_CAPTIONS); if (savedInstanceState != null) { mTabHost.setCurrentTabByTag(savedInstanceState.getString(EXTRA_TAB_STATE)); } // Reload all other data in this activity reloadFromIntent(getIntent()); // Update layout based on current configuration updateLayout(getResources().getConfiguration()); // Set up action bar if (!mLoadFromExtras) { // Start sessions query to populate action bar navigation spinner getSupportLoaderManager().initLoader(SessionsQuery._TOKEN, null, this); // Set up action bar mLivestreamAdapter = new LivestreamAdapter(this); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setListNavigationCallbacks(mLivestreamAdapter, this); actionBar.setDisplayShowTitleEnabled(false); } } @Override protected void onResume() { super.onResume(); if (mSessionSummaryDeferredSetup != null) { mSessionSummaryDeferredSetup.run(); mSessionSummaryDeferredSetup = null; } mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME); } @Override protected void onPause() { super.onPause(); mHandler.removeCallbacks(mStreamRefreshRunnable); } /** * Reloads all data in the activity and fragments from a given intent * @param intent The intent to load from */ private void reloadFromIntent(Intent intent) { final String youtubeUrl = intent.getStringExtra(EXTRA_YOUTUBE_URL); // Check if youtube url is set as an extra first if (youtubeUrl != null) { mLoadFromExtras = true; String trackName = intent.getStringExtra(EXTRA_TRACK); String actionBarTitle; if (trackName == null) { actionBarTitle = getString(R.string.session_livestream_title); } else { actionBarTitle = trackName + " - " + getString(R.string.session_livestream_title); } getSupportActionBar().setTitle(actionBarTitle); updateSessionViews(youtubeUrl, intent.getStringExtra(EXTRA_TITLE), intent.getStringExtra(EXTRA_ABSTRACT), UIUtils.CONFERENCE_HASHTAG, trackName); } else { // Otherwise load from session uri reloadFromUri(intent.getData()); } } /** * Reloads all data in the activity and fragments from a given uri * @param newUri The session uri to load from */ private void reloadFromUri(Uri newUri) { mSessionUri = newUri; if (mSessionUri != null && mSessionUri.getPathSegments().size() >= 2) { mSessionId = Sessions.getSessionId(mSessionUri); getSupportLoaderManager().restartLoader(SessionSummaryQuery._TOKEN, null, this); } else { // No session uri, get out mSessionUri = null; navigateUpOrFinish(); } } /** * Helper method to start this activity using only extras (rather than session uri). * @param context The package context * @param youtubeUrl The youtube url or video id to load * @param track The track title (appears as part of action bar title), can be null * @param title The title to show in the session info fragment, can be null * @param sessionAbstract The session abstract to show in the session info fragment, can be null */ public static void startFromExtras(Context context, String youtubeUrl, String track, String title, String sessionAbstract) { if (youtubeUrl == null) { return; } final Intent i = new Intent(); i.setClass(context, SessionLivestreamActivity.class); i.putExtra(EXTRA_YOUTUBE_URL, youtubeUrl); i.putExtra(EXTRA_TRACK, track); i.putExtra(EXTRA_TITLE, title); i.putExtra(EXTRA_ABSTRACT, sessionAbstract); context.startActivity(i); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mTabHost != null) { outState.putString(EXTRA_TAB_STATE, mTabHost.getCurrentTabTag()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.session_livestream, menu); mCaptionsMenuItem = menu.findItem(R.id.menu_captions); mShareMenuItem = menu.findItem(R.id.menu_share); if (mShareMenuDeferredSetup != null) { mShareMenuDeferredSetup.run(); } if (!mIsTablet && Configuration.ORIENTATION_LANDSCAPE == getResources().getConfiguration().orientation) { mCaptionsMenuItem.setVisible(true); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (mIsFullscreen) { mYouTubePlayer.setFullscreen(false); } else { navigateUpOrFinish(); } return true; case R.id.menu_captions: if (mIsFullscreen) { if (mFullscreenCaptions.getVisibility() == View.GONE) { mFullscreenCaptions.setVisibility(View.VISIBLE); SessionLiveCaptionsFragment captionsFragment; captionsFragment = (SessionLiveCaptionsFragment) getSupportFragmentManager().findFragmentByTag(TAG_CAPTIONS); if (captionsFragment == null) { captionsFragment = new SessionLiveCaptionsFragment(); captionsFragment.setDarkTheme(true); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.fullscreen_captions, captionsFragment, TAG_CAPTIONS); ft.commit(); } captionsFragment.setTrackName(mTrackName); return true; } } mFullscreenCaptions.setVisibility(View.GONE); break; case R.id.menu_share: if (mSessionShareData != null) { new SessionsHelper(this).shareSession(this, R.string.share_livestream_template, mSessionShareData.SESSION_TITLE, mSessionShareData.SESSION_HASHTAG, mSessionShareData.SESSION_URL); return true; } break; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (mIsFullscreen) { // Exit full screen mode on back key mYouTubePlayer.setFullscreen(false); } else { super.onBackPressed(); } } @Override public void onConfigurationChanged(Configuration newConfig) { // Need to handle configuration changes so as not to interrupt YT player and require // buffering again updateLayout(newConfig); super.onConfigurationChanged(newConfig); } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(itemPosition); setActionBarColor(cursor.getInt(SessionsQuery.TRACK_COLOR)); final String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId != null) { reloadFromUri(Sessions.buildSessionUri(sessionId)); return true; } return false; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { case SessionSummaryQuery._TOKEN: return new CursorLoader(this, Sessions.buildWithTracksUri(mSessionId), SessionSummaryQuery.PROJECTION, null, null, null); case SessionsQuery._TOKEN: boolean futureSessions = false; if (args != null) { futureSessions = args.getBoolean(LOADER_SESSIONS_ARG, false); } final long currentTime = UIUtils.getCurrentTime(this); String selection = Sessions.LIVESTREAM_SELECTION + " and "; String[] selectionArgs; if (!futureSessions) { selection += Sessions.AT_TIME_SELECTION; selectionArgs = Sessions.buildAtTimeSelectionArgs(currentTime); } else { selection += Sessions.UPCOMING_SELECTION; selectionArgs = Sessions.buildUpcomingSelectionArgs(currentTime); } return new CursorLoader(this, Sessions.buildWithTracksUri(), SessionsQuery.PROJECTION, selection, selectionArgs, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { switch (loader.getId()) { case SessionSummaryQuery._TOKEN: loadSession(data); break; case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(data); if (data != null && data.getCount() > 0) { mSessionsFound = true; final int selected = locateSelectedItem(data); getSupportActionBar().setSelectedNavigationItem(selected); } else if (mSessionsFound) { mSessionsFound = false; final Bundle bundle = new Bundle(); bundle.putBoolean(LOADER_SESSIONS_ARG, true); getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, bundle, this); } else { navigateUpOrFinish(); } break; } } /** * Locates which item should be selected in the action bar drop-down spinner based on the * current active session uri * @param data The data * @return The row num of the item that should be selected or 0 if not found */ private int locateSelectedItem(Cursor data) { int selected = 0; if (data != null && (mSessionId != null || mTrackName != null)) { final boolean findNextSessionByTrack = mTrackName != null; while (data.moveToNext()) { if (findNextSessionByTrack) { if (mTrackName.equals(data.getString(SessionsQuery.TRACK_NAME))) { selected = data.getPosition(); mTrackName = null; break; } } else { if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) { selected = data.getPosition(); } } } } return selected; } @Override public void onLoaderReset(Loader<Cursor> loader) { switch (loader.getId()) { case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(null); break; } } @Override public void onFullscreen(boolean fullScreen) { layoutFullscreenVideo(fullScreen); } @Override public void onLoaded(String s) { } @Override public void onPlaying() { } @Override public void onPaused() { } @Override public void onBuffering(boolean b) { } @Override public void onEnded() { } @Override public void onError() { Toast.makeText(this, R.string.session_livestream_error, Toast.LENGTH_LONG).show(); } private void loadSession(Cursor data) { if (data != null && data.moveToFirst()) { mTrackName = data.getString(SessionSummaryQuery.TRACK_NAME); if (TextUtils.isEmpty(mTrackName)) { mTrackName = KEYNOTE_TRACK_NAME; isKeynote = true; } final long currentTime = UIUtils.getCurrentTime(this); if (currentTime > data.getLong(SessionSummaryQuery.BLOCK_END)) { getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, null, this); return; } updateTagStreamFragment(data.getString(SessionSummaryQuery.HASHTAGS)); updateSessionViews( data.getString(SessionSummaryQuery.LIVESTREAM_URL), data.getString(SessionSummaryQuery.TITLE), data.getString(SessionSummaryQuery.ABSTRACT), data.getString(SessionSummaryQuery.HASHTAGS), mTrackName); } } /** * Updates views that rely on session data from explicit strings. */ private void updateSessionViews(final String youtubeUrl, final String title, final String sessionAbstract, final String hashTag, final String trackName) { if (youtubeUrl == null) { // Get out, nothing to do here navigateUpOrFinish(); return; } mTrackName = trackName; String youtubeVideoId = youtubeUrl; if (youtubeUrl.startsWith("http")) { final Uri youTubeUri = Uri.parse(youtubeUrl); youtubeVideoId = youTubeUri.getQueryParameter("v"); } playVideo(youtubeVideoId); if (mTrackPlay) { EasyTracker.getTracker().trackView("Live Streaming: " + title); LOGD("Tracker", "Live Streaming: " + title); } final String newYoutubeUrl = Config.YOUTUBE_SHARE_URL_PREFIX + youtubeVideoId; mSessionShareData = new SessionShareData(title, hashTag, newYoutubeUrl); mShareMenuDeferredSetup = new Runnable() { @Override public void run() { new SessionsHelper(SessionLivestreamActivity.this) .tryConfigureShareMenuItem(mShareMenuItem, R.string.share_livestream_template, title, hashTag, newYoutubeUrl); } }; if (mShareMenuItem != null) { mShareMenuDeferredSetup.run(); mShareMenuDeferredSetup = null; } mSessionSummaryDeferredSetup = new Runnable() { @Override public void run() { updateSessionSummaryFragment(title, sessionAbstract); updateSessionLiveCaptionsFragment(trackName); } }; if (!mLoadFromExtras) { mSessionSummaryDeferredSetup.run(); mSessionSummaryDeferredSetup = null; } } private void updateSessionSummaryFragment(String title, String sessionAbstract) { SessionSummaryFragment sessionSummaryFragment; if (mIsTablet) { sessionSummaryFragment = (SessionSummaryFragment) getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY); } else { sessionSummaryFragment = (SessionSummaryFragment) mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY); } if (sessionSummaryFragment != null) { sessionSummaryFragment.setSessionSummaryInfo( isKeynote ? getString(R.string.session_livestream_keynote_title, title) : title, (isKeynote && TextUtils.isEmpty(sessionAbstract)) ? getString(R.string.session_livestream_keynote_desc) : sessionAbstract); } } Runnable mStreamRefreshRunnable = new Runnable() { @Override public void run() { if (mTabsAdapter != null && mTabsAdapter.mFragments != null) { final SocialStreamFragment socialStreamFragment = (SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM); if (socialStreamFragment != null) { socialStreamFragment.refresh(); } } mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME); } }; private void updateTagStreamFragment(String trackHashTag) { String hashTags = UIUtils.CONFERENCE_HASHTAG; if (!TextUtils.isEmpty(trackHashTag)) { hashTags += " " + trackHashTag; } final SocialStreamFragment socialStreamFragment = (SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM); if (socialStreamFragment != null) { socialStreamFragment.refresh(hashTags); } } private void updateSessionLiveCaptionsFragment(String trackName) { final SessionLiveCaptionsFragment captionsFragment = (SessionLiveCaptionsFragment) mTabsAdapter.mFragments.get(TABNUM_LIVE_CAPTIONS); if (captionsFragment != null) { captionsFragment.setTrackName(trackName); } } private void playVideo(String videoId) { if ((TextUtils.isEmpty(mYouTubeVideoId) || !mYouTubeVideoId.equals(videoId)) && !TextUtils.isEmpty(videoId)) { mYouTubeVideoId = videoId; mYouTubePlayer.loadVideo(mYouTubeVideoId); mTrackPlay = true; if (mSessionShareData != null) { mSessionShareData.SESSION_URL = Config.YOUTUBE_SHARE_URL_PREFIX + mYouTubeVideoId; } } } private void navigateUpOrFinish() { if (mLoadFromExtras || isKeynote) { final Intent homeIntent = new Intent(); homeIntent.setClass(this, HomeActivity.class); NavUtils.navigateUpTo(this, homeIntent); } else if (mSessionUri != null) { final Intent parentIntent = new Intent(Intent.ACTION_VIEW, mSessionUri); NavUtils.navigateUpTo(this, parentIntent); } else { finish(); } } /** * Updates the layout based on the provided configuration */ private void updateLayout(Configuration config) { if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { if (mIsTablet) { layoutTabletForLandscape(); } else { layoutPhoneForLandscape(); } } else { if (mIsTablet) { layoutTabletForPortrait(); } else { layoutPhoneForPortrait(); } } } private void layoutPhoneForLandscape() { layoutFullscreenVideo(true); } private void layoutPhoneForPortrait() { layoutFullscreenVideo(false); SessionSummaryFragment fragment = (SessionSummaryFragment) mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY); if (fragment != null) { fragment.updateViews(); } } private void layoutTabletForLandscape() { mMainLayout.setOrientation(LinearLayout.HORIZONTAL); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.height = LayoutParams.MATCH_PARENT; videoLayoutParams.width = 0; videoLayoutParams.weight = 1; mVideoLayout.setLayoutParams(videoLayoutParams); final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams(); extraLayoutParams.height = LayoutParams.MATCH_PARENT; extraLayoutParams.width = 0; extraLayoutParams.weight = 1; mExtraLayout.setLayoutParams(extraLayoutParams); } private void layoutTabletForPortrait() { mMainLayout.setOrientation(LinearLayout.VERTICAL); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.width = LayoutParams.MATCH_PARENT; if (mLoadFromExtras) { // Loading from extras, let the top fragment wrap_content videoLayoutParams.height = LayoutParams.WRAP_CONTENT; videoLayoutParams.weight = 0; } else { // Otherwise the session description will be longer, give it some space videoLayoutParams.height = 0; videoLayoutParams.weight = 7; } mVideoLayout.setLayoutParams(videoLayoutParams); final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams(); extraLayoutParams.width = LayoutParams.MATCH_PARENT; extraLayoutParams.height = 0; extraLayoutParams.weight = 5; mExtraLayout.setLayoutParams(extraLayoutParams); } private void layoutFullscreenVideo(boolean fullscreen) { if (mIsFullscreen != fullscreen) { mIsFullscreen = fullscreen; if (mIsTablet) { // Tablet specific full screen layout layoutTabletFullScreen(fullscreen); } else { // Phone specific full screen layout layoutPhoneFullScreen(fullscreen); } // Full screen layout changes for all form factors final LayoutParams params = (LayoutParams) mPlayerContainer.getLayoutParams(); if (fullscreen) { if (mCaptionsMenuItem != null) { mCaptionsMenuItem.setVisible(true); } params.height = LayoutParams.MATCH_PARENT; mMainLayout.setPadding(0, 0, 0, 0); } else { getSupportActionBar().show(); if (mCaptionsMenuItem != null) { mCaptionsMenuItem.setVisible(false); } mFullscreenCaptions.setVisibility(View.GONE); params.height = LayoutParams.WRAP_CONTENT; adjustMainLayoutForActionBar(); } View youTubePlayerView = mYouTubePlayer.getView(); if (youTubePlayerView != null) { ViewGroup.LayoutParams playerParams = mYouTubePlayer.getView().getLayoutParams(); playerParams.height = fullscreen ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT; youTubePlayerView.setLayoutParams(playerParams); } mPlayerContainer.setLayoutParams(params); } } private void adjustMainLayoutForActionBar() { if (UIUtils.hasICS()) { // On ICS+ we use FEATURE_ACTION_BAR_OVERLAY so full screen mode doesn't need to // re-adjust layouts when hiding action bar. To account for this we add action bar // height pack to the padding when not in full screen mode. mMainLayout.setPadding(0, getActionBarHeightPx(), 0, 0); } } /** * Adjusts tablet layouts for full screen video. * * @param fullscreen True to layout in full screen, false to switch to regular layout */ private void layoutTabletFullScreen(boolean fullscreen) { if (fullscreen) { mExtraLayout.setVisibility(View.GONE); mSummaryLayout.setVisibility(View.GONE); mVideoLayout.setPadding(0, 0, 0, 0); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(0, 0, 0, 0); mVideoLayout.setLayoutParams(videoLayoutParams); } else { final int padding = getResources().getDimensionPixelSize(R.dimen.multipane_half_padding); mExtraLayout.setVisibility(View.VISIBLE); mSummaryLayout.setVisibility(View.VISIBLE); mVideoLayout.setBackgroundResource(R.drawable.grey_frame_on_white); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(padding, padding, padding, padding); mVideoLayout.setLayoutParams(videoLayoutParams); } } /** * Adjusts phone layouts for full screen video. */ private void layoutPhoneFullScreen(boolean fullscreen) { if (fullscreen) { mTabHost.setVisibility(View.GONE); } else { mTabHost.setVisibility(View.VISIBLE); } } private int getActionBarHeightPx() { int[] attrs = new int[] { android.R.attr.actionBarSize }; return (int) getTheme().obtainStyledAttributes(attrs).getDimension(0, 0f); } /** * Adapter that backs the action bar drop-down spinner. */ private class LivestreamAdapter extends CursorAdapter { LayoutInflater mLayoutInflater; public LivestreamAdapter(Context context) { super(context, null, false); if (UIUtils.hasICS()) { mLayoutInflater = (LayoutInflater) getSupportActionBar().getThemedContext() .getSystemService(LAYOUT_INFLATER_SERVICE); } else { mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); } } @Override public Object getItem(int position) { mCursor.moveToPosition(position); return mCursor; } @Override public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the drop-down spinner views return mLayoutInflater.inflate( R.layout.spinner_item_session_livestream, parent, false); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the selected spinner return mLayoutInflater.inflate(android.R.layout.simple_spinner_item, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { // Bind view that appears in the selected spinner or in the drop-down final TextView titleView = (TextView) view.findViewById(android.R.id.text1); final TextView subTitleView = (TextView) view.findViewById(android.R.id.text2); String trackName = cursor.getString(SessionsQuery.TRACK_NAME); if (TextUtils.isEmpty(trackName)) { trackName = getString(R.string.app_name); } else { trackName = getString(R.string.session_livestream_track_title, trackName); } String sessionTitle = cursor.getString(SessionsQuery.TITLE); if (subTitleView != null) { // Drop-down view titleView.setText(trackName); subTitleView.setText(sessionTitle); } else { // Selected view titleView.setText(getString(R.string.session_livestream_title) + ": " + trackName); } } } /** * Adapter that backs the viewpager tabs on the phone UI. */ private static class TabsAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener { private final FragmentActivity mContext; private final TabHost mTabHost; private final ViewPager mViewPager; public final SparseArray<Fragment> mFragments; private final ArrayList<Integer> mTabNums; private int mTabCount = 0; static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) { super(activity.getSupportFragmentManager()); mContext = activity; mTabHost = tabHost; mViewPager = pager; mTabHost.setOnTabChangedListener(this); mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); mFragments = new SparseArray<Fragment>(3); mTabNums = new ArrayList<Integer>(3); } public void addTab(String tabTitle, Fragment newFragment, int tabId) { ViewGroup tabWidget = (ViewGroup) mTabHost.findViewById(android.R.id.tabs); TextView tabIndicatorView = (TextView) mContext.getLayoutInflater().inflate( R.layout.tab_indicator_color, tabWidget, false); tabIndicatorView.setText(tabTitle); final TabHost.TabSpec tabSpec = mTabHost.newTabSpec(String.valueOf(mTabCount++)); tabSpec.setIndicator(tabIndicatorView); tabSpec.setContent(new DummyTabFactory(mContext)); mTabHost.addTab(tabSpec); mFragments.put(tabId, newFragment); mTabNums.add(tabId); notifyDataSetChanged(); } @Override public int getCount() { return mFragments.size(); } @Override public Fragment getItem(int position) { return mFragments.get(mTabNums.get(position)); } @Override public void onTabChanged(String tabId) { int position = mTabHost.getCurrentTab(); mViewPager.setCurrentItem(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { // Unfortunately when TabHost changes the current tab, it kindly also takes care of // putting focus on it when not in touch mode. The jerk. This hack tries to prevent // this from pulling focus out of our ViewPager. TabWidget widget = mTabHost.getTabWidget(); int oldFocusability = widget.getDescendantFocusability(); widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); mTabHost.setCurrentTab(position); widget.setDescendantFocusability(oldFocusability); } @Override public void onPageScrollStateChanged(int state) { } } /** * Simple fragment that inflates a session summary layout that displays session title and * abstract. */ public static class SessionSummaryFragment extends Fragment { private TextView mTitleView; private TextView mAbstractView; private String mTitle; private String mAbstract; public SessionSummaryFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_session_summary, null); mTitleView = (TextView) view.findViewById(R.id.session_title); mAbstractView = (TextView) view.findViewById(R.id.session_abstract); updateViews(); return view; } public void setSessionSummaryInfo(String sessionTitle, String sessionAbstract) { mTitle = sessionTitle; mAbstract = sessionAbstract; updateViews(); } public void updateViews() { if (mTitleView != null && mAbstractView != null) { mTitleView.setText(mTitle); if (!TextUtils.isEmpty(mAbstract)) { mAbstractView.setVisibility(View.VISIBLE); mAbstractView.setText(mAbstract); } else { mAbstractView.setVisibility(View.GONE); } } } } /** * Simple fragment that shows the live captions. */ public static class SessionLiveCaptionsFragment extends Fragment { private static final String CAPTIONS_DARK_THEME_URL_PARAM = "&theme=dark"; private FrameLayout mContainer; private WebView mWebView; private TextView mNoCaptionsTextView; private boolean mDarkTheme = false; private String mSessionTrack; public SessionLiveCaptionsFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_session_captions, null); mContainer = (FrameLayout) view.findViewById(R.id.session_caption_container); mNoCaptionsTextView = (TextView) view.findViewById(android.R.id.empty); mWebView = (WebView) view.findViewById(R.id.session_caption_area); mWebView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { // Disable text selection in WebView (doesn't work well with the YT player // triggering full screen chrome after a timeout) return true; } }); mWebView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { showNoCaptionsAvailable(); } }); updateViews(); return view; } public void setTrackName(String sessionTrack) { mSessionTrack = sessionTrack; updateViews(); } public void setDarkTheme(boolean dark) { mDarkTheme = dark; } public void updateViews() { if (mWebView != null && !TextUtils.isEmpty(mSessionTrack)) { if (mDarkTheme) { mWebView.setBackgroundColor(Color.BLACK); mContainer.setBackgroundColor(Color.BLACK); mNoCaptionsTextView.setTextColor(Color.WHITE); } else { mWebView.setBackgroundColor(Color.WHITE); mContainer.setBackgroundColor(Color.WHITE); } String captionsUrl; final String trackLowerCase = mSessionTrack.toLowerCase(); if (mSessionTrack.equals(KEYNOTE_TRACK_NAME)|| trackLowerCase.equals(Config.PRIMARY_LIVESTREAM_TRACK)) { // if keynote or primary track, use primary captions url captionsUrl = Config.PRIMARY_LIVESTREAM_CAPTIONS_URL; } else if (trackLowerCase.equals(Config.SECONDARY_LIVESTREAM_TRACK)) { // else if secondary track use secondary captions url captionsUrl = Config.SECONDARY_LIVESTREAM_CAPTIONS_URL; } else { // otherwise we don't have captions captionsUrl = null; } if (captionsUrl != null) { if (mDarkTheme) { captionsUrl += CAPTIONS_DARK_THEME_URL_PARAM; } mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl(captionsUrl); mNoCaptionsTextView.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } else { showNoCaptionsAvailable(); } } } private void showNoCaptionsAvailable() { mWebView.setVisibility(View.GONE); mNoCaptionsTextView.setVisibility(View.VISIBLE); } } private static class SessionShareData { String SESSION_TITLE; String SESSION_HASHTAG; String SESSION_URL; public SessionShareData(String title, String hashTag, String url) { SESSION_TITLE = title; SESSION_HASHTAG = hashTag; SESSION_URL = url; } } /** * Single session query */ public interface SessionSummaryQuery { int _TOKEN = 0; String[] PROJECTION = { ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, Tracks.TRACK_NAME, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int SESSION_ID = 0; int TITLE = 1; int ABSTRACT = 2; int HASHTAGS = 3; int LIVESTREAM_URL = 4; int TRACK_NAME = 5; int BLOCK_START= 6; int BLOCK_END = 7; } /** * List of sessions query */ public interface SessionsQuery { int _TOKEN = 1; String[] PROJECTION = { BaseColumns._ID, Sessions.SESSION_ID, Sessions.SESSION_TITLE, Tracks.TRACK_NAME, Tracks.TRACK_COLOR, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int ID = 0; int SESSION_ID = 1; int TITLE = 2; int TRACK_NAME = 3; int TRACK_COLOR = 4; int BLOCK_START= 5; int BLOCK_END = 6; } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.calendar.SessionAlarmService; import com.google.android.apps.iosched.calendar.SessionCalendarService; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.FractionalTouchDelegate; import com.google.android.apps.iosched.util.HelpUtils; import com.google.android.apps.iosched.util.ImageFetcher; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.android.plus.GooglePlus; import com.google.api.android.plus.PlusOneButton; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows detail information for a session, including session title, abstract, * time information, speaker photos and bios, etc. * * <p>This fragment is used in a number of activities, including * {@link com.google.android.apps.iosched.ui.phone.SessionDetailActivity}, * {@link com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity}, * {@link com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity}, etc. */ public class SessionDetailFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(SessionDetailFragment.class); // Set this boolean extra to true to show a variable height header public static final String EXTRA_VARIABLE_HEIGHT_HEADER = "com.google.android.iosched.extra.VARIABLE_HEIGHT_HEADER"; private String mSessionId; private Uri mSessionUri; private long mSessionBlockStart; private long mSessionBlockEnd; private String mTitleString; private String mHashtags; private String mUrl; private String mRoomId; private String mRoomName; private boolean mStarred; private boolean mInitStarred; private MenuItem mShareMenuItem; private MenuItem mStarMenuItem; private MenuItem mSocialStreamMenuItem; private ViewGroup mRootView; private TextView mTitle; private TextView mSubtitle; private PlusOneButton mPlusOneButton; private TextView mAbstract; private TextView mRequirements; private boolean mSessionCursor = false; private boolean mSpeakersCursor = false; private boolean mHasSummaryContent = false; private boolean mVariableHeightHeader = false; private ImageFetcher mImageFetcher; private List<Runnable> mDeferredUiOperations = new ArrayList<Runnable>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GooglePlus.initialize(getActivity(), Config.API_KEY, Config.CLIENT_ID); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSessionUri = intent.getData(); if (mSessionUri == null) { return; } mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri); mVariableHeightHeader = intent.getBooleanExtra(EXTRA_VARIABLE_HEIGHT_HEADER, false); LoaderManager manager = getLoaderManager(); manager.restartLoader(SessionsQuery._TOKEN, null, this); manager.restartLoader(SpeakersQuery._TOKEN, null, this); mImageFetcher = UIUtils.getImageFetcher(getActivity()); mImageFetcher.setImageFadeIn(false); setHasOptionsMenu(true); HelpUtils.maybeShowAddToScheduleTutorial(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_detail, null); mTitle = (TextView) mRootView.findViewById(R.id.session_title); mSubtitle = (TextView) mRootView.findViewById(R.id.session_subtitle); // Larger target triggers plus one button mPlusOneButton = (PlusOneButton) mRootView.findViewById(R.id.plus_one_button); final View plusOneParent = mRootView.findViewById(R.id.header_session); FractionalTouchDelegate.setupDelegate(plusOneParent, mPlusOneButton, new RectF(0.6f, 0f, 1f, 1.0f)); mAbstract = (TextView) mRootView.findViewById(R.id.session_abstract); mRequirements = (TextView) mRootView.findViewById(R.id.session_requirements); if (mVariableHeightHeader) { View headerView = mRootView.findViewById(R.id.header_session); ViewGroup.LayoutParams layoutParams = headerView.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; headerView.setLayoutParams(layoutParams); } return mRootView; } @Override public void onStop() { super.onStop(); if (mInitStarred != mStarred) { // Update Calendar event through the Calendar API on Android 4.0 or new versions. if (UIUtils.hasICS()) { Intent intent; if (mStarred) { // Set up intent to add session to Calendar, if it doesn't exist already. intent = new Intent(SessionCalendarService.ACTION_ADD_SESSION_CALENDAR, mSessionUri); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_START, mSessionBlockStart); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_END, mSessionBlockEnd); intent.putExtra(SessionCalendarService.EXTRA_SESSION_ROOM, mRoomName); intent.putExtra(SessionCalendarService.EXTRA_SESSION_TITLE, mTitleString); } else { // Set up intent to remove session from Calendar, if exists. intent = new Intent(SessionCalendarService.ACTION_REMOVE_SESSION_CALENDAR, mSessionUri); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_START, mSessionBlockStart); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_END, mSessionBlockEnd); intent.putExtra(SessionCalendarService.EXTRA_SESSION_TITLE, mTitleString); } intent.setClass(getActivity(), SessionCalendarService.class); getActivity().startService(intent); } if (mStarred && System.currentTimeMillis() < mSessionBlockStart) { setupNotification(); } } } @Override public void onPause() { super.onPause(); mImageFetcher.flushCache(); } @Override public void onDestroy() { super.onDestroy(); mImageFetcher.closeCache(); } private void setupNotification() { // Schedule an alarm that fires a system notification when expires. final Context ctx = getActivity(); Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, ctx, SessionAlarmService.class); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, mSessionBlockStart); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, mSessionBlockEnd); ctx.startService(scheduleIntent); } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionQueryComplete(Cursor cursor) { mSessionCursor = true; if (!cursor.moveToFirst()) { return; } mTitleString = cursor.getString(SessionsQuery.TITLE); // Format time block this session occupies mSessionBlockStart = cursor.getLong(SessionsQuery.BLOCK_START); mSessionBlockEnd = cursor.getLong(SessionsQuery.BLOCK_END); mRoomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = UIUtils.formatSessionSubtitle( mTitleString, mSessionBlockStart, mSessionBlockEnd, mRoomName, getActivity()); mTitle.setText(mTitleString); mUrl = cursor.getString(SessionsQuery.URL); if (TextUtils.isEmpty(mUrl)) { mUrl = ""; } mHashtags = cursor.getString(SessionsQuery.HASHTAGS); if (!TextUtils.isEmpty(mHashtags)) { enableSocialStreamMenuItemDeferred(); } mRoomId = cursor.getString(SessionsQuery.ROOM_ID); setupShareMenuItemDeferred(); showStarredDeferred(mInitStarred = (cursor.getInt(SessionsQuery.STARRED) != 0)); final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT); if (!TextUtils.isEmpty(sessionAbstract)) { UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract); mAbstract.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { mAbstract.setVisibility(View.GONE); } mPlusOneButton.setSize(PlusOneButton.Size.TALL); String url = cursor.getString(SessionsQuery.URL); if (TextUtils.isEmpty(url)) { mPlusOneButton.setVisibility(View.GONE); } else { mPlusOneButton.setUrl(url); } final View requirementsBlock = mRootView.findViewById(R.id.session_requirements_block); final String sessionRequirements = cursor.getString(SessionsQuery.REQUIREMENTS); if (!TextUtils.isEmpty(sessionRequirements)) { UIUtils.setTextMaybeHtml(mRequirements, sessionRequirements); requirementsBlock.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { requirementsBlock.setVisibility(View.GONE); } // Show empty message when all data is loaded, and nothing to show if (mSpeakersCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } ViewGroup linksContainer = (ViewGroup) mRootView.findViewById(R.id.links_container); linksContainer.removeAllViews(); LayoutInflater inflater = getLayoutInflater(null); boolean hasLinks = false; final Context context = mRootView.getContext(); // Render I/O live link final boolean hasLivestream = !TextUtils.isEmpty( cursor.getString(SessionsQuery.LIVESTREAM_URL)); long currentTimeMillis = UIUtils.getCurrentTime(context); if (UIUtils.hasHoneycomb() // Needs Honeycomb+ for the live stream && hasLivestream && currentTimeMillis > mSessionBlockStart && currentTimeMillis <= mSessionBlockEnd) { hasLinks = true; // Create the link item ViewGroup linkContainer = (ViewGroup) inflater.inflate(R.layout.list_item_session_link, linksContainer, false); ((TextView) linkContainer.findViewById(R.id.link_text)).setText( R.string.session_link_livestream); linkContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fireLinkEvent(R.string.session_link_livestream); Intent livestreamIntent = new Intent(Intent.ACTION_VIEW, mSessionUri); livestreamIntent.setClass(context, SessionLivestreamActivity.class); startActivity(livestreamIntent); } }); linksContainer.addView(linkContainer); } // Render normal links for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) { final String linkUrl = cursor.getString(SessionsQuery.LINKS_INDICES[i]); if (!TextUtils.isEmpty(linkUrl)) { hasLinks = true; // Create the link item ViewGroup linkContainer = (ViewGroup) inflater.inflate(R.layout.list_item_session_link, linksContainer, false); ((TextView) linkContainer.findViewById(R.id.link_text)).setText( SessionsQuery.LINKS_TITLES[i]); final int linkTitleIndex = i; linkContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fireLinkEvent(SessionsQuery.LINKS_TITLES[linkTitleIndex]); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(linkUrl)); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.safeOpenLink(context, intent); } }); linksContainer.addView(linkContainer); } } // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, mSessionBlockStart, mSessionBlockEnd, hasLivestream, null, null, mSubtitle, subtitle); mRootView.findViewById(R.id.session_links_block) .setVisibility(hasLinks ? View.VISIBLE : View.GONE); EasyTracker.getTracker().trackView("Session: " + mTitleString); LOGD("Tracker", "Session: " + mTitleString); } private void enableSocialStreamMenuItemDeferred() { mDeferredUiOperations.add(new Runnable() { @Override public void run() { mSocialStreamMenuItem.setVisible(true); } }); tryExecuteDeferredUiOperations(); } private void showStarredDeferred(final boolean starred) { mDeferredUiOperations.add(new Runnable() { @Override public void run() { showStarred(starred); } }); tryExecuteDeferredUiOperations(); } private void showStarred(boolean starred) { mStarMenuItem.setTitle(starred ? R.string.description_remove_schedule : R.string.description_add_schedule); mStarMenuItem.setIcon(starred ? R.drawable.ic_action_remove_schedule : R.drawable.ic_action_add_schedule); mStarred = starred; } private void setupShareMenuItemDeferred() { mDeferredUiOperations.add(new Runnable() { @Override public void run() { new SessionsHelper(getActivity()) .tryConfigureShareMenuItem(mShareMenuItem, R.string.share_template, mTitleString, mHashtags, mUrl); } }); tryExecuteDeferredUiOperations(); } private void tryExecuteDeferredUiOperations() { if (mStarMenuItem != null && mSocialStreamMenuItem != null) { for (Runnable r : mDeferredUiOperations) { r.run(); } mDeferredUiOperations.clear(); } } private void onSpeakersQueryComplete(Cursor cursor) { mSpeakersCursor = true; // TODO: remove existing speakers from layout, since this cursor might be from a data change final ViewGroup speakersGroup = (ViewGroup) mRootView.findViewById(R.id.session_speakers_block); final LayoutInflater inflater = getActivity().getLayoutInflater(); boolean hasSpeakers = false; while (cursor.moveToNext()) { final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME); if (TextUtils.isEmpty(speakerName)) { continue; } final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL); final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY); final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL); final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT); String speakerHeader = speakerName; if (!TextUtils.isEmpty(speakerCompany)) { speakerHeader += ", " + speakerCompany; } final View speakerView = inflater .inflate(R.layout.speaker_detail, speakersGroup, false); final TextView speakerHeaderView = (TextView) speakerView .findViewById(R.id.speaker_header); final ImageView speakerImageView = (ImageView) speakerView .findViewById(R.id.speaker_image); final TextView speakerAbstractView = (TextView) speakerView .findViewById(R.id.speaker_abstract); if (!TextUtils.isEmpty(speakerImageUrl)) { mImageFetcher.loadThumbnailImage(speakerImageUrl, speakerImageView, R.drawable.person_image_empty); } speakerHeaderView.setText(speakerHeader); speakerImageView.setContentDescription( getString(R.string.speaker_googleplus_profile, speakerHeader)); UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract); if (!TextUtils.isEmpty(speakerUrl)) { speakerImageView.setEnabled(true); speakerImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent speakerProfileIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(speakerUrl)); speakerProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), speakerProfileIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); UIUtils.safeOpenLink(getActivity(), speakerProfileIntent); } }); } else { speakerImageView.setEnabled(false); speakerImageView.setOnClickListener(null); } speakersGroup.addView(speakerView); hasSpeakers = true; mHasSummaryContent = true; } speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE); // Show empty message when all data is loaded, and nothing to show if (mSessionCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.session_detail, menu); mStarMenuItem = menu.findItem(R.id.menu_star); mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream); mShareMenuItem = menu.findItem(R.id.menu_share); tryExecuteDeferredUiOperations(); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); switch (item.getItemId()) { case R.id.menu_map: EasyTracker.getTracker().trackEvent( "Session", "Map", mTitleString, 0L); LOGD("Tracker", "Map: " + mTitleString); helper.startMapActivity(mRoomId); return true; case R.id.menu_star: boolean star = !mStarred; showStarred(star); helper.setSessionStarred(mSessionUri, star, mTitleString); Toast.makeText( getActivity(), getResources().getQuantityString(star ? R.plurals.toast_added_to_schedule : R.plurals.toast_removed_from_schedule, 1, 1), Toast.LENGTH_SHORT).show(); EasyTracker.getTracker().trackEvent( "Session", star ? "Starred" : "Unstarred", mTitleString, 0L); LOGD("Tracker", (star ? "Starred: " : "Unstarred: ") + mTitleString); return true; case R.id.menu_share: // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. helper.shareSession(getActivity(), R.string.share_template, mTitleString, mHashtags, mUrl); return true; case R.id.menu_social_stream: EasyTracker.getTracker().trackEvent( "Session", "Stream", mTitleString, 0L); LOGD("Tracker", "Stream: " + mTitleString); helper.startSocialStream(UIUtils.getSessionHashtagsString(mHashtags)); return true; } return super.onOptionsItemSelected(item); } /* * Event structure: * Category -> "Session Details" * Action -> Link Text * Label -> Session's Title * Value -> 0. */ public void fireLinkEvent(int actionId) { EasyTracker.getTracker().trackEvent( "Session", getActivity().getString(actionId), mTitleString, 0L); LOGD("Tracker", getActivity().getString(actionId) + ": " + mTitleString); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { CursorLoader loader = null; if (id == SessionsQuery._TOKEN){ loader = new CursorLoader(getActivity(), mSessionUri, SessionsQuery.PROJECTION, null, null, null); } else if (id == SpeakersQuery._TOKEN && mSessionUri != null){ Uri speakersUri = ScheduleContract.Sessions.buildSpeakersDirUri(mSessionId); loader = new CursorLoader(getActivity(), speakersUri, SpeakersQuery.PROJECTION, null, null, null); } return loader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } if (loader.getId() == SessionsQuery._TOKEN) { onSessionQueryComplete(cursor); } else if (loader.getId() == SpeakersQuery._TOKEN) { onSpeakersQueryComplete(cursor); } else { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) {} /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Sessions.SESSION_LEVEL, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_REQUIREMENTS, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_URL, ScheduleContract.Sessions.SESSION_YOUTUBE_URL, ScheduleContract.Sessions.SESSION_PDF_URL, ScheduleContract.Sessions.SESSION_NOTES_URL, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, ScheduleContract.Sessions.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, }; int BLOCK_START = 0; int BLOCK_END = 1; int LEVEL = 2; int TITLE = 3; int ABSTRACT = 4; int REQUIREMENTS = 5; int STARRED = 6; int HASHTAGS = 7; int URL = 8; int YOUTUBE_URL = 9; int PDF_URL = 10; int NOTES_URL = 11; int LIVESTREAM_URL = 12; int ROOM_ID = 13; int ROOM_NAME = 14; int[] LINKS_INDICES = { URL, YOUTUBE_URL, PDF_URL, NOTES_URL, }; int[] LINKS_TITLES = { R.string.session_link_main, R.string.session_link_youtube, R.string.session_link_pdf, R.string.session_link_notes, }; } private interface SpeakersQuery { int _TOKEN = 0x3; String[] PROJECTION = { ScheduleContract.Speakers.SPEAKER_NAME, ScheduleContract.Speakers.SPEAKER_IMAGE_URL, ScheduleContract.Speakers.SPEAKER_COMPANY, ScheduleContract.Speakers.SPEAKER_ABSTRACT, ScheduleContract.Speakers.SPEAKER_URL, }; int SPEAKER_NAME = 0; int SPEAKER_IMAGE_URL = 1; int SPEAKER_COMPANY = 2; int SPEAKER_ABSTRACT = 3; int SPEAKER_URL = 4; } }
Java
/* * Copyright 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.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.widget.SearchView; /** * A single-pane activity that shows a {@link SessionsFragment} containing a list of sessions. * This is used when showing the sessions for a given time slot, or showing session search results. */ public class SessionsActivity extends SimpleSinglePaneActivity implements SessionsFragment.Callbacks { @Override protected Fragment onCreatePane() { return new SessionsFragment(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.search, menu); setupSearchMenuItem(menu); return true; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupSearchMenuItem(Menu menu) { MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } }
Java
/* * Copyright 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.android.apps.iosched.ui.phone; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.SocialStreamActivity; import com.google.android.apps.iosched.ui.SocialStreamFragment; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * A single-pane activity that shows a {@link SessionsFragment} in one tab and a * {@link VendorsFragment} in another tab, representing the sessions and developer sandbox companies * for the given conference track (Android, Chrome, etc.). */ public class TrackDetailActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener, SessionsFragment.Callbacks, VendorsFragment.Callbacks, TrackInfoHelperFragment.Callbacks { private ViewPager mViewPager; private String mTrackId; private Uri mTrackUri; private boolean mShowVendors = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_track_detail); mTrackUri = getIntent().getData(); mTrackId = ScheduleContract.Tracks.getTrackId(mTrackUri); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(new TrackDetailPagerAdapter(getSupportFragmentManager())); mViewPager.setOnPageChangeListener(this); mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); mViewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width)); mShowVendors = !ScheduleContract.Tracks.CODELABS_TRACK_ID.equals(mTrackId) && !ScheduleContract.Tracks.TECH_TALK_TRACK_ID.equals(mTrackId); if (mShowVendors) { final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.addTab(actionBar.newTab() .setText(R.string.title_sessions) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_vendors) .setTabListener(this)); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri(mTrackUri), "track_info") .commit(); } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int position) { getSupportActionBar().setSelectedNavigationItem(position); int titleId = -1; switch (position) { case 0: titleId = R.string.title_sessions; break; case 1: titleId = R.string.title_vendors; break; } String title = getString(titleId); EasyTracker.getTracker().trackView(title + ": " + getTitle()); LOGD("Tracker", title + ": " + getTitle()); } @Override public void onPageScrollStateChanged(int i) { } private class TrackDetailPagerAdapter extends FragmentPagerAdapter { public TrackDetailPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(mTrackId)); if (position == 0) { Fragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(mTrackId)))); return fragment; } else { Fragment fragment = new VendorsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, allTracks ? ScheduleContract.Vendors.CONTENT_URI : ScheduleContract.Tracks.buildVendorsUri(mTrackId)))); return fragment; } } @Override public int getCount() { return mShowVendors ? 2 : 1; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.track_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_social_stream: Intent intent = new Intent(this, SocialStreamActivity.class); intent.putExtra(SocialStreamFragment.EXTRA_QUERY, UIUtils.getSessionHashtagsString(mTrackId)); startActivity(intent); break; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { setTitle(trackName); setActionBarColor(trackColor); EasyTracker.getTracker().trackView(getString(R.string.title_sessions) + ": " + getTitle()); LOGD("Tracker", getString(R.string.title_sessions) + ": " + getTitle()); } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } @Override public boolean onVendorSelected(String vendorId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Vendors.buildVendorUri(vendorId))); return false; } }
Java
/* * Copyright 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.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.actionbarsherlock.view.MenuItem; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.NavUtils; /** * A single-pane activity that shows a {@link VendorDetailFragment}. */ public class VendorDetailActivity extends SimpleSinglePaneActivity implements VendorDetailFragment.Callbacks, TrackInfoHelperFragment.Callbacks { private String mTrackId = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected Fragment onCreatePane() { return new VendorDetailFragment(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { // Up to this session's track details, or Home if no track is available Intent parentIntent; if (mTrackId != null) { parentIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { parentIntent = new Intent(this, HomeActivity.class); } NavUtils.navigateUpTo(this, parentIntent); return true; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { mTrackId = trackId; setTitle(trackName); setActionBarColor(trackColor); } @Override public void onTrackIdAvailable(final String trackId) { new Handler().post(new Runnable() { @Override public void run() { FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag("track_info") == null) { fm.beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri( ScheduleContract.Tracks.buildTrackUri(trackId)), "track_info") .commit(); } } }); } }
Java
/* * Copyright 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.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; /** * A single-pane activity that shows a {@link MapFragment}. */ public class MapActivity extends SimpleSinglePaneActivity implements MapFragment.Callbacks, LoaderManager.LoaderCallbacks<Cursor> { @Override protected Fragment onCreatePane() { return new MapFragment(); } @Override public void onRoomSelected(String roomId) { Bundle loadRoomDataArgs = new Bundle(); loadRoomDataArgs.putString("room_id", roomId); // force load (don't use previously used data) getSupportLoaderManager().restartLoader(0, loadRoomDataArgs, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(this, ScheduleContract.Rooms.buildRoomUri(data.getString("room_id")), RoomsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } Intent roomIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Rooms.buildSessionsDirUri( cursor.getString(RoomsQuery.ROOM_ID))); roomIntent.putExtra(Intent.EXTRA_TITLE, cursor.getString(RoomsQuery.ROOM_NAME)); startActivity(roomIntent); } finally { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } private interface RoomsQuery { String[] PROJECTION = { ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_FLOOR, }; int ROOM_ID = 0; int ROOM_NAME = 1; int ROOM_FLOOR = 2; } }
Java
/* * Copyright 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.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.NavUtils; /** * A single-pane activity that shows a {@link SessionDetailFragment}. */ public class SessionDetailActivity extends SimpleSinglePaneActivity implements TrackInfoHelperFragment.Callbacks { private String mTrackId = null; @Override protected void onCreate(Bundle savedInstanceState) { if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) { BeamUtils.setBeamUnlocked(this); showFirstBeamDialog(); } BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); if (savedInstanceState == null) { Uri sessionUri = getIntent().getData(); BeamUtils.setBeamSessionUri(this, sessionUri); trySetBeamCallback(); getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromSessionUri(sessionUri), "track_info") .commit(); } } @Override protected Fragment onCreatePane() { return new SessionDetailFragment(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { // Up to this session's track details, or Home if no track is available Intent parentIntent; if (mTrackId != null) { parentIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { parentIntent = new Intent(this, HomeActivity.class); } NavUtils.navigateUpTo(this, parentIntent); return true; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { mTrackId = trackId; setTitle(trackName); setActionBarColor(trackColor); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void trySetBeamCallback() { if (UIUtils.hasICS()) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override public void onNdefPushComplete(NfcEvent event) { // Beam has been sent if (!BeamUtils.isBeamUnlocked(SessionDetailActivity.this)) { BeamUtils.setBeamUnlocked(SessionDetailActivity.this); runOnUiThread(new Runnable() { @Override public void run() { showFirstBeamDialog(); } }); } } }); } } private void showFirstBeamDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_session) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(SessionDetailActivity.this); di.dismiss(); } }) .create() .show(); } }
Java
/* * Copyright 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.android.apps.iosched.ui.gtv; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.sync.SyncHelper; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionLivestreamActivity.SessionSummaryFragment; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.youtube.api.YouTube; import com.google.android.youtube.api.YouTubePlayer; import android.annotation.TargetApi; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A Google TV home activity for Google I/O 2012 that displays session live streams pulled in * from YouTube. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class GoogleTVSessionLivestreamActivity extends BaseActivity implements LoaderCallbacks<Cursor>, YouTubePlayer.OnPlaybackEventsListener, YouTubePlayer.OnFullscreenListener, OnItemClickListener { private static final String TAG = makeLogTag(GoogleTVSessionLivestreamActivity.class); private static final String TAG_SESSION_SUMMARY = "session_summary"; private static final int UPCOMING_SESSIONS_QUERY_ID = 3; private static final String PROMO_VIDEO_URL = "http://www.youtube.com/watch?v=gTA-5HM8Zhs"; private boolean mIsFullscreen = false; private boolean mTrackPlay = true; private YouTubePlayer mYouTubePlayer; private FrameLayout mPlayerContainer; private String mYouTubeVideoId; private LinearLayout mMainLayout; private LinearLayout mVideoLayout; private LinearLayout mExtraLayout; private FrameLayout mSummaryLayout; private ListView mLiveListView; private SyncHelper mGTVSyncHelper; private LivestreamAdapter mLivestreamAdapter; private String mSessionId; private Handler mHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); YouTube.initialize(this, Config.YOUTUBE_API_KEY); setContentView(R.layout.activity_session_livestream); // Set up YouTube player mYouTubePlayer = (YouTubePlayer) getSupportFragmentManager().findFragmentById( R.id.livestream_player); mYouTubePlayer.setOnPlaybackEventsListener(this); mYouTubePlayer.enableCustomFullscreen(this); mYouTubePlayer.setFullscreenControlFlags( YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI); // Views that are common over all layouts mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout); mPlayerContainer = (FrameLayout) findViewById(R.id.livestream_player_container); // Tablet UI specific views getSupportFragmentManager().beginTransaction().add(R.id.livestream_summary, new SessionSummaryFragment(), TAG_SESSION_SUMMARY).commit(); mVideoLayout = (LinearLayout) findViewById(R.id.livestream_videolayout); mExtraLayout = (LinearLayout) findViewById(R.id.googletv_livesextra_layout); mSummaryLayout = (FrameLayout) findViewById(R.id.livestream_summary); // Reload all other data in this activity reloadFromUri(getIntent().getData()); // Start sessions query to populate action bar navigation spinner getSupportLoaderManager().initLoader(SessionsQuery._TOKEN, null, this); // Set up left side listview mLivestreamAdapter = new LivestreamAdapter(this); mLiveListView = (ListView) findViewById(R.id.live_session_list); mLiveListView.setAdapter(mLivestreamAdapter); mLiveListView.setOnItemClickListener(this); mLiveListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); mLiveListView.setSelector(android.R.color.transparent); getSupportActionBar().hide(); // Sync data from Conference API new SyncOperationTask().execute((Void) null); } /** * Reloads all data in the activity and fragments from a given uri */ private void reloadFromUri(Uri newUri) { if (newUri != null && newUri.getPathSegments().size() >= 2) { mSessionId = Sessions.getSessionId(newUri); getSupportLoaderManager().restartLoader(SessionSummaryQuery._TOKEN, null, this); } } @Override public void onBackPressed() { if (mIsFullscreen) { // Exit full screen mode on back key mYouTubePlayer.setFullscreen(false); } else { super.onBackPressed(); } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int itemPosition, long itemId) { final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(itemPosition); final String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId != null) { reloadFromUri(Sessions.buildSessionUri(sessionId)); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { case SessionSummaryQuery._TOKEN: return new CursorLoader( this, Sessions.buildWithTracksUri(mSessionId), SessionSummaryQuery.PROJECTION, null, null, null); case SessionsQuery._TOKEN: final long currentTime = UIUtils.getCurrentTime(this); String selection = Sessions.LIVESTREAM_SELECTION + " and " + Sessions.AT_TIME_SELECTION; String[] selectionArgs = Sessions.buildAtTimeSelectionArgs(currentTime); return new CursorLoader(this, Sessions.buildWithTracksUri(), SessionsQuery.PROJECTION, selection, selectionArgs, null); case UPCOMING_SESSIONS_QUERY_ID: final long newCurrentTime = UIUtils.getCurrentTime(this); String sessionsSelection = Sessions.LIVESTREAM_SELECTION + " and " + Sessions.UPCOMING_SELECTION; String[] sessionsSelectionArgs = Sessions.buildUpcomingSelectionArgs(newCurrentTime); return new CursorLoader(this, Sessions.buildWithTracksUri(), SessionsQuery.PROJECTION, sessionsSelection, sessionsSelectionArgs, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mHandler.removeCallbacks(mNextSessionStartsInCountdownRunnable); switch (loader.getId()) { case SessionSummaryQuery._TOKEN: loadSession(data); break; case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(data); final int selected = locateSelectedItem(data); if (data.getCount() == 0) { handleNoLiveSessionsAvailable(); } else { mLiveListView.setSelection(selected); mLiveListView.requestFocus(selected); final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(selected); final String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId != null) { reloadFromUri(Sessions.buildSessionUri(sessionId)); } } break; case UPCOMING_SESSIONS_QUERY_ID: if (data != null && data.getCount() > 0) { data.moveToFirst(); handleUpdateNextUpcomingSession(data); } break; } } public void handleNoLiveSessionsAvailable() { getSupportLoaderManager().initLoader(UPCOMING_SESSIONS_QUERY_ID, null, this); updateSessionViews(PROMO_VIDEO_URL, getString(R.string.missed_io_title), getString(R.string.missed_io_subtitle), UIUtils.CONFERENCE_HASHTAG); //Make link in abstract view clickable TextView abstractLinkTextView = (TextView) findViewById(R.id.session_abstract); abstractLinkTextView.setMovementMethod(new LinkMovementMethod()); } private String mNextSessionTitle; private long mNextSessionStartTime; private final Runnable mNextSessionStartsInCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (mNextSessionStartTime - UIUtils.getCurrentTime( GoogleTVSessionLivestreamActivity.this)) / 1000); final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str; if (days == 0) { str = getResources().getString( R.string.starts_in_template_0_days, DateUtils.formatElapsedTime(secs)); } else { str = getResources().getQuantityString( R.plurals.starts_in_template, days, days, DateUtils.formatElapsedTime(secs)); } updateSessionSummaryFragment(mNextSessionTitle, str); if (remainingSec == 0) { // Next session starting now! mHandler.postDelayed(mRefreshSessionsRunnable, 1000); return; } // Repost ourselves to keep updating countdown mHandler.postDelayed(mNextSessionStartsInCountdownRunnable, 1000); } }; private final Runnable mRefreshSessionsRunnable = new Runnable() { @Override public void run() { getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, null, GoogleTVSessionLivestreamActivity.this); } }; public void handleUpdateNextUpcomingSession(Cursor data) { mNextSessionTitle = getString(R.string.next_live_stream_session_template, data.getString(SessionsQuery.TITLE)); mNextSessionStartTime = data.getLong(SessionsQuery.BLOCK_START); updateSessionViews(PROMO_VIDEO_URL, mNextSessionTitle, "", UIUtils.CONFERENCE_HASHTAG); // Begin countdown til next session mHandler.post(mNextSessionStartsInCountdownRunnable); } /** * Locates which item should be selected in the action bar drop-down spinner based on the * current active session uri */ private int locateSelectedItem(Cursor data) { int selected = 0; if (data != null && mSessionId != null) { while (data.moveToNext()) { if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) { selected = data.getPosition(); } } } return selected; } @Override public void onLoaderReset(Loader<Cursor> loader) { switch (loader.getId()) { case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(null); break; } } @Override public void onFullscreen(boolean fullScreen) { layoutFullscreenVideo(fullScreen); } @Override public void onLoaded(String s) { } @Override public void onPlaying() { } @Override public void onPaused() { } @Override public void onBuffering(boolean b) { } @Override public void onEnded() { mHandler.post(mRefreshSessionsRunnable); } @Override public void onError() { Toast.makeText(this, R.string.session_livestream_error, Toast.LENGTH_LONG).show(); LOGE(TAG, getString(R.string.session_livestream_error)); } private void loadSession(Cursor data) { if (data != null && data.moveToFirst()) { // Schedule a data refresh after the session ends. // NOTE: using postDelayed instead of postAtTime helps during debugging, using // mock times. mHandler.postDelayed(mRefreshSessionsRunnable, data.getLong(SessionSummaryQuery.BLOCK_END) + 1000 - UIUtils.getCurrentTime(this)); updateSessionViews( data.getString(SessionSummaryQuery.LIVESTREAM_URL), data.getString(SessionSummaryQuery.TITLE), data.getString(SessionSummaryQuery.ABSTRACT), data.getString(SessionSummaryQuery.HASHTAGS)); } } /** * Updates views that rely on session data from explicit strings. */ private void updateSessionViews(final String youtubeUrl, final String title, final String sessionAbstract, final String hashTag) { if (youtubeUrl == null) { // Get out, nothing to do here Toast.makeText(this, R.string.error_tv_no_url, Toast.LENGTH_SHORT).show(); LOGE(TAG, getString(R.string.error_tv_no_url)); return; } String youtubeVideoId = youtubeUrl; if (youtubeUrl.startsWith("http")) { final Uri youTubeUri = Uri.parse(youtubeUrl); youtubeVideoId = youTubeUri.getQueryParameter("v"); } playVideo(youtubeVideoId); if (mTrackPlay) { EasyTracker.getTracker().trackView("Live Streaming: " + title); LOGD("Tracker", "Live Streaming: " + title); } updateSessionSummaryFragment(title, sessionAbstract); mLiveListView.requestFocus(); } private void updateSessionSummaryFragment(String title, String sessionAbstract) { SessionSummaryFragment sessionSummaryFragment = (SessionSummaryFragment) getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY); if (sessionSummaryFragment != null) { sessionSummaryFragment.setSessionSummaryInfo(title, sessionAbstract); } } private void playVideo(String videoId) { if ((mYouTubeVideoId == null || !mYouTubeVideoId.equals(videoId)) && !TextUtils.isEmpty(videoId)) { mYouTubeVideoId = videoId; mYouTubePlayer.loadVideo(mYouTubeVideoId); mTrackPlay = true; } else { mTrackPlay = false; } } private void layoutFullscreenVideo(boolean fullscreen) { if (mIsFullscreen != fullscreen) { mIsFullscreen = fullscreen; mYouTubePlayer.setFullscreen(fullscreen); layoutGoogleTVFullScreen(fullscreen); // Full screen layout changes for all form factors final LayoutParams params = (LayoutParams) mPlayerContainer.getLayoutParams(); if (fullscreen) { params.height = LayoutParams.MATCH_PARENT; mMainLayout.setPadding(0, 0, 0, 0); } else { params.height = LayoutParams.WRAP_CONTENT; } mPlayerContainer.setLayoutParams(params); } } /** * Adjusts tablet layouts for full screen video. * * @param fullscreen True to layout in full screen, false to switch to regular layout */ private void layoutGoogleTVFullScreen(boolean fullscreen) { if (fullscreen) { mExtraLayout.setVisibility(View.GONE); mSummaryLayout.setVisibility(View.GONE); mMainLayout.setPadding(0, 0, 0, 0); mVideoLayout.setPadding(0, 0, 0, 0); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(0, 0, 0, 0); mVideoLayout.setLayoutParams(videoLayoutParams); } else { final int padding = getResources().getDimensionPixelSize(R.dimen.multipane_half_padding); mExtraLayout.setVisibility(View.VISIBLE); mSummaryLayout.setVisibility(View.VISIBLE); mMainLayout.setPadding(padding, padding, padding, padding); mVideoLayout.setBackgroundResource(R.drawable.grey_frame_on_white); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(padding, padding, padding, padding); mVideoLayout.setLayoutParams(videoLayoutParams); } } /** * Adapter that backs the action bar drop-down spinner. */ private class LivestreamAdapter extends CursorAdapter { private LayoutInflater mLayoutInflater; public LivestreamAdapter(Context context) { super(context, null, false); mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); } @Override public Object getItem(int position) { mCursor.moveToPosition(position); return mCursor; } @Override public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the side list view return mLayoutInflater.inflate( R.layout.list_item_live_session, parent, false); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the side list view return mLayoutInflater.inflate(R.layout.list_item_live_session, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { final TextView titleView = (TextView) view.findViewById(R.id.live_session_title); final TextView subTitleView = (TextView) view.findViewById(R.id.live_session_subtitle); String trackName = cursor.getString(SessionsQuery.TRACK_NAME); if (TextUtils.isEmpty(trackName)) { trackName = getString(R.string.app_name); } else { trackName = getString(R.string.session_livestream_track_title, trackName); } cursor.getInt(SessionsQuery.TRACK_COLOR); String sessionTitle = cursor.getString(SessionsQuery.TITLE); if (subTitleView != null) { titleView.setText(trackName); subTitleView.setText(sessionTitle); } else { // Selected view titleView.setText(getString(R.string.session_livestream_title) + ": " + trackName); } } } // Enabling media keys for Google TV Devices @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_MEDIA_PAUSE: mYouTubePlayer.pause(); return true; case KeyEvent.KEYCODE_MEDIA_PLAY: mYouTubePlayer.play(); return true; case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: mYouTubePlayer.seekRelativeMillis(20000); return true; case KeyEvent.KEYCODE_MEDIA_REWIND: mYouTubePlayer.seekRelativeMillis(-20000); return true; default: return super.onKeyDown(keyCode, event); } } // Need to sync with the conference API to get the livestream URLs private class SyncOperationTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { // Perform a sync using SyncHelper if (mGTVSyncHelper == null) { mGTVSyncHelper = new SyncHelper(getApplicationContext()); } try { mGTVSyncHelper.performSync(null, SyncHelper.FLAG_SYNC_LOCAL | SyncHelper.FLAG_SYNC_REMOTE); } catch (IOException e) { LOGE(TAG, "Error loading data for Google I/O 2012.", e); } return null; } } /** * Single session query */ public interface SessionSummaryQuery { int _TOKEN = 0; String[] PROJECTION = { ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int SESSION_ID = 0; int TITLE = 1; int ABSTRACT = 2; int HASHTAGS = 3; int LIVESTREAM_URL = 4; int TRACK_NAME = 5; int BLOCK_START= 6; int BLOCK_END = 7; } /** * List of sessions query */ public interface SessionsQuery { int _TOKEN = 1; String[] PROJECTION = { BaseColumns._ID, Sessions.SESSION_ID, Sessions.SESSION_TITLE, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int ID = 0; int SESSION_ID = 1; int TITLE = 2; int TRACK_NAME = 3; int TRACK_COLOR = 4; int BLOCK_START= 5; int BLOCK_END = 6; } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.ConsoleMessage; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Shows a {@link WebView} with a map of the conference venue. */ public class MapFragment extends SherlockFragment { private static final String TAG = makeLogTag(MapFragment.class); /** * When specified, will automatically point the map to the requested room. */ public static final String EXTRA_ROOM = "com.google.android.iosched.extra.ROOM"; private static final String SYSTEM_FEATURE_MULTITOUCH = "android.hardware.touchscreen.multitouch"; private static final String MAP_JSI_NAME = "MAP_CONTAINER"; private static final String MAP_URL = "http://ioschedmap.appspot.com/embed.html"; private static boolean CLEAR_CACHE_ON_LOAD = BuildConfig.DEBUG; private WebView mWebView; private View mLoadingSpinner; private boolean mMapInitialized = false; public interface Callbacks { public void onRoomSelected(String roomId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onRoomSelected(String roomId) { } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); EasyTracker.getTracker().trackView("Map"); LOGD("Tracker", "Map"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner, container, false); mLoadingSpinner = root.findViewById(R.id.loading_spinner); mWebView = (WebView) root.findViewById(R.id.webview); mWebView.setWebChromeClient(mWebChromeClient); mWebView.setWebViewClient(mWebViewClient); return root; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Initialize web view if (CLEAR_CACHE_ON_LOAD) { mWebView.clearCache(true); } boolean hideZoomControls = getActivity().getPackageManager().hasSystemFeature(SYSTEM_FEATURE_MULTITOUCH) && UIUtils.hasHoneycomb(); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); mWebView.loadUrl(MAP_URL + "?multitouch=" + (hideZoomControls ? 1 : 0)); mWebView.addJavascriptInterface(mMapJsiImpl, MAP_JSI_NAME); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.map, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_refresh) { mWebView.reload(); return true; } return super.onOptionsItemSelected(item); } private void runJs(final String js) { Activity activity = getActivity(); if (activity == null) { return; } activity.runOnUiThread(new Runnable() { @Override public void run() { LOGD(TAG, "Loading javascript:" + js); mWebView.loadUrl("javascript:" + js); } }); } /** * Helper method to escape JavaScript strings. Useful when passing strings to a WebView via * "javascript:" calls. */ private static String escapeJsString(String s) { if (s == null) { return ""; } return s.replace("'", "\\'").replace("\"", "\\\""); } public void panBy(float xFraction, float yFraction) { runJs("IoMap.panBy(" + xFraction + "," + yFraction + ");"); } /** * I/O Conference Map JavaScript interface. */ private interface MapJsi { public void openContentInfo(final String roomId); public void onMapReady(); } private final WebChromeClient mWebChromeClient = new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { LOGD(TAG, "JS Console message: (" + consoleMessage.sourceId() + ": " + consoleMessage.lineNumber() + ") " + consoleMessage.message()); return false; } }; private final WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mLoadingSpinner.setVisibility(View.VISIBLE); mWebView.setVisibility(View.INVISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mLoadingSpinner.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { LOGE(TAG, "Error " + errorCode + ": " + description); Toast.makeText(view.getContext(), "Error " + errorCode + ": " + description, Toast.LENGTH_LONG).show(); super.onReceivedError(view, errorCode, description, failingUrl); } }; private final MapJsi mMapJsiImpl = new MapJsi() { public void openContentInfo(final String roomId) { Activity activity = getActivity(); if (activity == null) { return; } activity.runOnUiThread(new Runnable() { @Override public void run() { mCallbacks.onRoomSelected(roomId); } }); } public void onMapReady() { LOGD(TAG, "onMapReady"); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); String showRoomId = null; if (!mMapInitialized && intent.hasExtra(EXTRA_ROOM)) { showRoomId = intent.getStringExtra(EXTRA_ROOM); } if (showRoomId != null) { runJs("IoMap.showLocationById('" + escapeJsString(showRoomId) + "');"); } mMapInitialized = true; } }; }
Java
/* * Copyright 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.android.apps.iosched.ui; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.BeamUtils; /** * Beam easter egg landing screen. */ public class BeamActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_beam); } @Override protected void onResume() { super.onResume(); if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) { BeamUtils.setBeamUnlocked(this); showUnlockDialog(); } } void showUnlockDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_default) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(BeamActivity.this); di.dismiss(); } }) .create() .show(); } void showHelpDialog() { new AlertDialog.Builder(this) .setTitle(R.string.title_beam) .setMessage(R.string.beam_unlocked_help) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(BeamActivity.this); di.dismiss(); } }) .create() .show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.beam, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_beam_help) { showHelpDialog(); return true; } return super.onOptionsItemSelected(item); } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NavUtils; /** * A base activity that handles common functionality in the app. */ public abstract class BaseActivity extends SherlockFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EasyTracker.getTracker().setContext(this); // If we're not on Google TV and we're not authenticated, finish this activity // and show the authentication screen. if (!UIUtils.isGoogleTV(this)) { if (!AccountUtils.isAuthenticated(this)) { AccountUtils.startAuthenticationFlow(this, getIntent()); finish(); } } // If Android Beam APIs are available, set up the Beam easter egg as the default Beam // content. This can be overridden by subclasses. if (UIUtils.hasICS()) { BeamUtils.setDefaultBeamUri(this); if (!BeamUtils.isBeamUnlocked(this)) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void onNdefPushComplete(NfcEvent event) { onBeamSent(); } }); } } getSupportActionBar().setHomeButtonEnabled(true); } private void onBeamSent() { if (!BeamUtils.isBeamUnlocked(this)) { BeamUtils.setBeamUnlocked(this); runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(BaseActivity.this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_default) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(BaseActivity.this); di.dismiss(); } }) .create() .show(); } }); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (this instanceof HomeActivity) { return false; } NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } /** * Sets the icon color using some fancy blending mode trickery. */ protected void setActionBarColor(int color) { if (color == 0) { color = 0xffffffff; } final Resources res = getResources(); Drawable maskDrawable = res.getDrawable(R.drawable.actionbar_icon_mask); if (!(maskDrawable instanceof BitmapDrawable)) { return; } Bitmap maskBitmap = ((BitmapDrawable) maskDrawable).getBitmap(); final int width = maskBitmap.getWidth(); final int height = maskBitmap.getHeight(); Bitmap outBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(outBitmap); canvas.drawBitmap(maskBitmap, 0, 0, null); Paint maskedPaint = new Paint(); maskedPaint.setColor(color); maskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); canvas.drawRect(0, 0, width, height, maskedPaint); BitmapDrawable outDrawable = new BitmapDrawable(res, outBitmap); getSupportActionBar().setIcon(outDrawable); } /** * Converts an intent into a {@link Bundle} suitable for use as fragment arguments. */ public static Bundle intentToFragmentArguments(Intent intent) { Bundle arguments = new Bundle(); if (intent == null) { return arguments; } final Uri data = intent.getData(); if (data != null) { arguments.putParcelable("_uri", data); } final Bundle extras = intent.getExtras(); if (extras != null) { arguments.putAll(intent.getExtras()); } return arguments; } /** * Converts a fragment arguments bundle into an intent. */ public static Intent fragmentArgumentsToIntent(Bundle arguments) { Intent intent = new Intent(); if (arguments == null) { return intent; } final Uri data = arguments.getParcelable("_uri"); if (data != null) { intent.setData(data); } intent.putExtras(arguments); intent.removeExtra("_uri"); return intent; } @Override protected void onStart() { super.onStart(); EasyTracker.getTracker().trackActivityStart(this); } @Override protected void onStop() { super.onStop(); EasyTracker.getTracker().trackActivityStop(this); } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; /** * A {@link BaseActivity} that simply contains a single fragment. The intent used to invoke this * activity is forwarded to the fragment as arguments during fragment instantiation. Derived * activities should only need to implement {@link SimpleSinglePaneActivity#onCreatePane()}. */ public abstract class SimpleSinglePaneActivity extends BaseActivity { private Fragment mFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_singlepane_empty); if (getIntent().hasExtra(Intent.EXTRA_TITLE)) { setTitle(getIntent().getStringExtra(Intent.EXTRA_TITLE)); } final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE); setTitle(customTitle != null ? customTitle : getTitle()); if (savedInstanceState == null) { mFragment = onCreatePane(); mFragment.setArguments(intentToFragmentArguments(getIntent())); getSupportFragmentManager().beginTransaction() .add(R.id.root_container, mFragment, "single_pane") .commit(); } else { mFragment = getSupportFragmentManager().findFragmentByTag("single_pane"); } } /** * Called in <code>onCreate</code> when the fragment constituting this activity is needed. * The returned fragment's arguments will be set to the intent used to invoke this activity. */ protected abstract Fragment onCreatePane(); public Fragment getFragment() { return mFragment; } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.apps.iosched.util.actionmodecompat.ActionMode; import com.google.android.apps.iosched.util.actionmodecompat.MultiChoiceModeListener; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.Spannable; import android.text.TextUtils; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.LinkedHashSet; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; import static com.google.android.apps.iosched.util.UIUtils.formatSessionSubtitle; /** * A {@link ListFragment} showing a list of sessions. This fragment supports multiple-selection * using the contextual action bar (on API 11+ devices), and also supports a separate 'activated' * state for indicating the currently-opened detail view on tablet devices. */ public class SessionsFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor>, MultiChoiceModeListener { private static final String TAG = makeLogTag(SessionsFragment.class); private static final String STATE_SELECTED_ID = "selectedId"; private CursorAdapter mAdapter; private String mSelectedSessionId; private MenuItem mStarredMenuItem; private MenuItem mMapMenuItem; private MenuItem mShareMenuItem; private MenuItem mSocialStreamMenuItem; private boolean mHasSetEmptyText = false; private int mSessionQueryToken; private LinkedHashSet<Integer> mSelectedSessionPositions = new LinkedHashSet<Integer>(); private Handler mHandler = new Handler(); public interface Callbacks { /** Return true to select (activate) the session in the list, false otherwise. */ public boolean onSessionSelected(String sessionId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public boolean onSessionSelected(String sessionId) { return true; } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mSelectedSessionId = savedInstanceState.getString(STATE_SELECTED_ID); } reloadFromArguments(getArguments()); } protected void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments setListAdapter(null); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri sessionsUri = intent.getData(); if (sessionsUri == null) { return; } if (!ScheduleContract.Sessions.isSearchUri(sessionsUri)) { mAdapter = new SessionsAdapter(getActivity()); mSessionQueryToken = SessionsQuery._TOKEN; } else { mAdapter = new SearchAdapter(getActivity()); mSessionQueryToken = SearchQuery._TOKEN; } setListAdapter(mAdapter); // Force start background query to load sessions getLoaderManager().restartLoader(mSessionQueryToken, arguments, this); } public void setSelectedSessionId(String id) { mSelectedSessionId = id; if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); listView.setCacheColorHint(Color.WHITE); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible // when it shouldn't // be visible. setEmptyText(getString(R.string.empty_sessions)); mHasSetEmptyText = true; } ActionMode.setMultiChoiceMode(getListView(), getActivity(), this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; getActivity().getContentResolver().unregisterContentObserver(mObserver); } @Override public void onResume() { super.onResume(); mHandler.post(mRefreshSessionsRunnable); } @Override public void onPause() { super.onPause(); mHandler.removeCallbacks(mRefreshSessionsRunnable); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSelectedSessionId != null) { outState.putString(STATE_SELECTED_ID, mSelectedSessionId); } } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); String sessionId = cursor.getString(cursor.getColumnIndex( ScheduleContract.Sessions.SESSION_ID)); if (mCallbacks.onSessionSelected(sessionId)) { mSelectedSessionId = sessionId; mAdapter.notifyDataSetChanged(); } } // LoaderCallbacks interface @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { final Intent intent = BaseActivity.fragmentArgumentsToIntent(data); final Uri sessionsUri = intent.getData(); Loader<Cursor> loader = null; if (id == SessionsQuery._TOKEN) { loader = new CursorLoader(getActivity(), sessionsUri, SessionsQuery.PROJECTION, null, null, ScheduleContract.Sessions.DEFAULT_SORT); } else if (id == SearchQuery._TOKEN) { loader = new CursorLoader(getActivity(), sessionsUri, SearchQuery.PROJECTION, null, null, ScheduleContract.Sessions.DEFAULT_SORT); } return loader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } int token = loader.getId(); if (token == SessionsQuery._TOKEN || token == SearchQuery._TOKEN) { mAdapter.changeCursor(cursor); Bundle arguments = getArguments(); if (arguments != null && arguments.containsKey("_uri")) { String uri = arguments.get("_uri").toString(); if(uri != null && uri.contains("blocks")) { String title = arguments.getString(Intent.EXTRA_TITLE); if (title == null) { title = (String) this.getActivity().getTitle(); } EasyTracker.getTracker().trackView("Session Block: " + title); LOGD("Tracker", "Session Block: " + title); } } } else { LOGD(TAG, "Query complete, Not Actionable: " + token); cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } // MultiChoiceModeListener interface @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); mode.finish(); switch (item.getItemId()) { case R.id.menu_map: { // multiple selection not supported int position = mSelectedSessionPositions.iterator().next(); Cursor cursor = (Cursor) mAdapter.getItem(position); String roomId = cursor.getString(SessionsQuery.ROOM_ID); helper.startMapActivity(roomId); String title = cursor.getString(SessionsQuery.TITLE); EasyTracker.getTracker().trackEvent( "Session", "Mapped", title, 0L); LOGV(TAG, "Starred: " + title); return true; } case R.id.menu_star: { // multiple selection supported boolean starred = false; int numChanged = 0; for (int position : mSelectedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(position); String title = cursor.getString(SessionsQuery.TITLE); String sessionId = cursor.getString(SessionsQuery.SESSION_ID); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); starred = cursor.getInt(SessionsQuery.STARRED) == 0; helper.setSessionStarred(sessionUri, starred, title); ++numChanged; EasyTracker.getTracker().trackEvent( "Session", starred ? "Starred" : "Unstarred", title, 0L); LOGV(TAG, "Starred: " + title); } Toast.makeText( getActivity(), getResources().getQuantityString(starred ? R.plurals.toast_added_to_schedule : R.plurals.toast_removed_from_schedule, numChanged, numChanged), Toast.LENGTH_SHORT).show(); setSelectedSessionStarred(starred); return true; } case R.id.menu_share: { // multiple selection not supported int position = mSelectedSessionPositions.iterator().next(); // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. Cursor cursor = (Cursor) mAdapter.getItem(position); new SessionsHelper(getActivity()).shareSession(getActivity(), R.string.share_template, cursor.getString(SessionsQuery.TITLE), cursor.getString(SessionsQuery.HASHTAGS), cursor.getString(SessionsQuery.URL)); return true; } case R.id.menu_social_stream: StringBuilder hashtags = new StringBuilder(); for (int position : mSelectedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(position); String term = cursor.getString(SessionsQuery.HASHTAGS); if (!term.startsWith("#")) { term = "#" + term; } if (hashtags.length() > 0) { hashtags.append(" OR "); } hashtags.append(term); String title = cursor.getString(SessionsQuery.TITLE); EasyTracker.getTracker().trackEvent( "Session", "Mapped", title, 0L); LOGV(TAG, "Starred: " + title); } helper.startSocialStream(hashtags.toString()); return true; default: LOGW(TAG, "CAB unknown selection=" + item.getItemId()); return false; } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.sessions_context, menu); mStarredMenuItem = menu.findItem(R.id.menu_star); mMapMenuItem = menu.findItem(R.id.menu_map); mShareMenuItem = menu.findItem(R.id.menu_share); mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream); mSelectedSessionPositions.clear(); return true; } @Override public void onDestroyActionMode(ActionMode mode) {} @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { if (checked) { mSelectedSessionPositions.add(position); } else { mSelectedSessionPositions.remove(position); } int numSelectedSessions = mSelectedSessionPositions.size(); mode.setTitle(getResources().getQuantityString( R.plurals.title_selected_sessions, numSelectedSessions, numSelectedSessions)); if (numSelectedSessions == 1) { // activate all the menu item mMapMenuItem.setVisible(true); mShareMenuItem.setVisible(true); mSocialStreamMenuItem.setVisible(true); mStarredMenuItem.setVisible(true); position = mSelectedSessionPositions.iterator().next(); Cursor cursor = (Cursor) mAdapter.getItem(position); boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; setSelectedSessionStarred(starred); } else { mMapMenuItem.setVisible(false); mShareMenuItem.setVisible(false); mSocialStreamMenuItem.setVisible(false); boolean allStarred = true; boolean allUnstarred = true; for (int pos : mSelectedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(pos); boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; allStarred = allStarred && starred; allUnstarred = allUnstarred && !starred; } if (allStarred) { setSelectedSessionStarred(true); mStarredMenuItem.setVisible(true); } else if (allUnstarred) { setSelectedSessionStarred(false); mStarredMenuItem.setVisible(true); } else { mStarredMenuItem.setVisible(false); } } } private void setSelectedSessionStarred(boolean starred) { mStarredMenuItem.setTitle(starred ? R.string.description_remove_schedule : R.string.description_add_schedule); mStarredMenuItem.setIcon(starred ? R.drawable.ic_action_remove_schedule : R.drawable.ic_action_add_schedule); } private final Runnable mRefreshSessionsRunnable = new Runnable() { public void run() { if (mAdapter != null) { // This is used to refresh session title colors. mAdapter.notifyDataSetChanged(); } // Check again on the next quarter hour, with some padding to // account for network // time differences. long nextQuarterHour = (SystemClock.uptimeMillis() / 900000 + 1) * 900000 + 5000; mHandler.postAtTime(mRefreshSessionsRunnable, nextQuarterHour); } }; private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(mSessionQueryToken); if (loader != null) { loader.forceLoad(); } } }; /** * {@link CursorAdapter} that renders a {@link SessionsQuery}. */ private class SessionsAdapter extends CursorAdapter { public SessionsAdapter(Context context) { super(context, null, false); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId == null) { return; } if (sessionId.equals(mSelectedSessionId)){ UIUtils.setActivatedCompat(view, true); } else { UIUtils.setActivatedCompat(view, false); } final TextView titleView = (TextView) view.findViewById(R.id.session_title); final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle); final String sessionTitle = cursor.getString(SessionsQuery.TITLE); titleView.setText(sessionTitle); // Format time block this session occupies final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END); final String roomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = formatSessionSubtitle( sessionTitle, blockStart, blockEnd, roomName, context); final boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; view.findViewById(R.id.indicator_in_schedule).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); final boolean hasLivestream = !TextUtils.isEmpty( cursor.getString(SessionsQuery.LIVESTREAM_URL)); // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, blockStart, blockEnd, hasLivestream, view.findViewById(R.id.list_item_session), titleView, subtitleView, subtitle); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null, false); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { UIUtils.setActivatedCompat(view, cursor.getString(SessionsQuery.SESSION_ID) .equals(mSelectedSessionId)); ((TextView) view.findViewById(R.id.session_title)).setText(cursor .getString(SearchQuery.TITLE)); final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET); final Spannable styledSnippet = buildStyledSnippet(snippet); ((TextView) view.findViewById(R.id.session_subtitle)).setText(styledSnippet); final boolean starred = cursor.getInt(SearchQuery.STARRED) != 0; view.findViewById(R.id.indicator_in_schedule).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} * query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_URL, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int BLOCK_START = 4; int BLOCK_END = 5; int ROOM_NAME = 6; int ROOM_ID = 7; int HASHTAGS = 8; int URL = 9; int LIVESTREAM_URL = 10; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} * search query parameters. */ private interface SearchQuery { int _TOKEN = 0x3; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Sessions.SEARCH_SNIPPET, ScheduleContract.Sessions.SESSION_LEVEL, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_URL }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int SEARCH_SNIPPET = 4; int LEVEL = 5; int ROOM_NAME = 6; int ROOM_ID = 7; int HASHTAGS = 8; int URL = 9; } }
Java
/* * Copyright 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.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Announcements; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; /** * A fragment used in {@link HomeActivity} that shows either a countdown, * announcements, or 'thank you' text, at different times (before/during/after * the conference). */ public class WhatsOnFragment extends Fragment implements LoaderCallbacks<Cursor> { private Handler mHandler = new Handler(); private TextView mCountdownTextView; private ViewGroup mRootView; private Cursor mAnnouncementsCursor; private LayoutInflater mInflater; private int mTitleCol = -1; private int mDateCol = -1; private int mUrlCol = -1; private static final int ANNOUNCEMENTS_LOADER_ID = 0; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_whats_on, container); refresh(); return mRootView; } @Override public void onDetach() { super.onDetach(); mHandler.removeCallbacks(mCountdownRunnable); getActivity().getContentResolver().unregisterContentObserver(mObserver); } private void refresh() { mHandler.removeCallbacks(mCountdownRunnable); mRootView.removeAllViews(); final long currentTimeMillis = UIUtils.getCurrentTime(getActivity()); // Show Loading... and load the view corresponding to the current state if (currentTimeMillis < UIUtils.CONFERENCE_START_MILLIS) { setupBefore(); } else if (currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS) { setupAfter(); } else { setupDuring(); } } private void setupBefore() { // Before conference, show countdown. mCountdownTextView = (TextView) mInflater .inflate(R.layout.whats_on_countdown, mRootView, false); mRootView.addView(mCountdownTextView); mHandler.post(mCountdownRunnable); } private void setupAfter() { // After conference, show canned text. mInflater.inflate(R.layout.whats_on_thank_you, mRootView, true); } private void setupDuring() { // Start background query to load announcements getLoaderManager().initLoader(ANNOUNCEMENTS_LOADER_ID, null, this); getActivity().getContentResolver().registerContentObserver( Announcements.CONTENT_URI, true, mObserver); } /** * Event that updates countdown timer. Posts itself again to * {@link #mHandler} to continue updating time. */ private final Runnable mCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (UIUtils.CONFERENCE_START_MILLIS - UIUtils .getCurrentTime(getActivity())) / 1000); final boolean conferenceStarted = remainingSec == 0; if (conferenceStarted) { // Conference started while in countdown mode, switch modes and // bail on future countdown updates. mHandler.postDelayed(new Runnable() { public void run() { refresh(); } }, 100); return; } final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str; if (days == 0) { str = getResources().getString( R.string.whats_on_countdown_title_0, DateUtils.formatElapsedTime(secs)); } else { str = getResources().getQuantityString( R.plurals.whats_on_countdown_title, days, days, DateUtils.formatElapsedTime(secs)); } mCountdownTextView.setText(str); // Repost ourselves to keep updating countdown mHandler.postDelayed(mCountdownRunnable, 1000); } }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), Announcements.CONTENT_URI, null, null, null, Announcements.ANNOUNCEMENT_DATE + " DESC"); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (getActivity() == null) { return; } if (data != null && data.getCount() > 0) { mTitleCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_TITLE); mDateCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_DATE); mUrlCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_URL); showAnnouncements(data); } else { showNoAnnouncements(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mAnnouncementsCursor = null; } /** * Show the the announcements */ private void showAnnouncements(Cursor announcements) { mAnnouncementsCursor = announcements; ViewGroup announcementsRootView = (ViewGroup) mInflater.inflate( R.layout.whats_on_announcements, mRootView, false); final ViewPager pager = (ViewPager) announcementsRootView.findViewById( R.id.announcements_pager); final View previousButton = announcementsRootView.findViewById( R.id.announcements_previous_button); final View nextButton = announcementsRootView.findViewById( R.id.announcements_next_button); final PagerAdapter adapter = new AnnouncementsAdapter(); pager.setAdapter(adapter); pager.setPageMargin( getResources().getDimensionPixelSize(R.dimen.announcements_margin_width)); pager.setPageMarginDrawable(R.drawable.announcements_divider); pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { previousButton.setEnabled(position > 0); nextButton.setEnabled(position < adapter.getCount() - 1); } }); previousButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { pager.setCurrentItem(pager.getCurrentItem() - 1); } }); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { pager.setCurrentItem(pager.getCurrentItem() + 1); } }); previousButton.setEnabled(false); nextButton.setEnabled(adapter.getCount() > 1); mRootView.removeAllViews(); mRootView.addView(announcementsRootView); } /** * Show a placeholder message */ private void showNoAnnouncements() { mInflater.inflate(R.layout.empty_announcements, mRootView, true); } public class AnnouncementsAdapter extends PagerAdapter { @Override public Object instantiateItem(ViewGroup pager, int position) { mAnnouncementsCursor.moveToPosition(position); LinearLayout rootView = (LinearLayout) mInflater.inflate( R.layout.pager_item_announcement, pager, false); TextView titleView = (TextView) rootView.findViewById(R.id.announcement_title); TextView subtitleView = (TextView) rootView.findViewById(R.id.announcement_ago); titleView.setText(mAnnouncementsCursor.getString(mTitleCol)); final long date = mAnnouncementsCursor.getLong(mDateCol); final String when = UIUtils.getTimeAgo(date, getActivity()); final String url = mAnnouncementsCursor.getString(mUrlCol); subtitleView.setText(when); rootView.setTag(url); if (!TextUtils.isEmpty(url)) { rootView.setClickable(true); rootView.setOnClickListener(mAnnouncementClick); } else { rootView.setClickable(false); } pager.addView(rootView, 0); return rootView; } private final OnClickListener mAnnouncementClick = new OnClickListener() { @Override public void onClick(View v) { String url = (String) v.getTag(); if (!TextUtils.isEmpty(url)) { UIUtils.safeOpenLink(getActivity(), new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } } }; @Override public void destroyItem(ViewGroup pager, int position, Object view) { pager.removeView((View) view); } @Override public int getCount() { return mAnnouncementsCursor.getCount(); } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public int getItemPosition(Object object) { return POSITION_NONE; } } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(ANNOUNCEMENTS_LOADER_ID); if (loader != null) { loader.forceLoad(); } } }; }
Java
/* * Copyright 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.android.apps.iosched.calendar; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred * session blocks. */ public class SessionAlarmReceiver extends BroadcastReceiver { public static final String TAG = makeLogTag(SessionAlarmReceiver.class); @Override public void onReceive(Context context, Intent intent) { Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS, null, context, SessionAlarmService.class); context.startService(scheduleIntent); } }
Java
/* * Copyright 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.android.apps.iosched.calendar; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.UIUtils; import android.annotation.TargetApi; import android.app.IntentService; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.content.OperationApplicationException; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.RemoteException; import android.provider.CalendarContract; import android.text.TextUtils; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Background {@link android.app.Service} that adds or removes session Calendar events through * the {@link CalendarContract} API available in Android 4.0 or above. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class SessionCalendarService extends IntentService { private static final String TAG = makeLogTag(SessionCalendarService.class); public static final String ACTION_ADD_SESSION_CALENDAR = "com.google.android.apps.iosched.action.ADD_SESSION_CALENDAR"; public static final String ACTION_REMOVE_SESSION_CALENDAR = "com.google.android.apps.iosched.action.REMOVE_SESSION_CALENDAR"; public static final String ACTION_UPDATE_ALL_SESSIONS_CALENDAR = "com.google.android.apps.iosched.action.UPDATE_ALL_SESSIONS_CALENDAR"; public static final String ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED = "com.google.android.apps.iosched.action.UPDATE_CALENDAR_COMPLETED"; public static final String ACTION_CLEAR_ALL_SESSIONS_CALENDAR = "com.google.android.apps.iosched.action.CLEAR_ALL_SESSIONS_CALENDAR"; public static final String EXTRA_ACCOUNT_NAME = "com.google.android.apps.iosched.extra.ACCOUNT_NAME"; public static final String EXTRA_SESSION_BLOCK_START = "com.google.android.apps.iosched.extra.SESSION_BLOCK_START"; public static final String EXTRA_SESSION_BLOCK_END = "com.google.android.apps.iosched.extra.SESSION_BLOCK_END"; public static final String EXTRA_SESSION_TITLE = "com.google.android.apps.iosched.extra.SESSION_TITLE"; public static final String EXTRA_SESSION_ROOM = "com.google.android.apps.iosched.extra.SESSION_ROOM"; private static final long INVALID_CALENDAR_ID = -1; // TODO: localize private static final String CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION = "%added by Google I/O 2012%"; public SessionCalendarService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { final String action = intent.getAction(); final ContentResolver resolver = getContentResolver(); boolean isAddEvent = false; if (ACTION_ADD_SESSION_CALENDAR.equals(action)) { isAddEvent = true; } else if (ACTION_REMOVE_SESSION_CALENDAR.equals(action)) { isAddEvent = false; } else if (ACTION_UPDATE_ALL_SESSIONS_CALENDAR.equals(action)) { try { getContentResolver().applyBatch(CalendarContract.AUTHORITY, processAllSessionsCalendar(resolver, getCalendarId(intent))); sendBroadcast(new Intent( SessionCalendarService.ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED)); } catch (RemoteException e) { LOGE(TAG, "Error adding all sessions to Google Calendar", e); } catch (OperationApplicationException e) { LOGE(TAG, "Error adding all sessions to Google Calendar", e); } } else if (ACTION_CLEAR_ALL_SESSIONS_CALENDAR.equals(action)) { try { getContentResolver().applyBatch(CalendarContract.AUTHORITY, processClearAllSessions(resolver, getCalendarId(intent))); } catch (RemoteException e) { LOGE(TAG, "Error clearing all sessions from Google Calendar", e); } catch (OperationApplicationException e) { LOGE(TAG, "Error clearing all sessions from Google Calendar", e); } } else { return; } final Uri uri = intent.getData(); final Bundle extras = intent.getExtras(); if (uri == null || extras == null) { return; } try { resolver.applyBatch(CalendarContract.AUTHORITY, processSessionCalendar(resolver, getCalendarId(intent), isAddEvent, uri, extras.getLong(EXTRA_SESSION_BLOCK_START), extras.getLong(EXTRA_SESSION_BLOCK_END), extras.getString(EXTRA_SESSION_TITLE), extras.getString(EXTRA_SESSION_ROOM))); } catch (RemoteException e) { LOGE(TAG, "Error adding session to Google Calendar", e); } catch (OperationApplicationException e) { LOGE(TAG, "Error adding session to Google Calendar", e); } } /** * Gets the currently-logged in user's Google Calendar, or the Google Calendar for the user * specified in the given intent's {@link #EXTRA_ACCOUNT_NAME}. */ private long getCalendarId(Intent intent) { final String accountName; if (intent != null && intent.hasExtra(EXTRA_ACCOUNT_NAME)) { accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME); } else { accountName = AccountUtils.getChosenAccountName(this); } if (TextUtils.isEmpty(accountName)) { return INVALID_CALENDAR_ID; } // TODO: The calendar ID should be stored in shared preferences upon choosing an account. Cursor calendarsCursor = getContentResolver().query( CalendarContract.Calendars.CONTENT_URI, new String[]{"_id"}, // TODO: Handle case where the calendar is not displayed or not sync'd "account_name = ownerAccount and account_name = ?", new String[]{accountName}, null); long calendarId = INVALID_CALENDAR_ID; if (calendarsCursor != null && calendarsCursor.moveToFirst()) { calendarId = calendarsCursor.getLong(0); calendarsCursor.close(); } return calendarId; } private String makeCalendarEventTitle(String sessionTitle) { return sessionTitle + getResources().getString(R.string.session_calendar_suffix); } /** * Processes all sessions in the * {@link com.google.android.apps.iosched.provider.ScheduleProvider}, adding or removing * calendar events to/from the specified Google Calendar depending on whether a session is * in the user's schedule or not. */ private ArrayList<ContentProviderOperation> processAllSessionsCalendar(ContentResolver resolver, final long calendarId) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Unable to find the Calendar associated with the user. Stop here. if (calendarId == INVALID_CALENDAR_ID) { return batch; } // Retrieves all sessions. For each session, add to Calendar if starred and attempt to // remove from Calendar if unstarred. Cursor cursor = resolver.query( ScheduleContract.Sessions.CONTENT_URI, SessionsQuery.PROJECTION, null, null, null); if (cursor != null) { while (cursor.moveToNext()) { Uri uri = ScheduleContract.Sessions.buildSessionUri( Long.valueOf(cursor.getLong(0)).toString()); boolean isAddEvent = (cursor.getInt(SessionsQuery.SESSION_STARRED) == 1); if (isAddEvent) { batch.addAll(processSessionCalendar(resolver, calendarId, isAddEvent, uri, cursor.getLong(SessionsQuery.BLOCK_START), cursor.getLong(SessionsQuery.BLOCK_END), cursor.getString(SessionsQuery.SESSION_TITLE), cursor.getString(SessionsQuery.ROOM_NAME))); } } cursor.close(); } return batch; } /** * Adds or removes a single session to/from the specified Google Calendar. */ private ArrayList<ContentProviderOperation> processSessionCalendar( final ContentResolver resolver, final long calendarId, final boolean isAddEvent, final Uri sessionUri, final long sessionBlockStart, final long sessionBlockEnd, final String sessionTitle, final String sessionRoom) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Unable to find the Calendar associated with the user. Stop here. if (calendarId == INVALID_CALENDAR_ID) { return batch; } final String calendarEventTitle = makeCalendarEventTitle(sessionTitle); Cursor cursor; ContentValues values = new ContentValues(); // Add Calendar event. if (isAddEvent) { if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) { LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters."); return batch; } // Check if the calendar event exists first. If it does, we don't want to add a // duplicate one. cursor = resolver.query( CalendarContract.Events.CONTENT_URI, // URI new String[] {CalendarContract.Events._ID}, // Projection CalendarContract.Events.CALENDAR_ID + "=? and " // Selection + CalendarContract.Events.TITLE + "=? and " + CalendarContract.Events.DTSTART + ">=? and " + CalendarContract.Events.DTEND + "<=?", new String[]{ // Selection args Long.valueOf(calendarId).toString(), calendarEventTitle, Long.toString(UIUtils.CONFERENCE_START_MILLIS), Long.toString(UIUtils.CONFERENCE_END_MILLIS) }, null); long newEventId = -1; if (cursor != null && cursor.moveToFirst()) { // Calendar event already exists for this session. newEventId = cursor.getLong(0); cursor.close(); } else { // Calendar event doesn't exist, create it. // NOTE: we can't use batch processing here because we need the result of // the insert. values.clear(); values.put(CalendarContract.Events.DTSTART, sessionBlockStart); values.put(CalendarContract.Events.DTEND, sessionBlockEnd); values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom); values.put(CalendarContract.Events.TITLE, calendarEventTitle); values.put(CalendarContract.Events.CALENDAR_ID, calendarId); values.put(CalendarContract.Events.EVENT_TIMEZONE, UIUtils.CONFERENCE_TIME_ZONE.getID()); Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values); String eventId = eventUri.getLastPathSegment(); if (eventId == null) { return batch; // Should be empty at this point } newEventId = Long.valueOf(eventId); // Since we're adding session reminder to system notification, we're not creating // Calendar event reminders. If we were to create Calendar event reminders, this // is how we would do it. //values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId)); //values.put(CalendarContract.Reminders.MINUTES, 10); //values.put(CalendarContract.Reminders.METHOD, // CalendarContract.Reminders.METHOD_ALERT); // Or default? //cr.insert(CalendarContract.Reminders.CONTENT_URI, values); //values.clear(); } // Update the session in our own provider with the newly created calendar event ID. values.clear(); values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId); resolver.update(sessionUri, values, null, null); } else { // Remove Calendar event, if exists. // Get the event calendar id. cursor = resolver.query(sessionUri, new String[] {ScheduleContract.Sessions.SESSION_CAL_EVENT_ID}, null, null, null); long calendarEventId = -1; if (cursor != null && cursor.moveToFirst()) { calendarEventId = cursor.getLong(0); cursor.close(); } // Try to remove the Calendar Event based on key. If successful, move on; // otherwise, remove the event based on Event title. int affectedRows = 0; if (calendarEventId != -1) { affectedRows = resolver.delete( CalendarContract.Events.CONTENT_URI, CalendarContract.Events._ID + "=?", new String[]{Long.valueOf(calendarEventId).toString()}); } if (affectedRows == 0) { resolver.delete(CalendarContract.Events.CONTENT_URI, String.format("%s=? and %s=? and %s=? and %s=?", CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND), new String[]{Long.valueOf(calendarId).toString(), calendarEventTitle, Long.valueOf(sessionBlockStart).toString(), Long.valueOf(sessionBlockEnd).toString()}); } // Remove the session and calendar event association. values.clear(); values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null); resolver.update(sessionUri, values, null, null); } return batch; } /** * Removes all calendar entries associated with Google I/O 2012. */ private ArrayList<ContentProviderOperation> processClearAllSessions( ContentResolver resolver, long calendarId) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Unable to find the Calendar associated with the user. Stop here. if (calendarId == INVALID_CALENDAR_ID) { return batch; } // Delete all calendar entries matching the given title within the given time period batch.add(ContentProviderOperation .newDelete(CalendarContract.Events.CONTENT_URI) .withSelection( CalendarContract.Events.CALENDAR_ID + " = ? and " + CalendarContract.Events.TITLE + " LIKE ? and " + CalendarContract.Events.DTSTART + ">= ? and " + CalendarContract.Events.DTEND + "<= ?", new String[]{ Long.toString(calendarId), CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION, Long.toString(UIUtils.CONFERENCE_START_MILLIS), Long.toString(UIUtils.CONFERENCE_END_MILLIS) }) .build()); return batch; } private interface SessionsQuery { String[] PROJECTION = { ScheduleContract.Sessions._ID, ScheduleContract.Sessions.BLOCK_START, ScheduleContract.Sessions.BLOCK_END, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.ROOM_NAME, ScheduleContract.Sessions.SESSION_STARRED, }; int _ID = 0; int BLOCK_START = 1; int BLOCK_END = 2; int SESSION_TITLE = 3; int ROOM_NAME = 4; int SESSION_STARRED = 5; } }
Java
/* * Copyright 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.android.apps.iosched.calendar; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.UIUtils; import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.support.v4.app.NotificationCompat; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Background service to handle scheduling of starred session notification via * {@link android.app.AlarmManager}. */ public class SessionAlarmService extends IntentService { private static final String TAG = makeLogTag(SessionAlarmService.class); public static final String ACTION_NOTIFY_SESSION = "com.google.android.apps.iosched.action.NOTIFY_SESSION"; public static final String ACTION_SCHEDULE_STARRED_BLOCK = "com.google.android.apps.iosched.action.SCHEDULE_STARRED_BLOCK"; public static final String ACTION_SCHEDULE_ALL_STARRED_BLOCKS = "com.google.android.apps.iosched.action.SCHEDULE_ALL_STARRED_BLOCKS"; public static final String EXTRA_SESSION_START = "com.google.android.apps.iosched.extra.SESSION_START"; public static final String EXTRA_SESSION_END = "com.google.android.apps.iosched.extra.SESSION_END"; public static final String EXTRA_SESSION_ALARM_OFFSET = "com.google.android.apps.iosched.extra.SESSION_ALARM_OFFSET"; private static final int NOTIFICATION_ID = 100; // pulsate every 1 second, indicating a relatively high degree of urgency private static final int NOTIFICATION_LED_ON_MS = 100; private static final int NOTIFICATION_LED_OFF_MS = 1000; private static final int NOTIFICATION_ARGB_COLOR = 0xff0088ff; // cyan private static final long ONE_MINUTE_MILLIS = 1 * 60 * 1000; private static final long TEN_MINUTES_MILLIS = 10 * ONE_MINUTE_MILLIS; private static final long UNDEFINED_ALARM_OFFSET = -1; public SessionAlarmService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { final String action = intent.getAction(); if (ACTION_SCHEDULE_ALL_STARRED_BLOCKS.equals(action)) { scheduleAllStarredBlocks(); return; } final long sessionStart = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_START, -1); if (sessionStart == -1) { return; } final long sessionEnd = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_END, -1); if (sessionEnd == -1) { return; } final long sessionAlarmOffset = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, UNDEFINED_ALARM_OFFSET); if (ACTION_NOTIFY_SESSION.equals(action)) { notifySession(sessionStart, sessionEnd, sessionAlarmOffset); } else if (ACTION_SCHEDULE_STARRED_BLOCK.equals(action)) { scheduleAlarm(sessionStart, sessionEnd, sessionAlarmOffset); } } private void scheduleAlarm(final long sessionStart, final long sessionEnd, final long alarmOffset) { NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(NOTIFICATION_ID); final long currentTime = System.currentTimeMillis(); // If the session is already started, do not schedule system notification. if (currentTime > sessionStart) { return; } // By default, sets alarm to go off at 10 minutes before session start time. If alarm // offset is provided, alarm is set to go off by that much time from now. long alarmTime; if (alarmOffset == UNDEFINED_ALARM_OFFSET) { alarmTime = sessionStart - TEN_MINUTES_MILLIS; } else { alarmTime = currentTime + alarmOffset; } final Intent alarmIntent = new Intent( ACTION_NOTIFY_SESSION, null, this, SessionAlarmService.class); // Setting data to ensure intent's uniqueness for different session start times. alarmIntent.setData( new Uri.Builder() .authority(ScheduleContract.CONTENT_AUTHORITY) .path(String.valueOf(sessionStart)) .build()); alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart); alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd); alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset); final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // Schedule an alarm to be fired to notify user of added sessions are about to begin. am.set(AlarmManager.RTC_WAKEUP, alarmTime, PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT)); } /** * Constructs and triggers system notification for when starred sessions are about to begin. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) { long currentTime = System.currentTimeMillis(); if (sessionStart < currentTime) { return; } // Avoid repeated notifications. if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock( this, ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) { return; } final ContentResolver resolver = getContentResolver(); final Uri starredBlockUri = ScheduleContract.Blocks.buildStarredSessionsUri( ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd)); Cursor cursor = resolver.query(starredBlockUri, new String[]{ ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Sessions.SESSION_TITLE }, null, null, null); int starredCount = 0; ArrayList<String> starredSessionTitles = new ArrayList<String>(); while (cursor.moveToNext()) { starredSessionTitles.add(cursor.getString(1)); starredCount = cursor.getInt(0); } if (starredCount < 1) { return; } // Generates the pending intent which gets fired when the user touches on the notification. Intent sessionIntent = new Intent(Intent.ACTION_VIEW, starredBlockUri); sessionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pi = PendingIntent.getActivity(this, 0, sessionIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Resources res = getResources(); String contentText; int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000; if (minutesLeft < 1) { minutesLeft = 1; } if (starredCount == 1) { contentText = res.getString(R.string.session_notification_text_1, minutesLeft); } else { contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1, minutesLeft, starredCount - 1); } // Construct a notification. Use Jelly Bean (API 16) rich notifications if possible. Notification notification; if (UIUtils.hasJellyBean()) { // Rich notifications Notification.Builder builder = new Notification.Builder(this) .setContentTitle(starredSessionTitles.get(0)) .setContentText(contentText) .setTicker(res.getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount)) .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) .setLights( SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS) .setSmallIcon(R.drawable.ic_stat_notification) .setContentIntent(pi) .setPriority(Notification.PRIORITY_MAX) .setAutoCancel(true); if (minutesLeft > 5) { builder.addAction(R.drawable.ic_alarm_holo_dark, String.format(res.getString(R.string.snooze_x_min), 5), createSnoozeIntent(sessionStart, sessionEnd, 5)); } Notification.InboxStyle richNotification = new Notification.InboxStyle( builder) .setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title, starredCount, minutesLeft, starredCount)); // Adds starred sessions starting at this time block to the notification. for (int i = 0; i < starredCount; i++) { richNotification.addLine(starredSessionTitles.get(i)); } notification = richNotification.build(); } else { // Pre-Jelly Bean non-rich notifications notification = new NotificationCompat.Builder(this) .setContentTitle(starredSessionTitles.get(0)) .setContentText(contentText) .setTicker(res.getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount)) .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) .setLights( SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS) .setSmallIcon(R.drawable.ic_stat_notification) .setContentIntent(pi) .getNotification(); } NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(NOTIFICATION_ID, notification); } private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd, final int snoozeMinutes) { Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, this, SessionAlarmService.class); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, snoozeMinutes * ONE_MINUTE_MILLIS); return PendingIntent.getService(this, 0, scheduleIntent, PendingIntent.FLAG_CANCEL_CURRENT); } private void scheduleAllStarredBlocks() { final Cursor cursor = getContentResolver().query( ScheduleContract.Sessions.CONTENT_STARRED_URI, new String[] { "distinct " + ScheduleContract.Sessions.BLOCK_START, ScheduleContract.Sessions.BLOCK_END }, null, null, null); if (cursor == null) { return; } while (cursor.moveToNext()) { final long sessionStart = cursor.getLong(0); final long sessionEnd = cursor.getLong(1); scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET); } } }
Java
/* * Copyright 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.android.apps.iosched; public class Config { // OAuth 2.0 related config public static final String APP_NAME = "Your-App-Name"; public static final String API_KEY = "API_KEY"; // from the APIs console public static final String CLIENT_ID = "0000000000000.apps.googleusercontent.com"; // from the APIs console // Conference API-specific config // NOTE: the backend used for the Google I/O 2012 Android app is not currently open source, so // you should modify these fields to reflect your own backend. private static final String CONFERENCE_API_KEY = "API_KEY"; private static final String ROOT_EVENT_ID = "googleio2012"; private static final String BASE_URL = "https://google-developers.appspot.com/_ah/api/resources/v0.1"; public static final String GET_ALL_SESSIONS_URL = BASE_URL + "/sessions?parent_event=" + ROOT_EVENT_ID + "&api_key=" + CONFERENCE_API_KEY; public static final String GET_ALL_SPEAKERS_URL = BASE_URL + "/speakers?event_id=" + ROOT_EVENT_ID + "&api_key=" + CONFERENCE_API_KEY; public static final String GET_ALL_ANNOUNCEMENTS_URL = BASE_URL + "/announcements?parent_event=" + ROOT_EVENT_ID + "&api_key=" + CONFERENCE_API_KEY; public static final String EDIT_MY_SCHEDULE_URL = BASE_URL + "/editmyschedule/o/"; // Static file host for the sandbox data public static final String GET_SANDBOX_URL = "https://developers.google.com/events/io/sandbox-data"; // YouTube API config public static final String YOUTUBE_API_KEY = "API_KEY"; // YouTube share URL public static final String YOUTUBE_SHARE_URL_PREFIX = "http://youtu.be/"; // Livestream captions config public static final String PRIMARY_LIVESTREAM_CAPTIONS_URL = "TODO"; public static final String SECONDARY_LIVESTREAM_CAPTIONS_URL = "TODO"; public static final String PRIMARY_LIVESTREAM_TRACK = "android"; public static final String SECONDARY_LIVESTREAM_TRACK = "chrome"; // GCM config public static final String GCM_SERVER_URL = "https://yourapp-gcm.appspot.com"; public static final String GCM_SENDER_ID = "0000000000000"; // project ID from the APIs console }
Java
/* * Copyright 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.android.apps.iosched.appwidget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SessionLivestreamActivity; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import android.accounts.Account; import android.annotation.TargetApi; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.widget.RemoteViews; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The app widget's AppWidgetProvider. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MyScheduleWidgetProvider extends AppWidgetProvider { private static final String TAG = makeLogTag(MyScheduleWidgetProvider.class); public static final String EXTRA_BLOCK_ID = "block_id"; public static final String EXTRA_STARRED_SESSION_ID = "star_session_id"; public static final String EXTRA_BLOCK_TYPE = "block_type"; public static final String EXTRA_STARRED_SESSION = "starred_session"; public static final String EXTRA_NUM_STARRED_SESSIONS = "num_starred_sessions"; public static final String EXTRA_BUTTON = "extra_button"; public static final String CLICK_ACTION = "com.google.android.apps.iosched.appwidget.action.CLICK"; public static final String REFRESH_ACTION = "com.google.android.apps.iosched.appwidget.action.REFRESH"; public static final String EXTRA_PERFORM_SYNC = "com.google.android.apps.iosched.appwidget.extra.PERFORM_SYNC"; private static Handler sWorkerQueue; // TODO: this will get destroyed when the app process is killed. need better observer strategy. private static SessionDataProviderObserver sDataObserver; public MyScheduleWidgetProvider() { // Start the worker thread HandlerThread sWorkerThread = new HandlerThread("MyScheduleWidgetProvider-worker"); sWorkerThread.start(); sWorkerQueue = new Handler(sWorkerThread.getLooper()); } @Override public void onEnabled(Context context) { final ContentResolver r = context.getContentResolver(); if (sDataObserver == null) { final AppWidgetManager mgr = AppWidgetManager.getInstance(context); final ComponentName cn = new ComponentName(context, MyScheduleWidgetProvider.class); sDataObserver = new SessionDataProviderObserver(mgr, cn, sWorkerQueue); r.registerContentObserver(ScheduleContract.Sessions.CONTENT_URI, true, sDataObserver); } } @Override public void onReceive(final Context context, Intent widgetIntent) { final String action = widgetIntent.getAction(); if (REFRESH_ACTION.equals(action)) { final boolean shouldSync = widgetIntent.getBooleanExtra(EXTRA_PERFORM_SYNC, false); sWorkerQueue.removeMessages(0); sWorkerQueue.post(new Runnable() { @Override public void run() { // Trigger sync String chosenAccountName = AccountUtils.getChosenAccountName(context); if (shouldSync && chosenAccountName != null) { Bundle extras = new Bundle(); extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync( new Account(chosenAccountName, GoogleAccountManager.ACCOUNT_TYPE), ScheduleContract.CONTENT_AUTHORITY, extras); } // Update widget final AppWidgetManager mgr = AppWidgetManager.getInstance(context); final ComponentName cn = new ComponentName(context, MyScheduleWidgetProvider.class); mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.widget_schedule_list); } }); } else if (CLICK_ACTION.equals(action)) { String blockId = widgetIntent.getStringExtra(EXTRA_BLOCK_ID); int numStarredSessions = widgetIntent.getIntExtra(EXTRA_NUM_STARRED_SESSIONS, 0); String starredSessionId = widgetIntent.getStringExtra(EXTRA_STARRED_SESSION_ID); String blockType = widgetIntent.getStringExtra(EXTRA_BLOCK_TYPE); boolean starredSession = widgetIntent.getBooleanExtra(EXTRA_STARRED_SESSION, false); boolean extraButton = widgetIntent.getBooleanExtra(EXTRA_BUTTON, false); LOGV(TAG, "blockId:" + blockId); LOGV(TAG, "starredSession:" + starredSession); LOGV(TAG, "blockType:" + blockType); LOGV(TAG, "numStarredSessions:" + numStarredSessions); LOGV(TAG, "extraButton:" + extraButton); if (ParserUtils.BLOCK_TYPE_SESSION.equals(blockType) || ParserUtils.BLOCK_TYPE_CODE_LAB.equals(blockType)) { Uri sessionsUri; if (numStarredSessions == 0) { sessionsUri = ScheduleContract.Blocks.buildSessionsUri( blockId); LOGV(TAG, "sessionsUri:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else if (numStarredSessions == 1) { if (extraButton) { sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); LOGV(TAG, "sessionsUri extraButton:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else { sessionsUri = ScheduleContract.Sessions.buildSessionUri(starredSessionId); LOGV(TAG, "sessionsUri:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } else { if (extraButton) { sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); LOGV(TAG, "sessionsUri extraButton:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else { sessionsUri = ScheduleContract.Blocks.buildStarredSessionsUri(blockId); LOGV(TAG, "sessionsUri:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } } else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(blockType)) { Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(starredSessionId); LOGV(TAG, "sessionUri:" + sessionUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.setClass(context, SessionLivestreamActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } super.onReceive(context, widgetIntent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final boolean isAuthenticated = AccountUtils.isAuthenticated(context); for (int appWidgetId : appWidgetIds) { // Specify the service to provide data for the collection widget. Note that we need to // embed the appWidgetId via the data otherwise it will be ignored. final Intent intent = new Intent(context, MyScheduleWidgetService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); final RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout); compatSetRemoteAdapter(rv, appWidgetId, intent); // Set the empty view to be displayed if the collection is empty. It must be a sibling // view of the collection view. rv.setEmptyView(R.id.widget_schedule_list, android.R.id.empty); rv.setTextViewText(android.R.id.empty, context.getResources().getString(isAuthenticated ? R.string.empty_widget_text : R.string.empty_widget_text_signed_out)); final Intent onClickIntent = new Intent(context, MyScheduleWidgetProvider.class); onClickIntent.setAction(MyScheduleWidgetProvider.CLICK_ACTION); onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); onClickIntent.setData(Uri.parse(onClickIntent.toUri(Intent.URI_INTENT_SCHEME))); final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.widget_schedule_list, onClickPendingIntent); final Intent refreshIntent = new Intent(context, MyScheduleWidgetProvider.class); refreshIntent.setAction(MyScheduleWidgetProvider.REFRESH_ACTION); refreshIntent.putExtra(MyScheduleWidgetProvider.EXTRA_PERFORM_SYNC, true); final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_refresh_button, refreshPendingIntent); final Intent openAppIntent = new Intent(context, HomeActivity.class); final PendingIntent openAppPendingIntent = PendingIntent.getActivity(context, 0, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_logo, openAppPendingIntent); appWidgetManager.updateAppWidget(appWidgetId, rv); } super.onUpdate(context, appWidgetManager, appWidgetIds); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void compatSetRemoteAdapter(RemoteViews rv, int appWidgetId, Intent intent) { if (UIUtils.hasICS()) { rv.setRemoteAdapter(R.id.widget_schedule_list, intent); } else { //noinspection deprecation rv.setRemoteAdapter(appWidgetId, R.id.widget_schedule_list, intent); } } private static class SessionDataProviderObserver extends ContentObserver { private AppWidgetManager mAppWidgetManager; private ComponentName mComponentName; SessionDataProviderObserver(AppWidgetManager appWidgetManager, ComponentName componentName, Handler handler) { super(handler); mAppWidgetManager = appWidgetManager; mComponentName = componentName; } @Override public void onChange(boolean selfChange) { // The data has changed, so notify the widget that the collection view needs to be updated. // In response, the factory's onDataSetChanged() will be called which will requery the // cursor for the new data. mAppWidgetManager.notifyAppWidgetViewDataChanged( mAppWidgetManager.getAppWidgetIds(mComponentName), R.id.widget_schedule_list); } } }
Java
/* * Copyright 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.android.apps.iosched.appwidget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter; import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter.Section; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.provider.BaseColumns; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.SparseBooleanArray; import android.util.SparseIntArray; import android.view.View; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * This is the service that provides the factory to be bound to the collection service. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MyScheduleWidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new WidgetRemoveViewsFactory(this.getApplicationContext()); } /** * This is the factory that will provide data to the collection widget. */ private static class WidgetRemoveViewsFactory implements RemoteViewsService.RemoteViewsFactory { private static final String TAG = makeLogTag(WidgetRemoveViewsFactory.class); private Context mContext; private Cursor mCursor; private SparseIntArray mPMap; private List<SimpleSectionedListAdapter.Section> mSections; private SparseBooleanArray mHeaderPositionMap; public WidgetRemoveViewsFactory(Context context) { mContext = context; } public void onCreate() { // Since we reload the cursor in onDataSetChanged() which gets called immediately after // onCreate(), we do nothing here. } public void onDestroy() { if (mCursor != null) { mCursor.close(); } } public int getCount() { if (mCursor == null || !AccountUtils.isAuthenticated(mContext)) { return 0; } int size = mCursor.getCount() + mSections.size(); if (size < 10) { init(); size = mCursor.getCount() + mSections.size(); } LOGV(TAG, "size returned:" + size); return size; } public RemoteViews getViewAt(int position) { RemoteViews rv; boolean isSectionHeader = mHeaderPositionMap.get(position); int offset = mPMap.get(position); if (isSectionHeader) { rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_header); Section section = mSections.get(offset - 1); rv.setTextViewText(R.id.list_item_schedule_header_textview, section.getTitle()); } else { int cursorPosition = position - offset; mCursor.moveToPosition(cursorPosition); rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_block_widget); final String type = mCursor.getString(BlocksQuery.BLOCK_TYPE); final String blockId = mCursor.getString(BlocksQuery.BLOCK_ID); final String blockTitle = mCursor.getString(BlocksQuery.BLOCK_TITLE); final String blockType = mCursor.getString(BlocksQuery.BLOCK_TYPE); final String blockMeta = mCursor.getString(BlocksQuery.BLOCK_META); final long blockStart = mCursor.getLong(BlocksQuery.BLOCK_START); final Resources res = mContext.getResources(); if (ParserUtils.BLOCK_TYPE_SESSION.equals(type) || ParserUtils.BLOCK_TYPE_CODE_LAB.equals(type)) { final int numStarredSessions = mCursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); final String starredSessionId = mCursor .getString(BlocksQuery.STARRED_SESSION_ID); if (numStarredSessions == 0) { // No sessions starred rv.setTextViewText(R.id.block_title, mContext.getString( R.string.schedule_empty_slot_title_template, TextUtils.isEmpty(blockTitle) ? "" : (" " + blockTitle.toLowerCase()))); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1_positive)); rv.setTextViewText(R.id.block_subtitle, mContext.getString( R.string.schedule_empty_slot_subtitle)); rv.setViewVisibility(R.id.extra_button, View.GONE); // TODO: use TaskStackBuilder final Intent fillInIntent = new Intent(); final Bundle extras = new Bundle(); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, numStarredSessions); extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, false); fillInIntent.putExtras(extras); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent); } else if (numStarredSessions == 1) { // exactly 1 session starred final String starredSessionTitle = mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE); String starredSessionRoomName = mCursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (starredSessionRoomName == null) { // TODO: remove this WAR for API not returning rooms for code labs starredSessionRoomName = mContext.getString( starredSessionTitle.contains("Code Lab") ? R.string.codelab_room : R.string.unknown_room); } rv.setTextViewText(R.id.block_title, starredSessionTitle); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1)); rv.setTextViewText(R.id.block_subtitle, starredSessionRoomName); rv.setViewVisibility(R.id.extra_button, View.VISIBLE); // TODO: use TaskStackBuilder final Intent fillInIntent = new Intent(); final Bundle extras = new Bundle(); extras.putString(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION_ID, starredSessionId); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, numStarredSessions); extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true); fillInIntent.putExtras(extras); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent); final Intent fillInIntent2 = new Intent(); final Bundle extras2 = new Bundle(); extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId); extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true); extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_BUTTON, true); extras2.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, numStarredSessions); fillInIntent2.putExtras(extras2); rv.setOnClickFillInIntent(R.id.extra_button, fillInIntent2); } else { // 2 or more sessions starred rv.setTextViewText(R.id.block_title, mContext.getString(R.string.schedule_conflict_title, numStarredSessions)); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1)); rv.setTextViewText(R.id.block_subtitle, mContext.getString(R.string.schedule_conflict_subtitle)); rv.setViewVisibility(R.id.extra_button, View.VISIBLE); // TODO: use TaskStackBuilder final Intent fillInIntent = new Intent(); final Bundle extras = new Bundle(); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true); extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, numStarredSessions); fillInIntent.putExtras(extras); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent); final Intent fillInIntent2 = new Intent(); final Bundle extras2 = new Bundle(); extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId); extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true); extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_BUTTON, true); extras2.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, numStarredSessions); fillInIntent2.putExtras(extras2); rv.setOnClickFillInIntent(R.id.extra_button, fillInIntent2); } rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_2)); } else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(type)) { final String starredSessionId = mCursor .getString(BlocksQuery.STARRED_SESSION_ID); final String starredSessionTitle = mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE); rv.setTextViewText(R.id.block_title, starredSessionTitle); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1)); rv.setTextViewText(R.id.block_subtitle, res.getString(R.string.keynote_room)); rv.setViewVisibility(R.id.extra_button, View.GONE); // TODO: use TaskStackBuilder final Intent fillInIntent = new Intent(); final Bundle extras = new Bundle(); extras.putString(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION_ID, starredSessionId); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); fillInIntent.putExtras(extras); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent); } else { rv.setTextViewText(R.id.block_title, blockTitle); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_disabled)); rv.setTextViewText(R.id.block_subtitle, blockMeta); rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_disabled)); rv.setViewVisibility(R.id.extra_button, View.GONE); // TODO: use TaskStackBuilder final Intent fillInIntent = new Intent(); final Bundle extras = new Bundle(); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, -1); fillInIntent.putExtras(extras); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent); } rv.setTextViewText(R.id.block_time, DateUtils.formatDateTime(mContext, blockStart, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR)); } return rv; } public RemoteViews getLoadingView() { return null; } public int getViewTypeCount() { return 2; } public long getItemId(int position) { return position; } public boolean hasStableIds() { return true; } public void onDataSetChanged() { init(); } private void init() { if (mCursor != null) { mCursor.close(); } mCursor = mContext.getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, ScheduleContract.Blocks.BLOCK_END + " >= ?", new String[]{ Long.toString(UIUtils.getCurrentTime(mContext)) }, ScheduleContract.Blocks.DEFAULT_SORT); mSections = new ArrayList<SimpleSectionedListAdapter.Section>(); mCursor.moveToFirst(); long previousTime = -1; long time; mPMap = new SparseIntArray(); mHeaderPositionMap = new SparseBooleanArray(); int offset = 0; int globalPosition = 0; while (!mCursor.isAfterLast()) { time = mCursor.getLong(BlocksQuery.BLOCK_START); if (!UIUtils.isSameDay(previousTime, time)) { mSections.add(new SimpleSectionedListAdapter.Section(mCursor.getPosition(), DateUtils.formatDateTime(mContext, time, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY))); ++offset; mHeaderPositionMap.put(globalPosition, true); mPMap.put(globalPosition, offset); ++globalPosition; } mHeaderPositionMap.put(globalPosition, false); mPMap.put(globalPosition, offset); ++globalPosition; previousTime = time; mCursor.moveToNext(); } LOGV(TAG, "Leaving init()"); } } public interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.BLOCK_META, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_ID, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int BLOCK_META = 6; int NUM_STARRED_SESSIONS = 7; int STARRED_SESSION_ID = 8; int STARRED_SESSION_TITLE = 9; int STARRED_SESSION_ROOM_NAME = 10; } }
Java
/* * Copyright 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.android.apps.iosched.provider; import com.google.android.apps.iosched.provider.ScheduleContract.Announcements; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables; import com.google.android.apps.iosched.util.SelectionBuilder; import android.app.Activity; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.BaseColumns; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Provider that stores {@link ScheduleContract} data. Data is usually inserted * by {@link com.google.android.apps.iosched.sync.SyncHelper}, and queried by various * {@link Activity} instances. */ public class ScheduleProvider extends ContentProvider { private static final String TAG = makeLogTag(ScheduleProvider.class); private ScheduleDatabase mOpenHelper; private static final UriMatcher sUriMatcher = buildUriMatcher(); private static final int BLOCKS = 100; private static final int BLOCKS_BETWEEN = 101; private static final int BLOCKS_ID = 102; private static final int BLOCKS_ID_SESSIONS = 103; private static final int BLOCKS_ID_SESSIONS_STARRED = 104; private static final int TRACKS = 200; private static final int TRACKS_ID = 201; private static final int TRACKS_ID_SESSIONS = 202; private static final int TRACKS_ID_VENDORS = 203; private static final int ROOMS = 300; private static final int ROOMS_ID = 301; private static final int ROOMS_ID_SESSIONS = 302; private static final int SESSIONS = 400; private static final int SESSIONS_STARRED = 401; private static final int SESSIONS_WITH_TRACK = 402; private static final int SESSIONS_SEARCH = 403; private static final int SESSIONS_AT = 404; private static final int SESSIONS_ID = 405; private static final int SESSIONS_ID_SPEAKERS = 406; private static final int SESSIONS_ID_TRACKS = 407; private static final int SESSIONS_ID_WITH_TRACK = 408; private static final int SPEAKERS = 500; private static final int SPEAKERS_ID = 501; private static final int SPEAKERS_ID_SESSIONS = 502; private static final int VENDORS = 600; private static final int VENDORS_STARRED = 601; private static final int VENDORS_SEARCH = 603; private static final int VENDORS_ID = 604; private static final int ANNOUNCEMENTS = 700; private static final int ANNOUNCEMENTS_ID = 701; private static final int SEARCH_SUGGEST = 800; private static final String MIME_XML = "text/xml"; /** * Build and return a {@link UriMatcher} that catches all {@link Uri} * variations supported by this {@link ContentProvider}. */ private static UriMatcher buildUriMatcher() { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = ScheduleContract.CONTENT_AUTHORITY; matcher.addURI(authority, "blocks", BLOCKS); matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN); matcher.addURI(authority, "blocks/*", BLOCKS_ID); matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS); matcher.addURI(authority, "blocks/*/sessions/starred", BLOCKS_ID_SESSIONS_STARRED); matcher.addURI(authority, "tracks", TRACKS); matcher.addURI(authority, "tracks/*", TRACKS_ID); matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS); matcher.addURI(authority, "tracks/*/vendors", TRACKS_ID_VENDORS); matcher.addURI(authority, "rooms", ROOMS); matcher.addURI(authority, "rooms/*", ROOMS_ID); matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS); matcher.addURI(authority, "sessions", SESSIONS); matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED); matcher.addURI(authority, "sessions/with_track", SESSIONS_WITH_TRACK); matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH); matcher.addURI(authority, "sessions/at/*", SESSIONS_AT); matcher.addURI(authority, "sessions/*", SESSIONS_ID); matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS); matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS); matcher.addURI(authority, "sessions/*/with_track", SESSIONS_ID_WITH_TRACK); matcher.addURI(authority, "speakers", SPEAKERS); matcher.addURI(authority, "speakers/*", SPEAKERS_ID); matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS); matcher.addURI(authority, "vendors", VENDORS); matcher.addURI(authority, "vendors/starred", VENDORS_STARRED); matcher.addURI(authority, "vendors/search/*", VENDORS_SEARCH); matcher.addURI(authority, "vendors/*", VENDORS_ID); matcher.addURI(authority, "announcements", ANNOUNCEMENTS); matcher.addURI(authority, "announcements/*", ANNOUNCEMENTS_ID); matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST); return matcher; } @Override public boolean onCreate() { mOpenHelper = new ScheduleDatabase(getContext()); return true; } private void deleteDatabase() { // TODO: wait for content provider operations to finish, then tear down mOpenHelper.close(); Context context = getContext(); ScheduleDatabase.deleteDatabase(context); mOpenHelper = new ScheduleDatabase(getContext()); } /** {@inheritDoc} */ @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: return Blocks.CONTENT_TYPE; case BLOCKS_BETWEEN: return Blocks.CONTENT_TYPE; case BLOCKS_ID: return Blocks.CONTENT_ITEM_TYPE; case BLOCKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case BLOCKS_ID_SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case TRACKS: return Tracks.CONTENT_TYPE; case TRACKS_ID: return Tracks.CONTENT_ITEM_TYPE; case TRACKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS_ID_VENDORS: return Vendors.CONTENT_TYPE; case ROOMS: return Rooms.CONTENT_TYPE; case ROOMS_ID: return Rooms.CONTENT_ITEM_TYPE; case ROOMS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case SESSIONS_WITH_TRACK: return Sessions.CONTENT_TYPE; case SESSIONS_SEARCH: return Sessions.CONTENT_TYPE; case SESSIONS_AT: return Sessions.CONTENT_TYPE; case SESSIONS_ID: return Sessions.CONTENT_ITEM_TYPE; case SESSIONS_ID_SPEAKERS: return Speakers.CONTENT_TYPE; case SESSIONS_ID_TRACKS: return Tracks.CONTENT_TYPE; case SESSIONS_ID_WITH_TRACK: return Sessions.CONTENT_TYPE; case SPEAKERS: return Speakers.CONTENT_TYPE; case SPEAKERS_ID: return Speakers.CONTENT_ITEM_TYPE; case SPEAKERS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case VENDORS: return Vendors.CONTENT_TYPE; case VENDORS_STARRED: return Vendors.CONTENT_TYPE; case VENDORS_SEARCH: return Vendors.CONTENT_TYPE; case VENDORS_ID: return Vendors.CONTENT_ITEM_TYPE; case ANNOUNCEMENTS: return Announcements.CONTENT_TYPE; case ANNOUNCEMENTS_ID: return Announcements.CONTENT_ITEM_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** {@inheritDoc} */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { LOGV(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")"); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { default: { // Most cases are handled with simple SelectionBuilder final SelectionBuilder builder = buildExpandedSelection(uri, match); return builder.where(selection, selectionArgs).query(db, projection, sortOrder); } case SEARCH_SUGGEST: { final SelectionBuilder builder = new SelectionBuilder(); // Adjust incoming query to become SQL text match selectionArgs[0] = selectionArgs[0] + "%"; builder.table(Tables.SEARCH_SUGGEST); builder.where(selection, selectionArgs); builder.map(SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_TEXT_1); projection = new String[] { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_QUERY }; final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT); return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit); } } } /** {@inheritDoc} */ @Override public Uri insert(Uri uri, ContentValues values) { LOGV(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri); switch (match) { case BLOCKS: { db.insertOrThrow(Tables.BLOCKS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID)); } case TRACKS: { db.insertOrThrow(Tables.TRACKS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID)); } case ROOMS: { db.insertOrThrow(Tables.ROOMS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID)); } case SESSIONS: { db.insertOrThrow(Tables.SESSIONS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID)); } case SESSIONS_ID_SPEAKERS: { db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID)); } case SESSIONS_ID_TRACKS: { db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID)); } case SPEAKERS: { db.insertOrThrow(Tables.SPEAKERS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID)); } case VENDORS: { db.insertOrThrow(Tables.VENDORS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Vendors.buildVendorUri(values.getAsString(Vendors.VENDOR_ID)); } case ANNOUNCEMENTS: { db.insertOrThrow(Tables.ANNOUNCEMENTS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Announcements.buildAnnouncementUri(values .getAsString(Announcements.ANNOUNCEMENT_ID)); } case SEARCH_SUGGEST: { db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return SearchSuggest.CONTENT_URI; } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** {@inheritDoc} */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { LOGV(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).update(db, values); boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return retVal; } /** {@inheritDoc} */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { LOGV(TAG, "delete(uri=" + uri + ")"); if (uri == ScheduleContract.BASE_CONTENT_URI) { // Handle whole database deletes (e.g. when signing out) deleteDatabase(); getContext().getContentResolver().notifyChange(uri, null, false); return 1; } final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).delete(db); getContext().getContentResolver().notifyChange(uri, null, !ScheduleContract.hasCallerIsSyncAdapterParameter(uri)); return retVal; } /** * Apply the given set of {@link ContentProviderOperation}, executing inside * a {@link SQLiteDatabase} transaction. All changes will be rolled back if * any single one fails. */ @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.beginTransaction(); try { final int numOperations = operations.size(); final ContentProviderResult[] results = new ContentProviderResult[numOperations]; for (int i = 0; i < numOperations; i++) { results[i] = operations.get(i).apply(this, results, i); } db.setTransactionSuccessful(); return results; } finally { db.endTransaction(); } } /** * Build a simple {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually enough to support {@link #insert}, * {@link #update}, and {@link #delete} operations. */ private SelectionBuilder buildSimpleSelection(Uri uri) { final SelectionBuilder builder = new SelectionBuilder(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .where(Blocks.BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case ANNOUNCEMENTS: { return builder.table(Tables.ANNOUNCEMENTS); } case ANNOUNCEMENTS_ID: { final String announcementId = Announcements.getAnnouncementId(uri); return builder.table(Tables.ANNOUNCEMENTS) .where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId); } case SEARCH_SUGGEST: { return builder.table(Tables.SEARCH_SUGGEST); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** * Build an advanced {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually only used by {@link #query}, since it * performs table joins useful for {@link Cursor} data. */ private SelectionBuilder buildExpandedSelection(Uri uri, int match) { final SelectionBuilder builder = new SelectionBuilder(); switch (match) { case BLOCKS: { return builder .table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .map(Blocks.STARRED_SESSION_ID, Subquery.BLOCK_STARRED_SESSION_ID) .map(Blocks.STARRED_SESSION_TITLE, Subquery.BLOCK_STARRED_SESSION_TITLE) .map(Blocks.STARRED_SESSION_HASHTAGS, Subquery.BLOCK_STARRED_SESSION_HASHTAGS) .map(Blocks.STARRED_SESSION_URL, Subquery.BLOCK_STARRED_SESSION_URL) .map(Blocks.STARRED_SESSION_LIVESTREAM_URL, Subquery.BLOCK_STARRED_SESSION_LIVESTREAM_URL) .map(Blocks.STARRED_SESSION_ROOM_NAME, Subquery.BLOCK_STARRED_SESSION_ROOM_NAME) .map(Blocks.STARRED_SESSION_ROOM_ID, Subquery.BLOCK_STARRED_SESSION_ROOM_ID); } case BLOCKS_BETWEEN: { final List<String> segments = uri.getPathSegments(); final String startTime = segments.get(2); final String endTime = segments.get(3); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .where(Blocks.BLOCK_START + ">=?", startTime) .where(Blocks.BLOCK_START + "<=?", endTime); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .where(Blocks.BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS_STARRED: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId) .where(Qualified.SESSIONS_STARRED + "=1"); } case TRACKS: { return builder.table(Tables.TRACKS) .map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT) .map(Tracks.VENDORS_COUNT, Subquery.TRACK_VENDORS_COUNT); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case TRACKS_ID_SESSIONS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId); } case TRACKS_ID_VENDORS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Qualified.VENDORS_TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case ROOMS_ID_SESSIONS: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS); } case SESSIONS_STARRED: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.SESSION_STARRED + "=1"); } case SESSIONS_WITH_TRACK: { return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_NAME, Tables.TRACKS) .mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS); } case SESSIONS_ID_WITH_TRACK: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_NAME, Tables.TRACKS) .mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_SEARCH: { final String query = Sessions.getSearchQuery(uri); return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS) .map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(SessionsSearchColumns.BODY + " MATCH ?", query); } case SESSIONS_AT: { final List<String> segments = uri.getPathSegments(); final String time = segments.get(2); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.BLOCK_START + "<=?", time) .where(Sessions.BLOCK_END + ">=?", time); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS) .mapToTable(Speakers._ID, Tables.SPEAKERS) .mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS) .where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS) .mapToTable(Tracks._ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case SPEAKERS_ID_SESSIONS: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS); } case VENDORS_STARRED: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_STARRED + "=1"); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case ANNOUNCEMENTS: { return builder.table(Tables.ANNOUNCEMENTS); } case ANNOUNCEMENTS_ID: { final String announcementId = Announcements.getAnnouncementId(uri); return builder.table(Tables.ANNOUNCEMENTS) .where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { final int match = sUriMatcher.match(uri); switch (match) { default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } private interface Subquery { String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String BLOCK_NUM_STARRED_SESSIONS = "(SELECT COUNT(1) FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1)"; String BLOCK_STARRED_SESSION_ID = "(SELECT " + Qualified.SESSIONS_SESSION_ID + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_TITLE = "(SELECT " + Qualified.SESSIONS_TITLE + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_HASHTAGS = "(SELECT " + Qualified.SESSIONS_HASHTAGS + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_URL = "(SELECT " + Qualified.SESSIONS_URL + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_LIVESTREAM_URL = "(SELECT " + Qualified.SESSIONS_LIVESTREAM_URL + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_ROOM_NAME = "(SELECT " + Qualified.ROOMS_ROOM_NAME + " FROM " + Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_ROOM_ID = "(SELECT " + Qualified.ROOMS_ROOM_ID + " FROM " + Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID + ") FROM " + Tables.SESSIONS_TRACKS + " WHERE " + Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String TRACK_VENDORS_COUNT = "(SELECT COUNT(" + Qualified.VENDORS_VENDOR_ID + ") FROM " + Tables.VENDORS + " WHERE " + Qualified.VENDORS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')"; } /** * {@link ScheduleContract} fields that are fully qualified with a specific * parent {@link Tables}. Used when needed to work around SQL ambiguity. */ private interface Qualified { String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID; String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID; String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.TRACK_ID; String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SESSION_ID; String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SPEAKER_ID; String VENDORS_VENDOR_ID = Tables.VENDORS + "." + Vendors.VENDOR_ID; String VENDORS_TRACK_ID = Tables.VENDORS + "." + Vendors.TRACK_ID; String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED; String SESSIONS_TITLE = Tables.SESSIONS + "." + Sessions.SESSION_TITLE; String SESSIONS_HASHTAGS = Tables.SESSIONS + "." + Sessions.SESSION_HASHTAGS; String SESSIONS_URL = Tables.SESSIONS + "." + Sessions.SESSION_URL; String SESSIONS_LIVESTREAM_URL = Tables.SESSIONS + "." + Sessions.SESSION_LIVESTREAM_URL; String ROOMS_ROOM_NAME = Tables.ROOMS + "." + Rooms.ROOM_NAME; String ROOMS_ROOM_ID = Tables.ROOMS + "." + Rooms.ROOM_ID; String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID; String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID; } }
Java
/* * Copyright 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.android.apps.iosched.provider; import com.google.android.apps.iosched.provider.ScheduleContract.AnnouncementsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleContract.VendorsColumns; import android.app.SearchManager; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Helper for managing {@link SQLiteDatabase} that stores data for * {@link ScheduleProvider}. */ public class ScheduleDatabase extends SQLiteOpenHelper { private static final String TAG = makeLogTag(ScheduleDatabase.class); private static final String DATABASE_NAME = "schedule.db"; // NOTE: carefully update onUpgrade() when bumping database versions to make // sure user data is saved. private static final int VER_LAUNCH = 25; private static final int VER_SESSION_TYPE = 26; private static final int DATABASE_VERSION = VER_SESSION_TYPE; interface Tables { String BLOCKS = "blocks"; String TRACKS = "tracks"; String ROOMS = "rooms"; String SESSIONS = "sessions"; String SPEAKERS = "speakers"; String SESSIONS_SPEAKERS = "sessions_speakers"; String SESSIONS_TRACKS = "sessions_tracks"; String VENDORS = "vendors"; String ANNOUNCEMENTS = "announcements"; String SESSIONS_SEARCH = "sessions_search"; String SEARCH_SUGGEST = "search_suggest"; String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_JOIN_ROOMS = "sessions " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String VENDORS_JOIN_TRACKS = "vendors " + "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id"; String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers " + "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id"; String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers " + "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks " + "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id"; String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks " + "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search " + "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_JOIN_TRACKS_JOIN_BLOCKS = "sessions " + "LEFT OUTER JOIN sessions_tracks ON " + "sessions_tracks.session_id=sessions.session_id " + "LEFT OUTER JOIN tracks ON tracks.track_id=sessions_tracks.track_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id"; String BLOCKS_JOIN_SESSIONS = "blocks " + "LEFT OUTER JOIN sessions ON blocks.block_id=sessions.block_id"; } private interface Triggers { String SESSIONS_SEARCH_INSERT = "sessions_search_insert"; String SESSIONS_SEARCH_DELETE = "sessions_search_delete"; String SESSIONS_SEARCH_UPDATE = "sessions_search_update"; // Deletes from session_tracks when corresponding sessions are deleted. String SESSIONS_TRACKS_DELETE = "sessions_tracks_delete"; } public interface SessionsSpeakers { String SESSION_ID = "session_id"; String SPEAKER_ID = "speaker_id"; } public interface SessionsTracks { String SESSION_ID = "session_id"; String TRACK_ID = "track_id"; } interface SessionsSearchColumns { String SESSION_ID = "session_id"; String BODY = "body"; } /** Fully-qualified field names. */ private interface Qualified { String SESSIONS_SEARCH_SESSION_ID = Tables.SESSIONS_SEARCH + "." + SessionsSearchColumns.SESSION_ID; String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID + "," + SessionsSearchColumns.BODY + ")"; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; } /** {@code REFERENCES} clauses. */ private interface References { String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")"; String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")"; String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")"; String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")"; String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")"; String VENDOR_ID = "REFERENCES " + Tables.VENDORS + "(" + Vendors.VENDOR_ID + ")"; } private interface Subquery { /** * Subquery used to build the {@link SessionsSearchColumns#BODY} string * used for indexing {@link Sessions} content. */ String SESSIONS_BODY = "(new." + Sessions.SESSION_TITLE + "||'; '||new." + Sessions.SESSION_ABSTRACT + "||'; '||" + "coalesce(new." + Sessions.SESSION_TAGS + ", '')" + ")"; } public ScheduleDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Tables.BLOCKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + BlocksColumns.BLOCK_ID + " TEXT NOT NULL," + BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL," + BlocksColumns.BLOCK_START + " INTEGER NOT NULL," + BlocksColumns.BLOCK_END + " INTEGER NOT NULL," + BlocksColumns.BLOCK_TYPE + " TEXT," + BlocksColumns.BLOCK_META + " TEXT," + "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TracksColumns.TRACK_ID + " TEXT NOT NULL," + TracksColumns.TRACK_NAME + " TEXT," + TracksColumns.TRACK_COLOR + " INTEGER," + TracksColumns.TRACK_ABSTRACT + " TEXT," + "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.ROOMS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + RoomsColumns.ROOM_ID + " TEXT NOT NULL," + RoomsColumns.ROOM_NAME + " TEXT," + RoomsColumns.ROOM_FLOOR + " TEXT," + "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SessionsColumns.SESSION_ID + " TEXT NOT NULL," + Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + "," + Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + "," + SessionsColumns.SESSION_TYPE + " TEXT," + SessionsColumns.SESSION_LEVEL + " TEXT," + SessionsColumns.SESSION_TITLE + " TEXT," + SessionsColumns.SESSION_ABSTRACT + " TEXT," + SessionsColumns.SESSION_REQUIREMENTS + " TEXT," + SessionsColumns.SESSION_TAGS + " TEXT," + SessionsColumns.SESSION_HASHTAGS + " TEXT," + SessionsColumns.SESSION_URL + " TEXT," + SessionsColumns.SESSION_YOUTUBE_URL + " TEXT," + SessionsColumns.SESSION_PDF_URL + " TEXT," + SessionsColumns.SESSION_NOTES_URL + " TEXT," + SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0," + SessionsColumns.SESSION_CAL_EVENT_ID + " INTEGER," + SessionsColumns.SESSION_LIVESTREAM_URL + " TEXT," + "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL," + SpeakersColumns.SPEAKER_NAME + " TEXT," + SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT," + SpeakersColumns.SPEAKER_COMPANY + " TEXT," + SpeakersColumns.SPEAKER_ABSTRACT + " TEXT," + SpeakersColumns.SPEAKER_URL + " TEXT," + "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + "," + "UNIQUE (" + SessionsSpeakers.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID + ")"); db.execSQL("CREATE TABLE " + Tables.VENDORS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + VendorsColumns.VENDOR_ID + " TEXT NOT NULL," + Vendors.TRACK_ID + " TEXT " + References.TRACK_ID + "," + VendorsColumns.VENDOR_NAME + " TEXT," + VendorsColumns.VENDOR_LOCATION + " TEXT," + VendorsColumns.VENDOR_DESC + " TEXT," + VendorsColumns.VENDOR_URL + " TEXT," + VendorsColumns.VENDOR_PRODUCT_DESC + " TEXT," + VendorsColumns.VENDOR_LOGO_URL + " TEXT," + VendorsColumns.VENDOR_STARRED + " INTEGER," + "UNIQUE (" + VendorsColumns.VENDOR_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.ANNOUNCEMENTS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + AnnouncementsColumns.ANNOUNCEMENT_ID + " TEXT," + AnnouncementsColumns.ANNOUNCEMENT_TITLE + " TEXT NOT NULL," + AnnouncementsColumns.ANNOUNCEMENT_SUMMARY + " TEXT," + AnnouncementsColumns.ANNOUNCEMENT_TRACKS + " TEXT," + AnnouncementsColumns.ANNOUNCEMENT_URL + " TEXT," + AnnouncementsColumns.ANNOUNCEMENT_DATE + " INTEGER NOT NULL)"); createSessionsSearch(db); createSessionsDeleteTriggers(db); db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)"); } /** * Create triggers that automatically build {@link Tables#SESSIONS_SEARCH} * as values are changed in {@link Tables#SESSIONS}. */ private static void createSessionsSearch(SQLiteDatabase db) { // Using the "porter" tokenizer for simple stemming, so that // "frustration" matches "frustrated." db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSearchColumns.BODY + " TEXT NOT NULL," + SessionsSearchColumns.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE," + "tokenize=porter)"); // TODO: handle null fields in body, which cause trigger to fail // TODO: implement update trigger, not currently exercised db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_INSERT + " AFTER INSERT ON " + Tables.SESSIONS + " BEGIN INSERT INTO " + Qualified.SESSIONS_SEARCH + " " + " VALUES(new." + Sessions.SESSION_ID + ", " + Subquery.SESSIONS_BODY + ");" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_DELETE + " AFTER DELETE ON " + Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SEARCH + " " + " WHERE " + Qualified.SESSIONS_SEARCH_SESSION_ID + "=old." + Sessions.SESSION_ID + ";" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_UPDATE + " AFTER UPDATE ON " + Tables.SESSIONS + " BEGIN UPDATE sessions_search SET " + SessionsSearchColumns.BODY + " = " + Subquery.SESSIONS_BODY + " WHERE session_id = old.session_id" + "; END;"); } private void createSessionsDeleteTriggers(SQLiteDatabase db) { db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_TRACKS_DELETE + " AFTER DELETE ON " + Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_TRACKS + " " + " WHERE " + Qualified.SESSIONS_TRACKS_SESSION_ID + "=old." + Sessions.SESSION_ID + ";" + " END;"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { LOGD(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion); // NOTE: This switch statement is designed to handle cascading database // updates, starting at the current version and falling through to all // future upgrade cases. Only use "break;" when you want to drop and // recreate the entire database. int version = oldVersion; switch (version) { case VER_LAUNCH: // VER_SESSION_TYPE added column for session feedback URL. db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_TYPE + " TEXT"); version = VER_SESSION_TYPE; } LOGD(TAG, "after upgrade logic, at version " + version); if (version != DATABASE_VERSION) { LOGW(TAG, "Destroying old data during upgrade"); db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS); db.execSQL("DROP TABLE IF EXISTS " + Tables.ANNOUNCEMENTS); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_INSERT); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_DELETE); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_UPDATE); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_TRACKS_DELETE); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH); db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST); onCreate(db); } } public static void deleteDatabase(Context context) { context.deleteDatabase(DATABASE_NAME); } }
Java
/* * Copyright 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.android.apps.iosched.provider; import com.google.android.apps.iosched.util.ParserUtils; import android.app.SearchManager; import android.graphics.Color; import android.net.Uri; import android.provider.BaseColumns; import android.provider.ContactsContract; import android.text.TextUtils; import android.text.format.DateUtils; import java.util.List; /** * Contract class for interacting with {@link ScheduleProvider}. Unless * otherwise noted, all time-based fields are milliseconds since epoch and can * be compared against {@link System#currentTimeMillis()}. * <p> * The backing {@link android.content.ContentProvider} assumes that {@link Uri} * are generated using stronger {@link String} identifiers, instead of * {@code int} {@link BaseColumns#_ID} values, which are prone to shuffle during * sync. */ public class ScheduleContract { /** * Special value for {@link SyncColumns#UPDATED} indicating that an entry * has never been updated, or doesn't exist yet. */ public static final long UPDATED_NEVER = -2; /** * Special value for {@link SyncColumns#UPDATED} indicating that the last * update time is unknown, usually when inserted from a local file source. */ public static final long UPDATED_UNKNOWN = -1; public interface SyncColumns { /** Last time this entry was updated or synchronized. */ String UPDATED = "updated"; } interface BlocksColumns { /** Unique string identifying this block of time. */ String BLOCK_ID = "block_id"; /** Title describing this block of time. */ String BLOCK_TITLE = "block_title"; /** Time when this block starts. */ String BLOCK_START = "block_start"; /** Time when this block ends. */ String BLOCK_END = "block_end"; /** Type describing this block. */ String BLOCK_TYPE = "block_type"; /** Extra string metadata for the block. */ String BLOCK_META = "block_meta"; } interface TracksColumns { /** Unique string identifying this track. */ String TRACK_ID = "track_id"; /** Name describing this track. */ String TRACK_NAME = "track_name"; /** Color used to identify this track, in {@link Color#argb} format. */ String TRACK_COLOR = "track_color"; /** Body of text explaining this track in detail. */ String TRACK_ABSTRACT = "track_abstract"; } interface RoomsColumns { /** Unique string identifying this room. */ String ROOM_ID = "room_id"; /** Name describing this room. */ String ROOM_NAME = "room_name"; /** Building floor this room exists on. */ String ROOM_FLOOR = "room_floor"; } interface SessionsColumns { /** Unique string identifying this session. */ String SESSION_ID = "session_id"; /** The type of session (session, keynote, codelab, etc). */ String SESSION_TYPE = "session_type"; /** Difficulty level of the session. */ String SESSION_LEVEL = "session_level"; /** Title describing this track. */ String SESSION_TITLE = "session_title"; /** Body of text explaining this session in detail. */ String SESSION_ABSTRACT = "session_abstract"; /** Requirements that attendees should meet. */ String SESSION_REQUIREMENTS = "session_requirements"; /** Keywords/tags for this session. */ String SESSION_TAGS = "session_keywords"; /** Hashtag for this session. */ String SESSION_HASHTAGS = "session_hashtag"; /** Full URL to session online. */ String SESSION_URL = "session_url"; /** Full URL to YouTube. */ String SESSION_YOUTUBE_URL = "session_youtube_url"; /** Full URL to PDF. */ String SESSION_PDF_URL = "session_pdf_url"; /** Full URL to official session notes. */ String SESSION_NOTES_URL = "session_notes_url"; /** User-specific flag indicating starred status. */ String SESSION_STARRED = "session_starred"; /** Key for session Calendar event. (Used in ICS or above) */ String SESSION_CAL_EVENT_ID = "session_cal_event_id"; /** The YouTube live stream URL. */ String SESSION_LIVESTREAM_URL = "session_livestream_url"; } interface SpeakersColumns { /** Unique string identifying this speaker. */ String SPEAKER_ID = "speaker_id"; /** Name of this speaker. */ String SPEAKER_NAME = "speaker_name"; /** Profile photo of this speaker. */ String SPEAKER_IMAGE_URL = "speaker_image_url"; /** Company this speaker works for. */ String SPEAKER_COMPANY = "speaker_company"; /** Body of text describing this speaker in detail. */ String SPEAKER_ABSTRACT = "speaker_abstract"; /** Full URL to the speaker's profile. */ String SPEAKER_URL = "speaker_url"; } interface VendorsColumns { /** Unique string identifying this vendor. */ String VENDOR_ID = "vendor_id"; /** Name of this vendor. */ String VENDOR_NAME = "vendor_name"; /** Location or city this vendor is based in. */ String VENDOR_LOCATION = "vendor_location"; /** Body of text describing this vendor. */ String VENDOR_DESC = "vendor_desc"; /** Link to vendor online. */ String VENDOR_URL = "vendor_url"; /** Body of text describing the product of this vendor. */ String VENDOR_PRODUCT_DESC = "vendor_product_desc"; /** Link to vendor logo. */ String VENDOR_LOGO_URL = "vendor_logo_url"; /** User-specific flag indicating starred status. */ String VENDOR_STARRED = "vendor_starred"; } interface AnnouncementsColumns { /** Unique string identifying this announcment. */ String ANNOUNCEMENT_ID = "announcement_id"; /** Title of the announcement. */ String ANNOUNCEMENT_TITLE = "announcement_title"; /** Summary of the announcement. */ String ANNOUNCEMENT_SUMMARY = "announcement_summary"; /** Track announcement belongs to. */ String ANNOUNCEMENT_TRACKS = "announcement_tracks"; /** Full URL for the announcement. */ String ANNOUNCEMENT_URL = "announcement_url"; /** Date of the announcement. */ String ANNOUNCEMENT_DATE = "announcement_date"; } public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); private static final String PATH_BLOCKS = "blocks"; private static final String PATH_AT = "at"; private static final String PATH_BETWEEN = "between"; private static final String PATH_TRACKS = "tracks"; private static final String PATH_ROOMS = "rooms"; private static final String PATH_SESSIONS = "sessions"; private static final String PATH_WITH_TRACK = "with_track"; private static final String PATH_STARRED = "starred"; private static final String PATH_SPEAKERS = "speakers"; private static final String PATH_VENDORS = "vendors"; private static final String PATH_ANNOUNCEMENTS = "announcements"; private static final String PATH_SEARCH = "search"; private static final String PATH_SEARCH_SUGGEST = "search_suggest_query"; /** * Blocks are generic timeslots that {@link Sessions} and other related * events fall into. */ public static class Blocks implements BlocksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.block"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.block"; /** Count of {@link Sessions} inside given block. */ public static final String SESSIONS_COUNT = "sessions_count"; /** * Flag indicating the number of sessions inside this block that have * {@link Sessions#SESSION_STARRED} set. */ public static final String NUM_STARRED_SESSIONS = "num_starred_sessions"; /** * The {@link Sessions#SESSION_ID} of the first starred session in this * block. */ public static final String STARRED_SESSION_ID = "starred_session_id"; /** * The {@link Sessions#SESSION_TITLE} of the first starred session in * this block. */ public static final String STARRED_SESSION_TITLE = "starred_session_title"; /** * The {@link Sessions#SESSION_LIVESTREAM_URL} of the first starred * session in this block. */ public static final String STARRED_SESSION_LIVESTREAM_URL = "starred_session_livestream_url"; /** * The {@link Rooms#ROOM_NAME} of the first starred session in this * block. */ public static final String STARRED_SESSION_ROOM_NAME = "starred_session_room_name"; /** * The {@link Rooms#ROOM_ID} of the first starred session in this block. */ public static final String STARRED_SESSION_ROOM_ID = "starred_session_room_id"; /** * The {@link Sessions#SESSION_HASHTAGS} of the first starred session in * this block. */ public static final String STARRED_SESSION_HASHTAGS = "starred_session_hashtags"; /** * The {@link Sessions#SESSION_URL} of the first starred session in this * block. */ public static final String STARRED_SESSION_URL = "starred_session_url"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, " + BlocksColumns.BLOCK_END + " ASC"; public static final String EMPTY_SESSIONS_SELECTION = "(" + BLOCK_TYPE + " = '" + ParserUtils.BLOCK_TYPE_SESSION + "' OR " + BLOCK_TYPE + " = '" + ParserUtils.BLOCK_TYPE_CODE_LAB + "') AND " + SESSIONS_COUNT + " = 0"; /** Build {@link Uri} for requested {@link #BLOCK_ID}. */ public static Uri buildBlockUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #BLOCK_ID}. */ public static Uri buildSessionsUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references starred {@link Sessions} associated * with the requested {@link #BLOCK_ID}. */ public static Uri buildStarredSessionsUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS) .appendPath(PATH_STARRED).build(); } /** * Build {@link Uri} that references any {@link Blocks} that occur * between the requested time boundaries. */ public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) { return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath( String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build(); } /** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */ public static String getBlockId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #BLOCK_ID} that will always match the requested * {@link Blocks} details. */ public static String generateBlockId(long startTime, long endTime) { startTime /= DateUtils.SECOND_IN_MILLIS; endTime /= DateUtils.SECOND_IN_MILLIS; return ParserUtils.sanitizeId(startTime + "-" + endTime); } } /** * Tracks are overall categories for {@link Sessions} and {@link Vendors}, * such as "Android" or "Enterprise." */ public static class Tracks implements TracksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.track"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.track"; /** "All tracks" ID. */ public static final String ALL_TRACK_ID = "all"; public static final String CODELABS_TRACK_ID = generateTrackId("Code Labs"); public static final String TECH_TALK_TRACK_ID = generateTrackId("Tech Talk"); /** Count of {@link Sessions} inside given track. */ public static final String SESSIONS_COUNT = "sessions_count"; /** Count of {@link Vendors} inside given track. */ public static final String VENDORS_COUNT = "vendors_count"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = TracksColumns.TRACK_NAME + " ASC"; /** Build {@link Uri} for requested {@link #TRACK_ID}. */ public static Uri buildTrackUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #TRACK_ID}. */ public static Uri buildSessionsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references any {@link Vendors} associated with * the requested {@link #TRACK_ID}. */ public static Uri buildVendorsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_VENDORS).build(); } /** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */ public static String getTrackId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #TRACK_ID} that will always match the requested * {@link Tracks} details. */ public static String generateTrackId(String name) { return ParserUtils.sanitizeId(name); } } /** * Rooms are physical locations at the conference venue. */ public static class Rooms implements RoomsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.room"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.room"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, " + RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #ROOM_ID}. */ public static Uri buildRoomUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #ROOM_ID}. */ public static Uri buildSessionsDirUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */ public static String getRoomId(Uri uri) { return uri.getPathSegments().get(1); } } /** * Each session is a block of time that has a {@link Tracks}, a * {@link Rooms}, and zero or more {@link Speakers}. */ public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build(); public static final Uri CONTENT_STARRED_URI = CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.session"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.session"; public static final String BLOCK_ID = "block_id"; public static final String ROOM_ID = "room_id"; public static final String SEARCH_SNIPPET = "search_snippet"; // TODO: shortcut primary track to offer sub-sorting here /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC," + SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC"; public static final String LIVESTREAM_SELECTION = SESSION_LIVESTREAM_URL + " is not null AND " + SESSION_LIVESTREAM_URL + "!=''"; // Used to fetch sessions for a particular time public static final String AT_TIME_SELECTION = BLOCK_START + " < ? and " + BLOCK_END + " " + "> ?"; // Builds selectionArgs for {@link AT_TIME_SELECTION} public static String[] buildAtTimeSelectionArgs(long time) { final String timeString = String.valueOf(time); return new String[] { timeString, timeString }; } // Used to fetch upcoming sessions public static final String UPCOMING_SELECTION = BLOCK_START + " = (select min(" + BLOCK_START + ") from " + ScheduleDatabase.Tables.BLOCKS_JOIN_SESSIONS + " where " + LIVESTREAM_SELECTION + " and " + BLOCK_START + " >" + " ?)"; // Builds selectionArgs for {@link UPCOMING_SELECTION} public static String[] buildUpcomingSelectionArgs(long minTime) { return new String[] { String.valueOf(minTime) }; } /** Build {@link Uri} for requested {@link #SESSION_ID}. */ public static Uri buildSessionUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).build(); } /** * Build {@link Uri} that references any {@link Speakers} associated * with the requested {@link #SESSION_ID}. */ public static Uri buildSpeakersDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build(); } /** * Build {@link Uri} that includes track detail with list of sessions. */ public static Uri buildWithTracksUri() { return CONTENT_URI.buildUpon().appendPath(PATH_WITH_TRACK).build(); } /** * Build {@link Uri} that includes track detail for a specific session. */ public static Uri buildWithTracksUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId) .appendPath(PATH_WITH_TRACK).build(); } /** * Build {@link Uri} that references any {@link Tracks} associated with * the requested {@link #SESSION_ID}. */ public static Uri buildTracksDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build(); } public static Uri buildSessionsAtDirUri(long time) { return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time)) .build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */ public static String getSessionId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } } /** * Speakers are individual people that lead {@link Sessions}. */ public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.speaker"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.speaker"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #SPEAKER_ID}. */ public static Uri buildSpeakerUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #SPEAKER_ID}. */ public static Uri buildSessionsDirUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */ public static String getSpeakerId(Uri uri) { return uri.getPathSegments().get(1); } } /** * Each vendor is a company appearing at the conference that may be * associated with a specific {@link Tracks}. */ public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.vendor"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.vendor"; /** {@link Tracks#TRACK_ID} that this vendor belongs to. */ public static final String TRACK_ID = "track_id"; public static final String SEARCH_SNIPPET = "search_snippet"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = VendorsColumns.VENDOR_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #VENDOR_ID}. */ public static Uri buildVendorUri(String vendorId) { return CONTENT_URI.buildUpon().appendPath(vendorId).build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */ public static String getVendorId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } /** * Generate a {@link #VENDOR_ID} that will always match the requested * {@link Vendors} details. */ public static String generateVendorId(String companyName) { return ParserUtils.sanitizeId(companyName); } } /** * Announcements of breaking news */ public static class Announcements implements AnnouncementsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ANNOUNCEMENTS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.announcement"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.announcement"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = AnnouncementsColumns.ANNOUNCEMENT_DATE + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #ANNOUNCEMENT_ID}. */ public static Uri buildAnnouncementUri(String announcementId) { return CONTENT_URI.buildUpon().appendPath(announcementId).build(); } /** * Build {@link Uri} that references any {@link Announcements} * associated with the requested {@link #ANNOUNCEMENT_ID}. */ public static Uri buildAnnouncementsDirUri(String announcementId) { return CONTENT_URI.buildUpon().appendPath(announcementId) .appendPath(PATH_ANNOUNCEMENTS).build(); } /** * Read {@link #ANNOUNCEMENT_ID} from {@link Announcements} {@link Uri}. */ public static String getAnnouncementId(Uri uri) { return uri.getPathSegments().get(1); } } public static class SearchSuggest { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build(); public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1 + " COLLATE NOCASE ASC"; } public static Uri addCallerIsSyncAdapterParameter(Uri uri) { return uri.buildUpon().appendQueryParameter( ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); } public static boolean hasCallerIsSyncAdapterParameter(Uri uri) { return TextUtils.equals("true", uri.getQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER)); } private ScheduleContract() { } }
Java
/* * Copyright 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.android.apps.iosched.io; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.io.model.Event; import com.google.android.apps.iosched.io.model.SessionsResponse; import com.google.android.apps.iosched.io.model.SessionsResult; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.text.format.Time; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; /** * Handler that parses session JSON data into a list of content provider operations. */ public class SessionsHandler extends JSONHandler { private static final String TAG = makeLogTag(SessionsHandler.class); private static final String BASE_SESSION_URL = "https://developers.google.com/events/io/sessions/"; private static final String EVENT_TYPE_KEYNOTE = "keynote"; private static final String EVENT_TYPE_CODELAB = "codelab"; private static final int PARSE_FLAG_FORCE_SCHEDULE_REMOVE = 1; private static final int PARSE_FLAG_FORCE_SCHEDULE_ADD = 2; private static final Time sTime = new Time(); private static final Pattern sRemoveSpeakerIdPrefixPattern = Pattern.compile(".*//"); private boolean mLocal; private boolean mThrowIfNoAuthToken; public SessionsHandler(Context context, boolean local, boolean throwIfNoAuthToken) { super(context); mLocal = local; mThrowIfNoAuthToken = throwIfNoAuthToken; } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); SessionsResponse response = new Gson().fromJson(json, SessionsResponse.class); int numEvents = 0; if (response.result != null) { numEvents = response.result[0].events.length; } if (numEvents > 0) { LOGI(TAG, "Updating sessions data"); // by default retain locally starred if local sync boolean retainLocallyStarredSessions = mLocal; if (response.error != null && response.error.isJsonPrimitive()) { String errorMessageLower = response.error.getAsString().toLowerCase(); if (!mLocal && (errorMessageLower.contains("no profile") || errorMessageLower.contains("no auth token"))) { // There was some authentication issue; retain locally starred sessions. retainLocallyStarredSessions = true; LOGW(TAG, "The user has no developers.google.com profile or this call is " + "not authenticated. Retaining locally starred sessions."); } if (mThrowIfNoAuthToken && errorMessageLower.contains("no auth token")) { throw new HandlerException.UnauthorizedException("No auth token but we tried " + "authenticating. Need to invalidate the auth token."); } } Set<String> starredSessionIds = new HashSet<String>(); if (retainLocallyStarredSessions) { // Collect the list of current starred sessions Cursor starredSessionsCursor = mContext.getContentResolver().query( Sessions.CONTENT_STARRED_URI, new String[]{ScheduleContract.Sessions.SESSION_ID}, null, null, null); while (starredSessionsCursor.moveToNext()) { starredSessionIds.add(starredSessionsCursor.getString(0)); } starredSessionsCursor.close(); } // Clear out existing sessions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.CONTENT_URI)) .build()); // Maintain a list of created block IDs Set<String> blockIds = new HashSet<String>(); for (SessionsResult result : response.result) { for (Event event : result.events) { int flags = 0; if (retainLocallyStarredSessions) { flags = (starredSessionIds.contains(event.id) ? PARSE_FLAG_FORCE_SCHEDULE_ADD : PARSE_FLAG_FORCE_SCHEDULE_REMOVE); } String sessionId = event.id; if (TextUtils.isEmpty(sessionId)) { LOGW(TAG, "Found session with empty ID in API response."); continue; } // Session title String sessionTitle = event.title; if (EVENT_TYPE_CODELAB.equals(result.event_type)) { sessionTitle = mContext.getString( R.string.codelab_title_template, sessionTitle); } // Whether or not it's in the schedule boolean inSchedule = "Y".equals(event.attending); if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0 || (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) { inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0; } if (EVENT_TYPE_KEYNOTE.equals(result.event_type)) { // Keynotes are always in your schedule. inSchedule = true; } // Re-order session tracks so that Code Lab is last if (event.track != null) { Arrays.sort(event.track, sTracksComparator); } // Hashtags String hashtags = ""; if (event.track != null) { StringBuilder hashtagsBuilder = new StringBuilder(); for (String trackName : event.track) { if (trackName.trim().startsWith("Code Lab")) { trackName = "Code Labs"; } if (trackName.contains("Keynote")) { continue; } hashtagsBuilder.append(" #"); hashtagsBuilder.append( ScheduleContract.Tracks.generateTrackId(trackName)); } hashtags = hashtagsBuilder.toString().trim(); } // Pre-reqs String prereqs = ""; if (event.prereq != null && event.prereq.length > 0) { StringBuilder sb = new StringBuilder(); for (String prereq : event.prereq) { sb.append(prereq); sb.append(" "); } prereqs = sb.toString(); if (prereqs.startsWith("<br>")) { prereqs = prereqs.substring(4); } } String youtubeUrl = null; if (event.youtube_url != null && event.youtube_url.length > 0) { youtubeUrl = event.youtube_url[0]; } // Insert session info final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Sessions.SESSION_ID, sessionId) .withValue(Sessions.SESSION_TYPE, result.event_type) .withValue(Sessions.SESSION_LEVEL, event.level) .withValue(Sessions.SESSION_TITLE, sessionTitle) .withValue(Sessions.SESSION_ABSTRACT, event._abstract) .withValue(Sessions.SESSION_TAGS, event.tags) .withValue(Sessions.SESSION_URL, makeSessionUrl(sessionId)) .withValue(Sessions.SESSION_LIVESTREAM_URL, event.livestream_url) .withValue(Sessions.SESSION_REQUIREMENTS, prereqs) .withValue(Sessions.SESSION_STARRED, inSchedule) .withValue(Sessions.SESSION_HASHTAGS, hashtags) .withValue(Sessions.SESSION_YOUTUBE_URL, youtubeUrl) .withValue(Sessions.SESSION_PDF_URL, "") .withValue(Sessions.SESSION_NOTES_URL, "") .withValue(Sessions.ROOM_ID, sanitizeId(event.room)); long sessionStartTime = parseTime(event.start_date, event.start_time); long sessionEndTime = parseTime(event.end_date, event.end_time); String blockId = ScheduleContract.Blocks.generateBlockId( sessionStartTime, sessionEndTime); if (!blockIds.contains(blockId)) { String blockType; String blockTitle; if (EVENT_TYPE_KEYNOTE.equals(result.event_type)) { blockType = ParserUtils.BLOCK_TYPE_KEYNOTE; blockTitle = mContext.getString(R.string.schedule_block_title_keynote); } else if (EVENT_TYPE_CODELAB.equals(result.event_type)) { blockType = ParserUtils.BLOCK_TYPE_CODE_LAB; blockTitle = mContext .getString(R.string.schedule_block_title_code_labs); } else { blockType = ParserUtils.BLOCK_TYPE_SESSION; blockTitle = mContext.getString(R.string.schedule_block_title_sessions); } batch.add(ContentProviderOperation .newInsert(ScheduleContract.Blocks.CONTENT_URI) .withValue(ScheduleContract.Blocks.BLOCK_ID, blockId) .withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType) .withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle) .withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime) .withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime) .build()); blockIds.add(blockId); } builder.withValue(Sessions.BLOCK_ID, blockId); batch.add(builder.build()); // Replace all session speakers final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId); batch.add(ContentProviderOperation .newDelete(ScheduleContract .addCallerIsSyncAdapterParameter(sessionSpeakersUri)) .build()); if (event.speaker_id != null) { for (String speakerId : event.speaker_id) { speakerId = sRemoveSpeakerIdPrefixPattern.matcher(speakerId).replaceAll( ""); batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri) .withValue(SessionsSpeakers.SESSION_ID, sessionId) .withValue(SessionsSpeakers.SPEAKER_ID, speakerId).build()); } } // Replace all session tracks final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.buildTracksDirUri(sessionId)); batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build()); if (event.track != null) { for (String trackName : event.track) { if (trackName.contains("Code Lab")) { trackName = "Code Labs"; } String trackId = ScheduleContract.Tracks.generateTrackId(trackName); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } } } } } return batch; } private Comparator<String> sTracksComparator = new Comparator<String>() { @Override public int compare(String s1, String s2) { // TODO: improve performance of this comparator return (s1.contains("Code Lab") ? "z" : s1).compareTo( (s2.contains("Code Lab") ? "z" : s2)); } }; private String makeSessionUrl(String sessionId) { if (TextUtils.isEmpty(sessionId)) { return null; } return BASE_SESSION_URL + sessionId; } private static long parseTime(String date, String time) { //change to this format : 2011-05-10T07:00:00.000-07:00 int index = time.indexOf(":"); if (index == 1) { time = "0" + time; } final String composed = String.format("%sT%s:00.000-07:00", date, time); //return sTimeFormat.parse(composed).getTime(); sTime.parse3339(composed); return sTime.toMillis(false); } }
Java
/* * Copyright 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.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.SearchSuggestions; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.app.SearchManager; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; /** * Handler that parses search suggestions JSON data into a list of content provider operations. */ public class SearchSuggestHandler extends JSONHandler { public SearchSuggestHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); SearchSuggestions suggestions = new Gson().fromJson(json, SearchSuggestions.class); if (suggestions.words != null) { // Clear out suggestions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.SearchSuggest.CONTENT_URI)) .build()); // Rebuild suggestions for (String word : suggestions.words) { batch.add(ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.SearchSuggest.CONTENT_URI)) .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, word) .build()); } } return batch; } }
Java
/* * Copyright 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.android.apps.iosched.io; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import android.content.ContentProviderOperation; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.TextUtils; import com.google.android.apps.iosched.io.model.Announcement; import com.google.android.apps.iosched.io.model.AnnouncementsResponse; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Announcements; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import java.io.IOException; import java.util.ArrayList; /** * Handler that parses announcements JSON data into a list of content provider operations. */ public class AnnouncementsHandler extends JSONHandler { private static final String TAG = makeLogTag(AnnouncementsHandler.class); public AnnouncementsHandler(Context context, boolean local) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); AnnouncementsResponse response = new Gson().fromJson(json, AnnouncementsResponse.class); int numAnnouncements = 0; if (response.announcements != null) { numAnnouncements = response.announcements.length; } if (numAnnouncements > 0) { LOGI(TAG, "Updating announcements data"); // Clear out existing announcements batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Announcements.CONTENT_URI)) .build()); for (Announcement announcement : response.announcements) { // Save tracks as a json array final String tracks = (announcement.tracks != null && announcement.tracks.length > 0) ? new Gson().toJson(announcement.tracks) : null; // Insert announcement info batch.add(ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Announcements.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) // TODO: better announcements ID heuristic .withValue(Announcements.ANNOUNCEMENT_ID, (announcement.date + announcement.title).hashCode()) .withValue(Announcements.ANNOUNCEMENT_DATE, announcement.date) .withValue(Announcements.ANNOUNCEMENT_TITLE, announcement.title) .withValue(Announcements.ANNOUNCEMENT_SUMMARY, announcement.summary) .withValue(Announcements.ANNOUNCEMENT_URL, announcement.link) .withValue(Announcements.ANNOUNCEMENT_TRACKS, tracks) .build()); } } return batch; } }
Java
/* * Copyright 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.android.apps.iosched.io; import java.io.IOException; /** * General {@link IOException} that indicates a problem occurred while parsing or applying a {@link * JSONHandler}. */ public class HandlerException extends IOException { public HandlerException() { super(); } public HandlerException(String message) { super(message); } public HandlerException(String message, Throwable cause) { super(message); initCause(cause); } @Override public String toString() { if (getCause() != null) { return getLocalizedMessage() + ": " + getCause(); } else { return getLocalizedMessage(); } } public static class UnauthorizedException extends HandlerException { public UnauthorizedException() { } public UnauthorizedException(String message) { super(message); } public UnauthorizedException(String message, Throwable cause) { super(message, cause); } } public static class NoDevsiteProfileException extends HandlerException { public NoDevsiteProfileException() { } public NoDevsiteProfileException(String message) { super(message); } public NoDevsiteProfileException(String message, Throwable cause) { super(message, cause); } } }
Java
/* * Copyright 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.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.Day; import com.google.android.apps.iosched.io.model.EventSlots; import com.google.android.apps.iosched.io.model.TimeSlot; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class BlocksHandler extends JSONHandler { private static final String TAG = makeLogTag(BlocksHandler.class); public BlocksHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); try { Gson gson = new Gson(); EventSlots eventSlots = gson.fromJson(json, EventSlots.class); int numDays = eventSlots.day.length; //2011-05-10T07:00:00.000-07:00 for (int i = 0; i < numDays; i++) { Day day = eventSlots.day[i]; String date = day.date; TimeSlot[] timeSlots = day.slot; for (TimeSlot timeSlot : timeSlots) { parseSlot(date, timeSlot, batch); } } } catch (Throwable e) { LOGE(TAG, e.toString()); } return batch; } private static void parseSlot(String date, TimeSlot slot, ArrayList<ContentProviderOperation> batch) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(Blocks.CONTENT_URI)); //LOGD(TAG, "Inside parseSlot:" + date + ", " + slot); String start = slot.start; String end = slot.end; String type = "N_D"; if (slot.type != null) { type = slot.type; } String title = "N_D"; if (slot.title != null) { title = slot.title; } String startTime = date + "T" + start + ":00.000-07:00"; String endTime = date + "T" + end + ":00.000-07:00"; LOGV(TAG, "startTime:" + startTime); long startTimeL = ParserUtils.parseTime(startTime); long endTimeL = ParserUtils.parseTime(endTime); final String blockId = Blocks.generateBlockId(startTimeL, endTimeL); LOGV(TAG, "blockId:" + blockId); LOGV(TAG, "title:" + title); LOGV(TAG, "start:" + startTimeL); builder.withValue(Blocks.BLOCK_ID, blockId); builder.withValue(Blocks.BLOCK_TITLE, title); builder.withValue(Blocks.BLOCK_START, startTimeL); builder.withValue(Blocks.BLOCK_END, endTimeL); builder.withValue(Blocks.BLOCK_TYPE, type); builder.withValue(Blocks.BLOCK_META, slot.meta); batch.add(builder.build()); } }
Java
/* * Copyright 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.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.MyScheduleItem; import com.google.android.apps.iosched.io.model.MyScheduleResponse; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Handler that parses "my schedule" JSON data into a list of content provider operations. */ public class MyScheduleHandler extends JSONHandler { private static final String TAG = makeLogTag(MyScheduleHandler.class); public MyScheduleHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); MyScheduleResponse response = new Gson().fromJson(json, MyScheduleResponse.class); if (response.error == null) { LOGI(TAG, "Updating user's schedule"); if (response.schedule_list != null) { // Un-star all sessions first batch.add(ContentProviderOperation .newUpdate(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.CONTENT_URI)) .withValue(Sessions.SESSION_STARRED, 0) .build()); // Star only those sessions in the "my schedule" response for (MyScheduleItem item : response.schedule_list) { batch.add(ContentProviderOperation .newUpdate(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.buildSessionUri(item.session_id))) .withValue(Sessions.SESSION_STARRED, 1) .build()); } } } return batch; } }
Java
/* * Copyright 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.android.apps.iosched.io.model; public class TimeSlot { public String start; public String end; public String title; public String type; public String meta; }
Java
/* * Copyright 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.android.apps.iosched.io.model; public class EventSlots { public Day[] day; }
Java
/* * Copyright 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.android.apps.iosched.io.model; public class MyScheduleResponse extends GenericResponse { public MyScheduleItem[] schedule_list; }
Java
/* * Copyright 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.android.apps.iosched.io.model; public class Speaker { public String display_name; public String bio; public String plusone_url; public String thumbnail_url; public String user_id; }
Java
/* * Copyright 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.android.apps.iosched.io.model; public class Tracks { Track[] track; public Track[] getTrack() { return track; } }
Java
/* * Copyright 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.android.apps.iosched.io.model; import com.google.gson.annotations.SerializedName; public class SpeakersResponse extends GenericResponse { @SerializedName("devsite_speakers") public Speaker[] speakers; }
Java
/* * Copyright 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.android.apps.iosched.io.model; public class Rooms { public Room[] rooms; }
Java
/* * Copyright 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.android.apps.iosched.io.model; public class SandboxCompany { public String company_name; public String company_description; public String[] exhibitors; public String logo_img; public String product_description; public String product_pod; public String website; }
Java
/* * Copyright 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.android.apps.iosched.io.model; import com.google.gson.annotations.SerializedName; public class Track { public String name; public String color; @SerializedName("abstract") public String _abstract; }
Java
/* * Copyright 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.android.apps.iosched.io.model; import com.google.gson.JsonElement; public class GenericResponse { public JsonElement error; // // public void checkResponseForAuthErrorsAndThrow() throws IOException { // if (error != null && error.isJsonObject()) { // JsonObject errorObject = error.getAsJsonObject(); // int errorCode = errorObject.get("code").getAsInt(); // String errorMessage = errorObject.get("message").getAsString(); // if (400 <= errorCode && errorCode < 500) { // // The API currently only returns 400 unfortunately. // throw ... // } // } // } }
Java
/* * Copyright 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.android.apps.iosched.io.model; public class Announcement { public String date; public String[] tracks; public String title; public String link; public String summary; }
Java
/* * Copyright 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.android.apps.iosched.io.model; public class SessionsResponse extends GenericResponse { public SessionsResult[] result; }
Java