<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
一般的android手机有厂商自定写驱动,实现操作系统,一些定制小厂商的android系统API实现,不是那怎完整,或者就是不支持,导致的结果是,你的应用装上去就弹出应用程序异常。
Ti.App.Properties.setString('host','http://192.168.0.209:81/Resources/');
Ti.App.Properties.getString('activeCode','http://192.168.0.209:81//Resources/md5.txt?activeCode=1111')
Ti.App.Properties.setString('host','http://222.76.242.154:9001/');
Ti.App.Properties.getString('activeCode','http://222.76.242.154:9001/host.txt?activeCode=1111')
'<ArrayOfKeyValueOfstringanyType xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:a="http://www./2001/XMLSchema" xmlns:i="http://www./2001/XMLSchema-instance"><KeyValueOfstringanyType><Key>Actorduty</Key><Value i:type="a:string"/></KeyValueOfstringanyType><KeyValueOfstringanyType><Key>ActordutyCode</Key><Value i:type="a:string"/></KeyValueOfstringanyType></ArrayOfKeyValueOfstringanyType>', 1, 0, 1, 1, '5f78349feacf4215953440c9c6581756ta'
Working with Remote Data Sources Working with XML Data
在Tweet的编辑页面中,我们还表示了一个图像,到现在为止,我们都是通过从相册中选择出来的图片,所以图片本身就保存在相册中,但是当我们通过相机拍照的话,就需要将图片保存在相册中。
Js代码
1. Titanium.Media.saveToPhotoGallery(image)
通过以上代码就能将image图片保存到相册中。
function openCamera() {
Titanium.Media.showCamera({
success : function(e) {
// e.media
var target = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, 'photo.png');
target.write(e.media);
if (!isAndroid) {
Titanium.Media.saveToPhotoGallery(e.media, function(e) {
if (e.success) {
//儲存成功
}
});
}
},
error : function(e) {
Titanium.API.info(JSON.stringify(e));
},
cancel : function(e) {
alert('取消拍照');
},
mediaTypes : [Titanium.Media.MEDIA_TYPE_PHOTO],
//^^^^^^^^^^^^^^^^^^^Android 較常用功能^^^^^^^^^^^^^^^^^^^^^^^^^^^
overlay : overlayView,
transform : Titanium.UI.create2DMatrix().scale(1.0),
showControls : false, //iOS Only
saveToPhotoGallery : isAndroid
});
}
shotButton.addEventListener('click', function() {
//不會自動存入相簿
Titanium.Media.takePicture();
});
win.addEventListener('open', function() {
openCamera();
});
Js代码
1. var file = Ti.Filesystem.getFile(
2. Titanium.Filesystem.resourcesDirectory + '/' + fileName
3. );
4. file.write(image)
当然也可以通过这样的方法,将图像以文件的形式保存。
myView.startLayout();
myView.top = 50;
myView.left = 50;
myView.width = 200;
myView.finishLayout();
myView.updateLayout({
top: 50,
left: 50,
width: 200
});
var postLayoutCallback = function(e){
Ti.API.info(String.format("Layout done, left: %f, width: %f", myView.rect.x, myView.rect.width));
myView.removeEventListener('postlayout', postLayoutCallback);
}
myView.addEventListener('postlayout', postLayoutCallback);
myView.updateLayout({
left: '25%',
width: '25%'
});
var win = Ti.UI.createWindow({});
//Clipping.
var parent = Ti.UI.createView(\{backgroundColor:'red',width:'100',height:'100'\})
var child = Ti.UI.createView(\{backgroundColor:'green',width:150,height:150,left:5,top:5\});
parent.add(child);
win.add(parent);
win.open();
var win = Ti.UI.createWindow({});
var label = Ti.UI.createLabel({text:'I am label', backgroundColor:'red'});
win.add(label);
win.open();
var win = Ti.UI.createWindow({});
//Implicit width calculation in 2_0_X
var parent = Ti.UI.createView({backgroundColor:'red',width:'100',height:'100'})
var child = Ti.UI.createView({backgroundColor:'green',left:5,top:5,center:{x:20,y:20}});
parent.add(child);
win.add(parent);
win.open();
var win = Ti.UI.createWindow({});
var parent = Ti.UI.createView({backgroundColor:'red',width:'100',height:'100'})
var child = Ti.UI.createView({backgroundColor:'green',width:50,height:50,left:5,top:5,
center:{x:60,y:60}});
parent.add(child);
win.add(parent);
win.open();
var win = Ti.UI.createWindow({});
//Horizontal Layout behavior. Green child centered vertically (No positioning pins)
var parent = Ti.UI.createView({backgroundColor:'red',layout:'horizontal',width:100, height:100})
var child1 = Ti.UI.createView({backgroundColor:'green',height:20,width:50});
var child2 = Ti.UI.createView({backgroundColor:'blue',height:40,width:50});
parent.add(child1);
parent.add(child2);
win.add(parent);
win.open();
var win = Ti.UI.createWindow({backgroundColor:'white',});
//Implicit width calculation in 2_0_X
var parent = Ti.UI.createView({backgroundColor:'red',width:'100',height:'100'})
var child = Ti.UI.createView({backgroundColor:'green',left:5,top:5,center:{x:20,y:20}});
parent.add(child);
win.add(parent);
win.open();
var foo = true;
var me = 'awesome';
var foo = true, me = 'awesome';
// You could do this
if(somecondition === somevalue) {
var xyz = 'abc';
} else {
var xyz = '123';
}
// but this is more compact
var xyz = (somecondition === somevalue) ? 'abc' : '123';
var names = ['Jeff','Nolan','Marshall','Don'];
for(var i=0;i<names.length;i++){
process(names[i]);
}
It is better to only get the length of the array only once, as in:
var names = ['Jeff','Nolan','Marshall','Don'];
for(var i=0,j=names.length;i<j;i++){
process(names[i]);
}
var sum = (function() {
var tmpValue = 0;
for (var i = 0; i < 100; i++) {
tmpValue += i;
}
return tmpValue;
})();
Ti.UI.createWindow({
url:'window.js'
}).open();
var label1 = Titanium.UI.createLabel({
color:'#999',
text:'I am Window 1',
font:{fontSize:20,fontFamily:'Helvetica Neue'},
textAlign:'center',
width:'auto'
});
win1.add(label1);
var win1 = Titanium.UI.createWindow({
title:'Tab 1',
backgroundColor:'#fff',
url:'win1.js'
});
var label1 = Titanium.UI.createLabel({
color:'#999',
text:win1.mylabel,
font:{fontSize:20,fontFamily:'Helvetica Neue'},
textAlign:'center',
width:'auto'
});
label1.addEventListener('click', function() {
Ti.App.fireEvent('app:labelclicked', {newlabel:'Sent from win1.js'});
});
var win = Ti.UI.createWindow({ id:'mainwin' });
var label = Ti.UI.createLabel({ id:'ptlabel' });
win.add(label);
win.open();
var thisDate = new Date(); // will always return date in English
Ti.API.info("Ti.Locale.currentLanguage = " + Ti.Locale.currentLanguage);
Ti.API.info("Ti.Locale.currentLocale = " + Ti.Locale.currentLocale);
Ti.API.info("thisDate = " + thisDate);
var thisMonth = thisDate.toString().split(' ',2)[1];
Ti.API.info("The month contained in thisDate is: " + thisMonth);
Ti.API.info("Note: as thisMonth is always in the default language, English, it can be used to look up the localized string.");
Ti.API.info("Hence, the localized string, headingDate, in the language of " + Ti.Locale.currentLanguage + " is:");
Ti.API.info(String.format(L('headingDate'),thisDate.getDate(),L(thisMonth),thisDate.getFullYear()));
// create tab group
var tabGroup = Titanium.UI.createTabGroup();
var win1 = Titanium.UI.createWindow({
title:'Tab 1',
backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
icon:'tab1icon.png',
title:'Tab 1',
window:win1
});
var win2 = Titanium.UI.createWindow({
title:'Tab 2',
backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
icon:'tab2icon.png',
title:'Tab 2',
window:win2
});
// add tabs to the group
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);
// open tab group
tabGroup.open();
var win = Ti.UI.createWindow({
backgroundColor:'#fff'
});
var redview = Ti.UI.createView({
top:20,
left:20,
width:10,
height:10,
backgroundColor:"red"
});
win.add(redview);
var yellowview = Ti.UI.createView({
bottom:100,
right:100,
width:10,
height:10,
backgroundColor:"yellow"
});
win.add(yellowview);
var blueview = Ti.UI.createView({
center: {x: 160, y: 240},
width:50,
height:50,
backgroundColor:"blue"
});
win.add(blueview);
var greenview = Ti.UI.createView({
top:-20,
width:10,
height:10,
backgroundColor:"green"
});
win.add(greenview);
win.open();
var win = Ti.UI.createWindow({
backgroundColor:'#fff'
});
// uses grid-drawing module from https://gist.github.com/1187384
// to draw grid lines every 20 points
var grid = require('gridlines');
grid.drawgrid(20,win);
// draw a view that fills the window and set its layout property
var view = Ti.UI.createView({
backgroundColor:'transparent',
top:0,
left:0,
width:'100%',
height:'100%',
layout:'vertical'
});
// simple function for making colored boxes
function makeView(color) {
return Ti.UI.createView({
top:20,
left:20,
width:20,
height:20,
backgroundColor:color
});
}
view.add(makeView('red'));
view.add(makeView('yellow'));
view.add(makeView('blue'));
view.add(makeView('green'));
win.add(view);
win.open();
事件与addEventListener()函数
element.addEventListener('event_type', function(e) {
// code here is run when the event is fired
// properties of the event object 'e' describe the event and object that received it
Ti.API.info('The '+e.type+' event happened');
});
function doSomething(e) {
// This function will be called by multiple handlers
// The event object is accessible within this function
Ti.API.info('The '+e.type+' event happened');
}
button1.addEventListener('click', doSomething);
button2.addEventListener('click', doSomething)
click and its synonym tap
swipe which is a left or right touch and drag the finger action
scroll which is a touch and drag action
dblclick and its synonym doubletap
touchstart, touchmove, and touchend which define the three stages of an action where the user touches the screen, moves his or her finger in an arbitrary direction, then lifts the finger
Firing events 解雇事件
someButton.fireEvent('click');
someButton.addEventListener('click', function(e){
Ti.APP.info('The value of kitchen is '+e.kitchen);
});
function doSomething(e) {
// do something
}
deleteButton.addEventListener('click', doSomething);
// ... elsewhere in your code ...
deleteButton.removeEventListener('click', doSomething);
});
// create tab group
var tabGroup = Titanium.UI.createTabGroup();
var win1 = Titanium.UI.createWindow({
title:'Tab 1',
backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
icon:'tab1icon.png',
title:'Tab 1',
window:win1
});
var win2 = Titanium.UI.createWindow({
title:'Tab 2',
backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
icon:'tab2icon.png',
title:'Tab 2',
window:win2
});
// add tabs to the group
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);
// open tab group
tabGroup.open();
var view = Ti.UI.createView({
/* You would not normally mix units like this */
top: '10mm',
left: '5px',
width: '30%',
height: 50 /* default system units are used here */
});
// create an array of anonymous objects
var tbl_data = [
{title:'Row 1'},
{title:'Row 2'},
{title:'Row 3'}
];
// now assign that array to the table's data property to add those objects as rows
var table = Titanium.UI.createTableView({
data:tbl_data
});
// alternatively, you could do
table.setData(tbl_data);
var row = Titanium.UI.createTableViewRow({
title: 'Row 1'
/* other properties */
});
table.appendRow(row);
// with an explicit object, you can call methods such as
// var imgCapture = row.toImage();
table.setData([]);
// or
table.data = [];
Row properties
className – set this property equal to an arbitrary string to optimize rendering performance. On both iOS and Android, setting this property enables the operating system to reuse table rows that are scrolled out of view to speed up the rendering of newly-visible rows. On iOS, the string you supply is used to specify the reuse-identifier string (setdequeueReusableCellWithIdentifier); on Android, it is used within a custom object reuse method within Titanium.
leftImage – set this property equal to an image URL (local or remote) to display that image to the left of the row's title
rightImage – set this property equal to an image URL (local or remote) to display that image to the right of the row's title
backgroundImage – set this property equal to an image URL (local or remote) to display that image in the background of the row
backgroundColor – set this property to a color string to set the row's background color
var tbl_data = [
{title:'Row 1', leftImage: 'KS_nav_ui.png'},
{title:'Row 2', rightImage: 'KS_nav_ui.png'},
{title:'Row 3', backgroundColor: '#fdd'}
];
// now assign that array to the table's data property to add those objects as rows
var table = Titanium.UI.createTableView({
data:tbl_data
});
// alternatively, you could do
table.setData(tbl_data);
Row indicators
hasChild – indicates sub-table or additional rows (most commonly used on iOS with the NavigationGroup control)
hasDetail – indicates a detail view or alert will appear when row is tapped (not supported on Android)
hasCheck – an on/off or yes/no indicator
,
});
You can use the built-in headerTitle and footerTitle to add header and footer titles to your tables. This convenience property allows you to enter arbitrary text for these titles, but will only use the default font formatting.
var data = [
{ title: 'Row 1' },
{ title: 'Row 2' },
{ title: 'Row 3' }
];
var tableview = Titanium.UI.createTableView ({
data:data,
headerTitle:'TableView examples and test cases',
footerTitle:"Wow. That was cool!",
});
var tbl_data = [
{ title: 'Row 1' },
{ title: 'Row 2' },
{ title: 'Row 3' }
];
var createCustomView = function(title) {
var view = Ti.UI.createView({
backgroundColor: '#222',
height: 40
});
var text = Ti.UI.createLabel({
text: title,
left: 20,
color: '#fff'
});
view.add(text);
return view;
};
// now assign that array to the table's data property to add those objects as rows
var table = Titanium.UI.createTableView({
data:tbl_data,
headerView: createCustomView('Header View'),
footerView: createCustomView('Footer View')
});
// alternatively, you could do
table.setData(tbl_data);
// Create the first TableViewSection
var section1 = Ti.UI.createTableViewSection({
headerTitle:'Header 1'
});
// use a loop to add some rows
for (var i=0; i < 4; i++) {
section1.add(Ti.UI.createTableViewRow({
title:'Row '+i
}));
}
// do it all again...
var section2 = Ti.UI.createTableViewSection({
headerTitle: 'Section 2'
});
for (var i=4; i < 10; i++) {
section2.add(Ti.UI.createTableViewRow({
title:'Row '+i
}));
}
// Now, here's our table, and we're setting the data to hold the sections
var tv = Ti.UI.createTableView({
data:[section1,section2]
});
function makeRow() {
// generate random string of digits and capital English letters
// see http://en./wiki/Base_36
return Ti.UI.createTableViewRow({
title: Math.random().toString(36).substring(7)
});
}
var searchbar = Ti.UI.createSearchBar({
barColor: '#385292',
showCancel: false
});
var tbl = Ti.UI.createTableView({
search: searchbar,
hideSearchOnSelection: true
});
var data = [];
for(var i=0; i<100; i++) {
data.push(makeRow());
}
tbl.data = data;
win.add(tbl);
table.addEventListener('click', function(e){
alert('You clicked row '+e.index);
});
index – the ordinal index number of the row that received the event
row – the object representing the row that received the event
rowData – the properties of the row that received the event
source – the object that received the original event
section – the table section that received the event
You create a ScrollView using the createScrollView() method, as shown here:
var sv = Ti.UI.createScrollView({
height:200,
width:200,
/* left & right work too */
contentHeight:'auto',
contentWidth:'auto'
})
ScrollView properties
zoomScale, minZoomScale, maxZoomScale
You can control zooming of the content within the ScrollView with these properties. Each accepts a numeric value between 0 and 1.
horizontalBounce, verticalBounce
(iOS only) These Boolean values control whether the ScrollView displays that "bounce" effect when the user has reached the end of the scrolling content.
showHorizontalScrollIndicator, showVerticalScrollIndicator
These Boolean values control whether the scroll indicator (scrollbar-like gizmo) is displayed.
scrollType
On Android, you can set the ScrollView to either "vertical" or "horizontal" but not both.
canCancelEvents
On iOS, you can set this value to true (default) so that events are handled by the ScrollView rather than the views it contains.
var view1 = Titanium.UI.createView({backgroundColor:'#123'});
var view2 = Titanium.UI.createView({backgroundColor:'#234'});
var view3 = Titanium.UI.createView({backgroundColor:'#345'});
var scrollable = Titanium.UI.createScrollableView({
views:[view1,view2,view3],
showPagingControl: true
});
win.add(scrollable);
// add another view
var view4 = Titanium.UI.createView({backgroundColor:'#456'});
scrollable.addView(view4);
// and you could remove a view with
scrollable.removeView(view1);
ScrollableView properties
showPagingControl
Boolean, set to false (default) to hide the paging control (the dots that show which page you're viewing)
pagingControlColor
Set the background color for the paging control; you can't control the color of the dots.
pagingControlHeight
Set the height of the paging control area.
currentPage
This property accepts an index number of the view to display (zero-based, so currentPage=2 would show the third view within the ScrollableView)
cacheSize
This iOS-only property accepts an integer value to control the number of views pre-rendered. See the API docs for considerations when using this property.
ScrollableView methods
scrollToView()
Accepts an integer or object reference of the sub-view to scroll into view within the ScrollableView.
addView()
Adds a view to the ScrollableView, as shown in the code above.
removeView()
Removes a view from the ScrollableView, as shown in the code above.
var view = Ti.UI.createView();
view.addEventListener('longpress', function(e){
alert('You pressed at coordinates ' + e.x + ' / ' + e.y);
});
if(Titanium.Platform.name == 'android') {
Ti.Android.currentActivity.addEventListener('pause', function(e) {
// called when app is put into the background
if(accelerometerAdded) {
Ti.API.info("removing accelerometer callback on pause");
Ti.Accelerometer.removeEventListener('update', accelerometerCallback);
}
});
Ti.Android.currentActivity.addEventListener('resume', function(e) {
if(accelerometerAdded) {
Ti.API.info("adding accelerometer callback on resume");
Ti.Accelerometer.addEventListener('update', accelerometerCallback);
}
});
}
Added in the 1.8 release of the APIs, the pinch event is currently supported on iOS only. (Android support is in the works.) This event is associated with UI components and its event object has the useful scale property as shown here:
var view = Ti.UI.createView();
view.addEventListener('pinch', function(e){
alert('You pinched to ' + e.scale*100 + '%');
});
Touch
Touch events are associated with the Titanium UI components. There are four touch events:
touchstart – fired when a user's finger first contacts the device's screen.
touchend – fired when the user lifts his or her finger.
touchmove – fires continuously as the user drags his or her finger on the screen.
touchcancel – fired if the operating system interrupts an ongoing touch event, such as when a phone call is received.
The event object associated with these events has only two useful properties: the X and Y coordinates of
teView();
view.addEventListener('swipe', function(e){
alert('You swiped to the '+e.direction);
});
Swipe
Swipes are left/right tap & drag the finger gestures (where scrolls are up/down drags). Support for swipes are built into most of the Titanium UI components.
var view = Ti.UI.createView();
view.addEventListener('swipe', function(e){
alert('You swiped to the '+e.direction);
});
Shake
You can determine when a user shakes their device via the Ti.Gesture module.
Ti.Gesture.addEventListener('shake',function(e) {
alert('shaken at '+e.timestamp);
});
// box is a Ti.UI.View, when clicked, it fades out of view in 2 seconds, then fades back into view
box.addEventListener('click', function(){
box.animate({
opacity:0,
duration:2000
}, function(){
box.animate({
opacity:1,
duration:2000
});
});
});
Alternatively, you could use Animation objects to do the same thing:
var a = Ti.UI.createAnimation({
opacity:0,
duration:2000
});
var b = Ti.UI.createAnimation({
opacity:1,
duration:2000
});
box.addEventListener('click', function(){
box.animate(a, function(){
box.animate(b);
});
});
var matrix2d = Ti.UI.create2DMatrix();
matrix2d = matrix2d.rotate(20); // in degrees
matrix2d = matrix2d.scale(1.5); // scale to 1.5 times original size
var a = Ti.UI.createAnimation({
transform: matrix2d,
duration: 2000,
autoreverse: true,
repeat: 3
});
box.animate(a); // set the animation in motion
var matrix3d = Ti.UI.iOS.create3DMatrix();
// In next statement, the first arg is in degrees and the next three define an xyz vector describing the transformation
matrix3d = matrix3d.rotate(180, 1, 1, 0);
matrix3d = matrix3d.scale(2, 2, 2); // scale factor in the xyz axes
var a = Ti.UI.createAnimation({
transform: matrix3d,
duration: 2000,
autoreverse: true,
repeat: 3
});
box.animate(a); // set the animation in motion
// container is a View to which box1 and box2 are added
var selectedIndex = 0;
container.addEventListener('click', function(){
if (selectedIndex%2 == 0) {
container.animate({
view:box2,
transition:Ti.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT
});
}
else {
container.animate({
view:box1,
transition:Ti.UI.iPhone.AnimationStyle.FLIP_FROM_RIGHT
});
}
selectedIndex++;
});
/*
Branching logic based on OS
*/
var osname = Ti.Platform.osname;
var os = function(/*Object*/ map) {
var def = map.def||null; //default function or value
if (map[osname]) {
if (typeof map[osname] == 'function') { return map[osname](); }
else { return map[osname]; }
}
else {
if (typeof def == 'function') { return def(); }
else { return def; }
}
};
// Associated directly with an activity
activity = Ti.Android.currentActivity;
activity.onCreateOptionsMenu = function(e) {
var menu = e.menu;
var menuItem = menu.add({ title: "Item 1" });
menuItem.setIcon("item1.png");
menuItem.addEventListener("click", function(e) {
// do something when the menu item is tapped
});
};
// or with your heavyweight window, set here with navBarHidden
var win = Titanium.UI.createWindow({
navBarHidden: false,
activity : {
onCreateOptionsMenu : function(e) {
var menu = e.menu;
var menuItem = menu.add({ title : 'Item 1' });
menuItem.setIcon("item1.png");
menuItem.addEventListener('click', function(e) {
// do something when the menu item is tapped
});
}
}
// must be a heavyweight window to capture the androidback event
// so set something like fullscreen:false
var win = Ti.UI.createWindow({
title:'Hello world',
backgroundColor:'#fff',
fullscreen:false
});
win.addEventListener('androidback',function() {
// do something
});
var label = Ti.UI.createLabel({
html: 'Testing <b>bold</b> <i>italic</i> text',
text: 'This is for iOS',
top:125,
height:50,
width:'100%'
});
var lbl = Ti.UI.createLabel({
autoLink : Ti.UI.Android.LINKIFY_ALL,
left : 5, top : 5, right : 5, height : 100,
backgroundColor : '#222',
text : 'Contact\n test@test.com\n 817-555-5555\n http://\n 440 Bernardo Ave, Mountain View, CA'
});
});
The linkification options include:
Ti.UI.Android.LINKIFY_ALL – linkify all possible forms of links
Ti.UI.Android.LINKIFY_EMAIL_ADDRESSES – linkify just email addresses
Ti.UI.Android.LINKIFY_MAP_ADDRESSES – linkify just map addresses
Ti.UI.Android.LINKIFY_PHONE_NUMBERS – linkify just phone numbers
Ti.UI.Android.LINKIFY_WEB_URLS – linkify just Web addresses
Android enables simple "toast" style notifications. These are short messages that briefly float over all other content in your app, disappearing a short time later. You can create such notifications in Titanium by using the Ti.UI.createNotification() method as shown here:
var n = Ti.UI.createNotification({message:"Howdy folks"});
n.duration = Ti.UI.NOTIFICATION_DURATION_LONG;
// Also valid is NOTIFICATION_DURATION_SHORT
// Optionally, set the X & Y Offsets, by default
n.offsetX = 100;
n.offsetY = 75;
// display the toast message
n.show();
var intent = Ti.Android.createIntent({
action: Ti.Android.ACTION_DIAL,
data: "tel:8175551212"
});
// Create a PendingIntent to tie together the Activity and Intent
var pending = Titanium.Android.createPendingIntent({
activity: Titanium.Android.currentActivity,
intent: intent,
type: Titanium.Android.PENDING_INTENT_FOR_ACTIVITY,
flags: Titanium.Android.FLAG_UPDATE_CURRENT
});
// Here's the notification now
var notification = Titanium.Android.createNotification({
icon: 0x7f020000,
contentTitle: 'Dial Now!',
contentText : '817-555-1212',
contentIntent: pending
});
// Send the Notification to the manager, the digit is an ID you could use to later cancel the notification
Titanium.Android.NotificationManager.notify(1, notification);
var button = Ti.UI.createButton({
title:'Show popover',
width:250,
height:50,
top:30,
right:5
});
var popover = Ti.UI.iPad.createPopover({
width:300,
height:250,
title:'I\'m a Popover',
arrowDirection:Ti.UI.iPad.POPOVER_ARROW_DIRECTION_RIGHT
});
button.addEventListener('click', function(e) {
popover.show({
view:button,
animated:true
});
});
win.add(button);
// Sets the app's icon badge to 23
Ti.UI.iPhone.appBadge = 23;
var tabGroup = Titanium.UI.createTabGroup();
var win1 = Titanium.UI.createWindow({
title:'Window 1',
backgroundColor:'#fff'
});
// Set the badge for this tab to 10
var tab1 = Titanium.UI.createTab({
icon:'KS_nav_views.png',
title:'Tab 1',
window:win1,
badge:10
});
Ti.API.info(Ti.App.Properties.getString('name_preference')); // logs the name pref value from KitchenSink
Reading and Writing Properties
Titanium.App.Properties has six sets of get/set methods for handling six different data types:
getBool() / setBool(): for booleans (true, false)
getDouble() / setDouble(): for double-precision floating point numbers
getInt() / setInt(): for integers
getList() / setList(): for arrays
getString() / setString(): for strings
var window = Titanium.UI.createWindow({
backgroundColor:'#999'
});
var myArray = [ { name:'Name 1', address:'1 Main St'}, {name:'Name 2', address:'2 Main St'}, {name:'Name 3', address:'3 Main St'}, {name:'Name 4', address:'4 Main St' } ];
Ti.App.Properties.setString('myString','This is a string');
Ti.App.Properties.setInt('myInt',10);
Ti.App.Properties.setBool('myBool',true);
Ti.App.Properties.setDouble('myDouble',10.6);
Ti.App.Properties.setList('myList',myArray);
// **********************************************
// Notice the use of the second argument of the get* methods below
// that would be returned if no property exists with that name
// **********************************************
Ti.API.info("String: "+Ti.App.Properties.getString('myString','This is a string default'));
Ti.API.info("Integer: "+Ti.App.Properties.getInt('myInt',20));
Ti.API.info("Boolean: "+Ti.App.Properties.getBool('myBool',false));
Ti.API.info("Double: "+Ti.App.Properties.getDouble('myDouble',20.6));
Ti.API.info("List: "+Ti.App.Properties.getList('myList'));
window.open();
var window = Titanium.UI.createWindow({
backgroundColor:'#999'
});
var weatherData = { "reports" : [ { "city": "Mountain View", "condition": "Cloudy", "icon": "http://www./img_cartoon/pic23.gif" }, { "city": "Washington, DC", "condition": "Mostly Cloudy", "icon": "http://www./img_cartoon/pic20.gif" }, { "city": "Brasilia", "condition": "Thunderstorm", "icon": "http://www./img_cartoon/pic02.gif" } ] };
Ti.App.Properties.setString('myJSON', JSON.stringify(weatherData));
var retrievedJSON=Ti.App.Properties.getString('myJSON', 'myJSON not found');
Ti.API.info("The myJSON property contains: " + retrievedJSON);
window.open();
var myObject = JSON.parse(Ti.App.Properties.getString('myJSON'));
Working with a SQLite Database
var db = Ti.Database.open('weatherDB');
//bootstrap the database
var db = Ti.Database.open('TiBountyHunter');
db.execute('CREATE TABLE IF NOT EXISTS fugitives(id INTEGER PRIMARY KEY, name TEXT, captured INTEGER, url TEXT, capturedLat REAL, capturedLong REAL);');
db.close();
db.execute('INSERT INTO city (name,continent,temp_f,temp_c,condition_id) VALUES (?,?,?,?,?)', importName, importContinent, importTempF, importTempC, dbConditionId);
db.execute('INSERT INTO city (name,continent,temp_f,temp_c,condition_id) VALUES (?,?,?,?,?)', importName, importContinent, importTempF, importTempC, dbConditionId);
var lastID = db.lastInsertRowID; // presumes `city` has an auto-increment column();
// you get a bunch of data, maybe from the network, to save in the db
var playlist = [];
playlist.push({disc:'Leon Live', artist:'Leon Russell', comment:'Gospel, blues and rock rolled into one'});
playlist.push({disc:'Animal Notes', artist:'Crack the Sky', rating:'Obscure but rocking'});
// etc.
var db = Ti.Database.open('myDatabase');
db.execute('BEGIN'); // begin the transaction
for(var i=0, var j=playlist.length; i < j; i++) {
var item = playlist[i];
db.execute('INSERT INTO albums (disc, artist, rating) VALUES (?, ?, ?)', item.disc, item.artist, item.comment);
}
db.execute('COMMIT');
db.close();
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'yourfile.txt');
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'yourfile.txt');
var contents = f.read();
Ti.API.info('Output as a blob: '+contents); // useful if contents are binary
Ti.API.info('Output text of the file: '+contents.text);
Ti.API.info('Output the file\'s MIME type: '+contents.mimeType); // e.g. text/plain
var log = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'logfile.txt');
log.write('My log file\n');
for(var i=0; i<10; i++) {
log.write(i+': new log statement\n', true); // Boolean argument causes write() to append
}
alert(log.read().text);
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'nonexistent_file.txt');
if(f.exists()===false) {
// you don't need to do this, but you could...
f.createFile();
}
f.write('writing to the file would be enough to create it');
var oldfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'old.txt');
var newfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'new.txt');
newfile.write(oldfile.read()); // both old.txt and new.txt exist now
// get a handle to the directory
var dir = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory);
// create our starting file
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'original_name.txt');
f.write('foo');
// rename the file
var success = f.rename('fluffernutter.txt');
if(success==true) {
Ti.API.info('File has been renamed');
} else {
Ti.API.info('File has NOT been renamed');
}
// output a directory listing
Ti.API.info('Dir list after rename = ' + dir.getDirectoryListing());
// But f still points to the old, now non-existent file
Ti.API.info('f.name = ' + f.name); // = 'original_name.txt'
f.write('new information');
Ti.API.info('f contains: ' + f.read());
Ti.API.info('Dir list after writing to f again = ' + dir.getDirectoryListing());
// grab a handle to the copy
var newf = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'fluffernutter.txt');
Ti.API.info('The copy is named ' + newf.name); // = 'fluffernutter.txt'
Ti.API.info(newf.read()); // = 'foo'
Ti.Network.HTTPClient skeleton
var url = "https://www.";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this function is called when data is returned from the server and available for use
// this.responseText holds the raw text return of the message (used for text/JSON)
// this.responseXML holds any returned XML (including SOAP)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
alert('success');
},
onerror: function(e) {
// this function is called when an error occurs, including a timeout
Ti.API.debug(e.error);
alert('error');
},
timeout:5000 /* in milliseconds */
});
xhr.open("GET", url);
xhr.send(); // request is actually sent with this statement
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function(e) {
//handle response, which at minimum will be an HTTP status code
};
xhr.open('POST','http://www./post.php');
xhr.send({
title:'My awesome blog',
body:'Today I met Susy at the laundromat. Best day EVAR\!'
});
var client = Ti.Network.createHTTPClient();
client.open('POST','http:///files/new');
client.setRequestHeader('Content-Type','text/csv');
client.send('foo,bar,foo,bar');
var url = "http:///json.txt";
var json;
var xhr = Ti.Network.createHTTPClient({
onload: function() {
// parse the retrieved data, turning it into a JavaScript object
json = JSON.parse(this.responseText);
// ...
}
});