‘壹’ android怎样实现日历年视图
因为日历是系统自带的,所以读写它一定要申请权限,也就是在AndroidManifest.xml加如下两行代码(一个读一个写):
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
Android中日历用了三个URL,分别是日历用户的URL,事件的URL,事件提醒URL,三个URL在Android2.1之前是如下的样子:
calanderURL = "content://calendar/calendars";
calanderEventURL = "content://calendar/events";
calanderRemiderURL= "content://calendar/reminders";
但是在Android2.2版本以后,三个URL有了改变,变成如下的样子:
calanderURL = "content://com.android.calendar/calendars";
calanderEventURL = "content://com.android.calendar/events";
calanderRemiderURL = "content://com.android.calendar/reminders";
简单的Demo,按照我的步骤一步一步的来:
第一步:新建一个Android工程命名为CalendarDemo.
第二步:修改main.xml布局文件,增加了三个按钮,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>困亏
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/readUserButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get a User"
/>
<Button
android:id="@+id/readEventButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get a Event"
/>
<Button
android:id="@+id/writeEventButton"
android:layout_width="旅尺腔fill_parent"
android:layout_height="wrap_content"
android:text="Input a Event"
/拆衫>
</LinearLayout>
第三步:修改主核心程序CalendarDemo.java,代码如下:
package com.tutor.calendardemo;
import java.util.Calendar;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class CalendarDemo extends Activity implements OnClickListener {
private Button mReadUserButton;
private Button mReadEventButton;
private Button mWriteEventButton;
private static String calanderURL = "";
private static String calanderEventURL = "";
private static String calanderRemiderURL = "";
//为了兼容不同版本的日历,2.2以后url发生改变
static{
if(Integer.parseInt(Build.VERSION.SDK) >= 8){
calanderURL = "content://com.android.calendar/calendars";
calanderEventURL = "content://com.android.calendar/events";
calanderRemiderURL = "content://com.android.calendar/reminders";
}else{
calanderURL = "content://calendar/calendars";
calanderEventURL = "content://calendar/events";
calanderRemiderURL = "content://calendar/reminders";
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupViews();
}
private void setupViews(){
mReadUserButton = (Button)findViewById(R.id.readUserButton);
mReadEventButton = (Button)findViewById(R.id.readEventButton);
mWriteEventButton = (Button)findViewById(R.id.writeEventButton);
mReadUserButton.setOnClickListener(this);
mReadEventButton.setOnClickListener(this);
mWriteEventButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v == mReadUserButton){
Cursor userCursor = getContentResolver().query(Uri.parse(calanderURL), null,
null, null, null);
if(userCursor.getCount() > 0){
userCursor.moveToFirst();
String userName = userCursor.getString(userCursor.getColumnIndex("name"));
Toast.makeText(CalendarDemo.this, userName, Toast.LENGTH_LONG).show();
}
}else if(v == mReadEventButton){
Cursor eventCursor = getContentResolver().query(Uri.parse(calanderEventURL), null,
null, null, null);
if(eventCursor.getCount() > 0){
eventCursor.moveToLast();
String eventTitle = eventCursor.getString(eventCursor.getColumnIndex("title"));
Toast.makeText(CalendarDemo.this, eventTitle, Toast.LENGTH_LONG).show();
}
}else if(v == mWriteEventButton){
//获取要出入的gmail账户的id
String calId = "";
Cursor userCursor = getContentResolver().query(Uri.parse(calanderURL), null,
null, null, null);
if(userCursor.getCount() > 0){
userCursor.moveToFirst();
calId = userCursor.getString(userCursor.getColumnIndex("_id"));
}
ContentValues event = new ContentValues();
event.put("title", "与苍井空小-姐动作交流");
event.put("description", "Frankie受空姐邀请,今天晚上10点以后将在Sheraton动作交流.lol~");
//插入[email protected]这个账户
event.put("calendar_id",calId);
Calendar mCalendar = Calendar.getInstance();
mCalendar.set(Calendar.HOUR_OF_DAY,10);
long start = mCalendar.getTime().getTime();
mCalendar.set(Calendar.HOUR_OF_DAY,11);
long end = mCalendar.getTime().getTime();
event.put("dtstart", start);
event.put("dtend", end);
event.put("hasAlarm",1);
Uri newEvent = getContentResolver().insert(Uri.parse(calanderEventURL), event);
long id = Long.parseLong( newEvent.getLastPathSegment() );
ContentValues values = new ContentValues();
values.put( "event_id", id );
//提前10分钟有提醒
values.put( "minutes", 10 );
getContentResolver().insert(Uri.parse(calanderRemiderURL), values);
Toast.makeText(CalendarDemo.this, "插入事件成功!!!", Toast.LENGTH_LONG).show();
}
}
}
第四步:在AndroidManifest.xml中申请权限,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutor.calendardemo"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".CalendarDemo"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
</manifest>
第五步:运行上述Android工程,查看效果:
‘贰’ Android 怎么获取当前的时间戳
Android获取当前时间代码
//需要引用的
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
//详细代码
java.util.Date currentdate = new java.util.Date();//当前时间
//long i = (currentdate.getTime()/1000-timestamp)/(60);
//System.out.println(currentdate.getTime());
//System.out.println(i);
Timestamp now = new Timestamp(System.currentTimeMillis());//获取系统当前时间
System.out.println("now-->"+now);//返回结果精确到毫秒。
时间戳转日期
int timestamp = 1310457552; //将这个时间戳转为日期
return getTime(timestamp);
定义getTime, getDate, IntToLong
public static String getTime(int timestamp){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time= null;
try {
String str = sdf.format(new Timestamp(IntToLong(timestamp)));
time = str.substring(11, 16);
String month = str.substring(5, 7);
String day = str.substring(8,10 );
time =getDate(month, day)+ time;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return time;
}
public static String getDate(String month,String day){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
java.util.Date d = new java.util.Date(); ;
String str = sdf.format(d);
String nowmonth = str.substring(5, 7);
String nowday = str.substring(8,10 );
String result = null;
int temp = Integer.parseInt(nowday)-Integer.parseInt(day);
switch (temp) {
case 0:
result="今天";
break;
case 1:
result = "昨天";
break;
case 2:
result = "前天";
break;
default:
StringBuilder sb = new StringBuilder();
sb.append(Integer.parseInt(month)+"月");
sb.append(Integer.parseInt(day)+"日");
result = sb.toString();
break;
}
return result;
}
//java Timestamp构造函数需传入Long型
public static long IntToLong(int i){
long result = (long)i;
result*=1000;
return result;
}
‘叁’ android 基本文件操作命令
ADB (Android Debug Bridge)
说明:下面一些命令需要有root权限才能执行成功
快速启动dos窗口执行adb:
1. adb.exe所在路径添加到系统环境变量中
2. 配置快捷键启动dos
进入C:\WINDOWS\system32目录下,找到cmd.exe.
右击菜单 "发送到" -> 桌面快捷方式。
在桌面上右击"快捷方式 到 cmd.exe" -> "属性" -> "快捷方式"页
-> 光标高亮"快捷键" -> 按下自定义快捷键 (如:Ctrl + Alt + Z)
任何情况下,按下Ctrl + Alt + Z启动dos窗口就可以执行adb命令了
-----------查看设备连接状态 系列-----------
adb get-serialno 获取设备的ID和序列号serialNumber
adb devices 查询当前计算机上连接那些设备(包括模拟器和手机),输出格式: [serialNumber] [state]
adb get-state 查看模拟器/设施的当前状态.
说明:
序列号[serialNumber]——由adb创建的一个字符串,这个字符串通过自己的控制端口<type>-<consolePort>
唯一地识别一个模拟器/设备实例。一个序列号的例子: emulator-5554
-----------发送命令到设备 系列-----------
adb [-d|-e|-s <serialNumber>] <command>
-d 发送命令给usb连接的设备
-e 发送命令到模拟器设备
-s <serialNumber> 发送命令到指定设备
如启动手机设备shell: adb -d shell
adb forward <local> <remote>发布端口,可以设置任意的端口号,
做为主机向模拟器或设备的请求端口。如:adb forward tcp:5555 tcp:8000
adb reboot 重启手机
adb remount 将system分区重新挂载为可读写分区
adb kill-server 终止adb服务进程
adb start-server 重启adb服务进程
adb root 已root权限重启adb服务
adb wait-for-device 在模拟器/设备连接之前把命令转载在adb的命令器中
adb jdwp 查看指定的设施的可用的JDWP信息.
可以用 forward jdwp:<pid> 端口映射信息来连接指定的JDWP进程.例如:
adb forward tcp:8000 jdwp:472
jdb -attach localhost:8000
adb shell am 命令可以启动应用程序
adb shell input text <string> 向设备输入文本(光标所在的文本框)
adb shell input keyevent <event_code> 向设备发送按键事件
如:
在编辑短信时,往文本框输入文本:adb shell input text "hello"
向手机发送键值回Home:adb shell input keyevent 3
event_code 参考view/KeyEvent.java中的 KEYCODE_*
public static final int KEYCODE_SOFT_LEFT = 1;
public static final int KEYCODE_SOFT_RIGHT = 2;
public static final int KEYCODE_HOME = 3;
public static final int KEYCODE_BACK = 4;
public static final int KEYCODE_CALL = 5;
public static final int KEYCODE_ENDCALL = 6;
-----------安装卸载 系列-----------
adb install [-l] [-r] <file> - push this package file to the device and install it
('-l' means forward-lock the app)
('-r' means reinstall the app, keeping its data)
adb uninstall [-k] <package> - remove this app package from the device
('-k' means keep the data and cache directories)
如:
adb install d:\hello.apk
adb unstall com.huawei.hello
说明:如果带-r选项重新安装apk时,安装在 /data/local/tmp/目录下,手机重启后还是使用原来的apk.
-----------文件操作 系列-----------
adb push <local> <remote> - file/dir to device
adb pull <remote> <local> - file/dir from device
-----------基本linux shell命令 系列-----------
adb shell [command]
ls 列出目录下的文件和文件夹
cd 切换目录
rm 删除目录和文件
cat 查看文件内容
ps 可以看那个进程再跑
ps -x [PID] 查看单个进程的状态
top 可以看那个进程的占用率最高
su 切换到root用户
kill [pid] 杀死一个进程
chmod 777 <file> 修改该文件为可执行权限
详细使用情况可以登录一台Linux服务器在shell下查看帮助手册, man <command>
-----------查看系统状态和信息 系列-----------
adb shell procrank 查询各进程内存使用情况
adb shell service list 查看services信息
adb shell cat /proc/meminfo 查看当前的内存情况
adb shell cat /proc/cpuinfo 查看CPU信息(硬件)
adb shell cat /proc/iomem 查看IO内存分区
adb shell getprop 列出系统所有属性
adb shell getprop | findstr "gsm" 列出包含gsm的属性
adb shell setprop <key> <value> 修改系统属性
adb shell sqlite3 可以执行sql语句查看数据库信息, 具体使用情况待调查
-----------Log 系列-----------
adb logcat [ <filter-spec> ] - View device log
1~~~~~~~~~~~查看可用日志缓冲区:
adb logcat -b radio — 查看缓冲区的相关的信息.
adb logcat -b events — 查看和事件相关的的缓冲区.
adb logcat -b main — 查看主要的日志缓冲区
2~~~~~~~~~~~过滤日志输出:
过滤器语句按照下面的格式描tag:priority ... , tag 表示是标签, priority 是表示标签的报告的最低等级
adb logcat *:W 显示优先级为warning或更高的日志信息
adb logcat ActivityManager:I MyApp:D *:S
日志的标签是系统部件原始信息的一个简要的标志。(比如:“View”就是查看系统的标签).
优先级有下列集中,是按照从低到高顺利排列的:
V — Verbose (lowest priority)
D — Debug
I — Info
W — Warning
E — Error
F — Fatal
S — Silent (highest priority, on which nothing is ever printed)
如果你电脑上运行logcat ,相比在远程adbshell端,你还可以为环境变量ANDROID_LOG_TAGS :输入一个参数来设置默认的过滤
export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"
需要注意的是ANDROID_LOG_TAGS 过滤器如果通过远程shell运行logcat 或用adb shell logcat 来运行模拟器/设备不能输出日志.
3~~~~~~~~~~~控制日志输出格式:
日志信息包括了许多元数据域包括标签和优先级。可以修改日志的输出格式,所以可以显示出特定的元数据域。可以通过 -v 选项得到格式化输出日志的相关信息.
brief — Display priority/tag and PID of originating process (the default format).
process — Display PID only.
tag — Display the priority/tag only.
thread — Display process:thread and priority/tag only.
raw — Display the raw log message, with no other metadata fields.
time — Display the date, invocation time, priority/tag, and PID of the originating process.
long — Display all metadata fields and separate messages with a blank lines.
当启动了logcat ,你可以通过-v 选项来指定输出格式:
[adb] logcat [-v <format>]
下面是用 thread 来产生的日志格式:
adb logcat -v thread
需要注意的是你只能-v 选项来规定输出格式 option.
4~~~~~~~~~~~Logcat命令列表
-b <buffer> 加载一个可使用的日志缓冲区供查看,比如event 和radio . 默认值是main 。具体查看Viewing Alternative Log Buffers.
-c 清楚屏幕上的日志.
-d 输出日志到屏幕上.
-f <filename> 指定输出日志信息的<filename> ,默认是stdout .
-g 输出指定的日志缓冲区,输出后退出.
-n <count> 设置日志的最大数目<count> .,默认值是4,需要和 -r 选项一起使用。
-r <kbytes> 每<kbytes> 时输出日志,默认值为16,需要和-f 选项一起使用.
-s 设置默认的过滤级别为silent.
-v <format> 设置日志输入格式,默认的是brief 格式,要知道更多的支持的格式,参看Controlling Log Output Format
adb bugreport - return all information from the device
that should be included in a bug report.
adb shell dmesg 查询内核缓冲区信息
adb shell mpstate 各类信息,比如进程信息,内存信息,进程是否异常,kernnel的log等
adb shell mpcrash
adb shell mpsys 查询所有service的状态
-----------其他 -----------
模拟器使用镜像sdcard
用SDK里的mksdcard工具来创建FAT32磁盘镜像并在模拟器启动时加载它。这样创建镜像:? mksdcard <size> <file>,
比如我要创建一个64M的SD卡模拟文件,文件路径是在D:\workspace\sdcard.img
mksdcard 64000000 D:\workspace\sdcard.img
Emulator –sdcard D:\workspace\sdcard.img
或者在eclipse的run菜单的open run dialog对话框中配置启动参数。
#top
Usage: top [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]
-m num Maximum number of processes to display.
-n num Updates to show before exiting.
-d num Seconds to wait between updates.
-s col Column to sort by (cpu,vss,rss,thr).
-t Show threads instead of processes.
-h Display this help screen.
********* simple selection ********* ********* selection by list *********
-A all processes -C by command name
-N negate selection -G by real group ID (supports names)
-a all w/ tty except session leaders -U by real user ID (supports names)
-d all except session leaders -g by session OR by effective group name
-e all processes -p by process ID
T all processes on this terminal -s processes in the sessions given
a all w/ tty, including other users -t by tty
g OBSOLETE -- DO NOT USE -u by effective user ID (supports names)
r only running processes U processes for specified users
x processes w/o controlling ttys t by tty
*********** output format ********** *********** long options ***********
-o,o user-defined -f full --Group --User --pid --cols --ppid
-j,j job control s signal --group --user --sid --rows --info
-O,O preloaded -o v virtual memory --cumulative --format --deselect
-l,l long u user-oriented --sort --tty --forest --version
-F extra full X registers --heading --no-heading --context
********* misc options *********
-V,V show version L list format codes f ASCII art forest
-m,m,-L,-T,H threads S children in sum -y change -l format
-M,Z security data c true command name -c scheling class
-w,w wide output n numeric WCHAN,UID -H process hierarchy
netstat -ano 查看网络连状态
显示协议统计信息和当前 TCP/IP 网络连接。
NETSTAT [-a] [-b] [-e] [-n] [-o] [-p proto] [-r] [-s] [-v] [interval]
-a 显示所有连接和监听端口。
-b 显示包含于创建每个连接或监听端口的
可执行组件。在某些情况下已知可执行组件
拥有多个独立组件,并且在这些情况下
包含于创建连接或监听端口的组件序列
被显示。这种情况下,可执行组件名
在底部的 [] 中,顶部是其调用的组件,
等等,直到 TCP/IP 部分。注意此选项
可能需要很长时间,如果没有足够权限
可能失败。
-e 显示以太网统计信息。此选项可以与 -s
选项组合使用。
-n 以数字形式显示地址和端口号。
-o 显示与每个连接相关的所属进程 ID。
-p proto 显示 proto 指定的协议的连接;proto 可以是
下列协议之一: TCP、UDP、TCPv6 或 UDPv6。
如果与 -s 选项一起使用以显示按协议统计信息,proto 可以是下列协议之一:
IP、IPv6、ICMP、ICMPv6、TCP、TCPv6、UDP 或 UDPv6。
-r 显示路由表。
-s 显示按协议统计信息。默认地,显示 IP、
IPv6、ICMP、ICMPv6、TCP、TCPv6、UDP 和 UDPv6 的统计信息;
-p 选项用于指定默认情况的子集。
-v 与 -b 选项一起使用时将显示包含于
为所有可执行组件创建连接或监听端口的
组件。
interval 重新显示选定统计信息,每次显示之间
暂停时间间隔(以秒计)。按 CTRL+C 停止重新
显示统计信息。如果省略,netstat 显示当前
配置信息(只显示一次)
pm
usage: pm [list|path|install|uninstall]
pm list packages [-f]
pm list permission-groups
pm list permissions [-g] [-f] [-d] [-u] [GROUP]
pm list instrumentation [-f] [TARGET-PACKAGE]
pm list features
pm path PACKAGE
pm install [-l] [-r] [-t] [-i INSTALLER_PACKAGE_NAME] PATH
pm uninstall [-k] PACKAGE
pm enable PACKAGE_OR_COMPONENT
pm disable PACKAGE_OR_COMPONENT
The list packages command prints all packages. Options:
-f: see their associated file.
The list permission-groups command prints all known
permission groups.
The list permissions command prints all known
permissions, optionally only those in GROUP. Options:
-g: organize by group.
-f: print all information.
-s: short summary.
-d: only list dangerous permissions.
-u: list only the permissions users will see.
The list instrumentation command prints all instrumentations,
or only those that target a specified package. Options:
-f: see their associated file.
The list features command prints all features of the system.
The path command prints the path to the .apk of a package.
The install command installs a package to the system. Options:
-l: install the package with FORWARD_LOCK.
-r: reinstall an exisiting app, keeping its data.
-t: allow test .apks to be installed.
-i: specify the installer package name.
The uninstall command removes a package from the system. Options:
-k: keep the data and cache directories around.
after the package removal.
The enable and disable commands change the enabled state of
a given package or component (written as "package/class").
查看stdout 和stderr
在默认状态下,Android系统有stdout 和 stderr (System.out和System.err )输出到/dev/null ,
在运行Dalvik VM的进程中,有一个系统可以备份日志文件。在这种情况下,系统会用stdout 和stderr 和优先级 I.来记录日志信息
通过这种方法指定输出的路径,停止运行的模拟器/设备,然后通过用setprop 命令远程输入日志
$ adb shell stop
$ adb shell setprop log.redirect-stdio true
$ adb shell start系统直到你关闭模拟器/设备前设置会一直保留,可以通过添加/data/local.prop 可以使用模拟器/设备上的默认设置
UI/软件 试验程序 Monkey
当Monkey程序在模拟器或设备运行的时候,如果用户出发了比如点击,触摸,手势或一些系统级别的事件的时候,
它就会产生随机脉冲,所以可以用Monkey用随机重复的方法去负荷测试你开发的软件.
最简单的方法就是用用下面的命令来使用Monkey,这个命令将会启动你的软件并且触发500个事件.
$ adb shell monkey -v -p your.package.name 500
更多的关于命令Monkey的命令的信息,可以查看UI/Application Exerciser Monkey documentation page.
‘肆’ 如何用Android写一个时间戳编码程序‘
这是我项目中正在用的时间戳,没经过整理,你看下
package com.tianwei.utils;
import android.net.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by GT on 2017/8/22.
* 注:Uinix和Windows时间不同
*/
public class Time {
public void Time() {
}
//格式时间
public static String systemTime(String time) {
SimpleDateFormat sDateFormat = null;
if (time != null && time.length() > 0) {
sDateFormat = new SimpleDateFormat(time);
} else {
sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
}
String date = sDateFormat.format(new java.util.Date());
return date;
}
//无格式时间
public static String systemTime() {
SimpleDateFormat sDateFormat = null;
sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String date = sDateFormat.format(new java.util.Date());
return date;
}
/*
* 将时间戳转换为时间
*/
public static String stampToDate(String s, String time) {
String res;
SimpleDateFormat simpleDateFormat;
if (time == null && time.length() > 0) {
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} else {
simpleDateFormat = new SimpleDateFormat(time);
}
long lt = new Long(s);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}
/*
* 将时间转换为时间戳
*/
public static String dateToStamp(String s) throws ParseException {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = simpleDateFormat.parse(s);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
long ts = date.getTime();
res = String.valueOf(ts);
return res;
}
/**
* 系统时间戳
*/
public static long dataStampDate() {
long s = System.currentTimeMillis();
// long s = new Date().getTime();
// long s = Calendar.getInstance().getTimeInMillis();
return s;
}
/**
* Unix
* 时间戳转换成日期格式
*
* @param timestampString
* @param formats
* @return
*/
public static String timeStampUnixDate(String timestampString, String formats) {
Long timestamp = Long.parseLong(timestampString) * 1000;
String date = new java.text.SimpleDateFormat(formats).format(new java.util.Date(timestamp));
return date;
}
/**
* Unix
* 日期格式字符串转换成时间戳
*
* @param dateStr 字符串日期
* @param format 如:yyyy-MM-dd HH:mm:ss
* @return
*/
public static String dateUinxTimeStamp(String dateStr, String format) {
try {
SimpleDateFormat sdf = null;
if (format != null && format.length() > 0) {
sdf = new SimpleDateFormat(format);
} else {
sdf = new SimpleDateFormat("yyyyMMddhhmmss");
}
return String.valueOf(sdf.parse(dateStr).getTime() / 1000);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 两个时间间的时间戳计算函数
*
* @param beginDate
* @param endDate
* @param f 时间差的形式0:秒,1:分种,2:小时,3:天
* @return long 秒
*/
public static long getDifference(Date beginDate, Date endDate, int f) {
long result = 0;
if (beginDate == null || endDate == null) {
return 0;
}
try {
// 日期相减获取日期差X(单位:毫秒)
long millisecond = endDate.getTime() - beginDate.getTime();
/**
* Math.abs((int)(millisecond/1000)); 绝对值 1秒 = 1000毫秒
* millisecond/1000 --> 秒 millisecond/1000*60 - > 分钟
* millisecond/(1000*60*60) -- > 小时 millisecond/(1000*60*60*24) -->
* 天
* */
switch (f) {
case 0: // second
return (millisecond / 1000);
case 1: // minute
return (millisecond / (1000 * 60));
case 2: // hour
return (millisecond / (1000 * 60 * 60));
case 3: // day
return (millisecond / (1000 * 60 * 60 * 24));
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 计算时间差
*
* @param starTime 开始时间
* @param endTime 结束时间
* @return 返回时间差
* @param返回类型==1----天,时,分。 ==2----时
*/
public String getTimeDifference(String starTime, String endTime) {
String timeString = "";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
Date parse = dateFormat.parse(starTime);
Date parse1 = dateFormat.parse(endTime);
long diff = parse1.getTime() - parse.getTime();
long day = diff / (24 * 60 * 60 * 1000);
long hour = (diff / (60 * 60 * 1000) - day * 24);
long min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
long s = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
long ms = (diff - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000
- min * 60 * 1000 - s * 1000);
// System.out.println(day + "天" + hour + "小时" + min + "分" + s +
// "秒");
long hour1 = diff / (60 * 60 * 1000);
String hourString = hour1 + "";
long min1 = ((diff / (60 * 1000)) - hour1 * 60);
timeString = hour1 + "小时" + min1 + "分";
// System.out.println(day + "天" + hour + "小时" + min + "分" + s +
// "秒");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return timeString;
}
/**
* Java YEAR、MONTH、DAY_OF_MONTH、HOUR加减法,int num +(日期前) -(日期后)
*
* @param num
* @param type
* @return
*/
public static String timeDateCompute(int num, int type) {
// YEAR、MONTH、DAY_OF_MONTH、HOUR 等
Calendar cal = Calendar.getInstance();//使用默认时区和语言环境获得一个日历。
if (type > 6) {
return null;
}
switch (type) {
case 0://年
cal.add(Calendar.YEAR, -num);
break;
case 1://月
cal.add(Calendar.MONTH, -num);
break;
case 2://日
cal.add(Calendar.DAY_OF_MONTH, -num);//取当前日期的前num天.
break;
case 3://时
cal.add(Calendar.HOUR_OF_DAY, -num);
break;
case 4://分
cal.add(Calendar.MINUTE, -num);
break;
case 5://秒
cal.add(Calendar.SECOND, -num);
break;
case 6://周
cal.add(Calendar.WEEK_OF_MONTH, -num);
break;
}
//通过格式化输出日期
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
// SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (type == 0) {
System.out.println("Today is: " + format.format(Calendar.getInstance().getTime()));
}
System.out.println("CutNum is: " + format.format(cal.getTime()));
String CutNum = format.format(cal.getTime());
return CutNum;
}
/**
* 时间日期加减(-前,+后)
*
* @param statTime
* @param ymdhms
* @param type
* @return
*/
public String timeNum(Date statTime, int ymdhms, int type) {
String tn = null;
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
System.out.println("今天的日期:" + df.format(statTime));
System.out.println("两天前的日期:" + df.format(new Date(statTime.getTime() - 2 * 24 * 60 * 60 * 1000)));
System.out.println("三天后的日期:" + df.format(new Date(statTime.getTime() + 3 * 24 * 60 * 60 * 1000)));
switch (type) {
case 0://年
break;
case 1://月
break;
case 2://日
tn = df.format(new Date(statTime.getTime() - ymdhms * 24 * 60 * 60 * 1000));
break;
case 3://时
tn = df.format(new Date(statTime.getTime() - ymdhms * 60 * 60 * 1000));
break;
case 4://分
tn = df.format(new Date(statTime.getTime() - ymdhms * 60 * 1000));
break;
case 5://秒
tn = df.format(new Date(statTime.getTime() - ymdhms * 1000));
break;
}
return tn;
}
/**
* 时间日期加减(-前,+后)
*
* @param statTime
* @param year
* @param month
* @param day
* @param hour
* @param min
* @param sec
* @return
*/
public String timeNumStr(Date statTime, int year, int month, int day, int hour, int min, int sec) {
String tn = null;
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
System.out.println("今天的日期:" + df.format(statTime));
System.out.println("两天前的日期:" + df.format(new Date(statTime.getTime() - 2 * 24 * 60 * 60 * 1000)));
System.out.println("三天后的日期:" + df.format(new Date(statTime.getTime() + 3 * 24 * 60 * 60 * 1000)));
tn = df.format(new Date(statTime.getTime() - day * hour * min * sec * 1000));
return tn;
}
}
‘伍’ android 仿预订日历时间选择(如去哪儿,携程
看标题就知道了,一个日历选择,类似于去哪儿,携程,酒店预订功能
调用方法
package com.fly.caldroid;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Intent;import android.content.res.Configuration;import android.os.Bundle;import android.view.View;import com.wz.caldroid.CalendarCellDecorator;import com.wz.caldroid.CalendarPickerView;import java.util.ArrayList;import java.util.Calendar;import java.util.Collections;import java.util.Date;@SuppressLint("SimpleDateFormat")public class CaldroidActivity extends Activity { private CalendarPickerView calendar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.calendar_activity); Bundle myBundle = getIntent().getExtras(); long seleteTime = myBundle.getLong("selete_time"); final Calendar nextYear = Calendar.getInstance(); nextYear.add(Calendar.MONTH, 3); final Calendar lastYear = Calendar.getInstance(); lastYear.add(Calendar.MONTH, 0); calendar = (CalendarPickerView) findViewById(R.id.calendar_view); Calendar today = Calendar.getInstance(); ArrayList<Date> dates = new ArrayList<Date>(); if (seleteTime>0){
Date d1=new Date(seleteTime); dates.add(d1); }else{
dates.add(today.getTime()); } calendar.setDecorators(Collections.<CalendarCellDecorator>emptyList()); calendar.init(lastYear.getTime(), nextYear.getTime()) // .inMode(CalendarPickerView.SelectionMode.MULTIPLE) // .withSelectedDate(dates.get(0)); initButtonListeners(); } private void initButtonListeners() { calendar.setOnDateSelectedListener(new CalendarPickerView.OnDateSelectedListener() { @Override public void onDateSelected(Date date) {
Intent intent = new Intent(); intent.putExtra("SELETE_DATA_TIME", calendar.getSelectedDate().getTime()); setResult(2, intent); finish(); } @Override public void onDateUnselected(Date date) {
}
}); View titlebar_img_back=findViewById(R.id.titlebar_img_back); titlebar_img_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
finish(); }
}); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); }
}
layout======
calendar_activity
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <RelativeLayout android:id="@+id/title_content_layout" android:layout_width="match_parent" android:layout_height="47.5dp" android:background="@color/big_red"> <TextView android:id="@+id/titlebar_text_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/titlebar_img_back" android:maxEms="8" android:singleLine="true" android:text="选择日历" android:textColor="@color/white" android:textSize="18sp" android:visibility="visible" /> <ImageView android:id="@+id/titlebar_img_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:padding="5dp" android:src="@drawable/back_ic" android:visibility="visible" /> </RelativeLayout> <com.wz.caldroid.CalendarPickerView android:id="@+id/calendar_view" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingBottom="16dp" android:scrollbarStyle="outsideOverlay" android:clipToPadding="false" android:background="#FFFFFF" /></LinearLayout>
在textview上显示时间
package com.fly.caldroid;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.TextView;import java.text.SimpleDateFormat;import java.util.Date;public class MainActivity extends AppCompatActivity { private long seleteTime = 0; private TextView time_choice_view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); time_choice_view = (TextView) findViewById(R.id.time_choice_view); time_choice_view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putLong("selete_time", seleteTime); intent.putExtras(bundle); intent.setClass(MainActivity.this, CaldroidActivity.class); startActivityForResult(intent, 5); }
}); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 5) { if (resultCode == 2) { seleteTime = data.getLongExtra("SELETE_DATA_TIME", 0); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = new Date(seleteTime); String t1 = format.format(d1); if (seleteTime > 0) { time_choice_view.setText(t1); } else { return; }
}
} super.onActivityResult(requestCode, resultCode, data); }
}
‘陆’ 问个关于安卓开发中的时间相减的问题
try {
java.util.Date nowdate = new Date();
java.util.Date setdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse("2014-05-28 18:30:59");
long between = (setdate.getTime() - nowdate.getTime());
boolean result = between < 1000 * 60 * 60;
System.out.println(result);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
‘柒’ 怎么获取android系统服务,如Uri,intent参数等,或者说去哪里查看
android系统服务,如Uri,intent参数
可以在Intent中指定程序要执行的动作(比如:view,edit,dial),以及程序执行到该动作时所需要的资料。都指定好后,只要调用startActivity(),Android系统会自动寻找最符合你指定要求的应用程序,并执行该程序。
★intent大全:
1.从google搜索内容
Intent intent = new Intent();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"searchString")
startActivity(intent);
2.浏览网页
Uri uri =Uri.parse("htt。。。。。。。。om");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
3.显示地图
Uri uri = Uri.parse("geo:38.899533,-77.036476");
Intent it = newIntent(Intent.Action_VIEW,uri);
startActivity(it);
4.路径规划
Uri uri =Uri.parse("http。。。。。。。。。。/maps?
f=dsaddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");
Intent it = newIntent(Intent.ACTION_VIEW,URI);
startActivity(it);
5.拨打电话
Uri uri =Uri.parse("tel:xxxxxx");
Intent it = new Intent(Intent.ACTION_DIAL,uri);
startActivity(it);
6.调用发短信的程序
Intent it = newIntent(Intent.ACTION_VIEW);
it.putExtra("sms_body", "TheSMS text");
it.setType("vnd.android-dir/mms-sms");
startActivity(it);
7.发送短信
Uri uri =Uri.parse("smsto:0800000123");
Intent it = newIntent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "TheSMS text");
startActivity(it);
String body="this is sms demo";
Intent mmsintent = newIntent(Intent.ACTION_SENDTO, Uri.fromParts("smsto",
number, null));
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY,body);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE,true);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT,true);
startActivity(mmsintent);
8.发送彩信
Uri uri =Uri.parse("content://media/external/images/media/23");
Intent it = newIntent(Intent.ACTION_SEND);
it.putExtra("sms_body","some text");
it.putExtra(Intent.EXTRA_STREAM, uri);
it.setType("image/png");
startActivity(it);
StringBuilder sb = new StringBuilder();
sb.append("file://");
sb.append(fd.getAbsoluteFile());
Intent intent = newIntent(Intent.ACTION_SENDTO, Uri.fromParts("mmsto",
number, null));
// Below extra datas are all optional.
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT,subject);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY,body);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI,sb.toString());
intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE,composeMode);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT,exitOnSent);
startActivity(intent);
9.发送Email
Uri uri =Uri.parse("mailto:[email protected]");
Intent it = newIntent(Intent.ACTION_SENDTO, uri);
startActivity(it);
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL,"[email protected]");
it.putExtra(Intent.EXTRA_TEXT, "Theemail body text");
it.setType("text/plain");
startActivity(Intent.createChooser(it,"Choose Email Client"));
Intent it=new Intent(Intent.ACTION_SEND);
String[] tos={"[email protected]"};
String[]ccs={"[email protected]"};
it.putExtra(Intent.EXTRA_EMAIL, tos);
it.putExtra(Intent.EXTRA_CC, ccs);
it.putExtra(Intent.EXTRA_TEXT, "Theemail body text");
it.putExtra(Intent.EXTRA_SUBJECT, "Theemail subject text");
it.setType("message/rfc822");
startActivity(Intent.createChooser(it,"Choose Email Client"));
Intent it = newIntent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "Theemail subject text");
it.putExtra(Intent.EXTRA_STREAM,"file:///sdcard/mysong.mp3");
sendIntent.setType("audio/mp3");
startActivity(Intent.createChooser(it,"Choose Email Client"));
10.播放多媒体
Intent it = new Intent(Intent.ACTION_VIEW);
Uri uri =Uri.parse("file:///sdcard/song.mp3");
it.setDataAndType(uri,"audio/mp3");
startActivity(it);
Uri uri
=Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"1");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
11.uninstall apk
Uri uri =Uri.fromParts("package", strPackageName, null);
Intent it = newIntent(Intent.ACTION_DELETE, uri);
startActivity(it);
12.install apk
Uri installUri = Uri.fromParts("package","xxx", null);
returnIt = newIntent(Intent.ACTION_PACKAGE_ADDED, installUri);
打开照相机
<1>Intent i = new Intent(Intent.ACTION_CAMERA_BUTTON, null);
this.sendBroadcast(i);
<2>long dateTaken = System.currentTimeMillis();
String name = createName(dateTaken) + ".jpg";
fileName = folder + name;
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, fileName);
values.put("_data", fileName);
values.put(Images.Media.PICASA_ID, fileName);
values.put(Images.Media.DISPLAY_NAME, fileName);
values.put(Images.Media.DESCRIPTION, fileName);
values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, fileName);
Uri photoUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
Intent inttPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
inttPhoto.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(inttPhoto, 10);
14.从gallery选取图片
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, 11);
打开录音机
Intent mi = new Intent(Media.RECORD_SOUND_ACTION);
startActivity(mi);
16.显示应用详细列表
Uri uri =Uri.parse("market://details?id=app_id");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
//where app_id is the application ID, findthe ID
//by clicking on your application on Markethome
//page, and notice the ID from the addressbar
刚才找app id未果,结果发现用package name也可以
Uri uri =Uri.parse("market://details?id=");
这个简单多了
17寻找应用
Uri uri =Uri.parse("market://search?q=pname:pkg_name");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
//where pkg_name is the full package pathfor an application
18打开联系人列表
<1>
Intent i = new Intent();
i.setAction(Intent.ACTION_GET_CONTENT);
i.setType("vnd.android.cursor.item/phone");
startActivityForResult(i, REQUEST_TEXT);
<2>
Uri uri = Uri.parse("content://contacts/people");
Intent it = new Intent(Intent.ACTION_PICK, uri);
startActivityForResult(it, REQUEST_TEXT);
19 打开另一程序
Intent i = new Intent();
ComponentName cn = newComponentName("com.yellowbook.android2",
"com.yellowbook.android2.AndroidSearch");
i.setComponent(cn);
i.setAction("android.intent.action.MAIN");
startActivityForResult(i, RESULT_OK);
20.调用系统编辑添加联系人(高版本SDK有效):
Intent it = newIntent(Intent.ACTION_INSERT_OR_EDIT);
it.setType("vnd.android.cursor.item/contact");
//it.setType(Contacts.CONTENT_ITEM_TYPE);
it.putExtra("name","myName");
it.putExtra(android.provider.Contacts.Intents.Insert.COMPANY,
"organization");
it.putExtra(android.provider.Contacts.Intents.Insert.EMAIL,"email");
it.putExtra(android.provider.Contacts.Intents.Insert.PHONE,"homePhone");
it.putExtra(android.provider.Contacts.Intents.Insert.SECONDARY_PHONE,
"mobilePhone");
it.putExtra( android.provider.Contacts.Intents.Insert.TERTIARY_PHONE,
"workPhone");
it.putExtra(android.provider.Contacts.Intents.Insert.JOB_TITLE,"title");
startActivity(it);
21.调用系统编辑添加联系人(全有效):
Intent intent = newIntent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(People.CONTENT_ITEM_TYPE);
intent.putExtra(Contacts.Intents.Insert.NAME, "My Name");
intent.putExtra(Contacts.Intents.Insert.PHONE, "+1234567890");
intent.putExtra(Contacts.Intents.Insert.PHONE_TYPE,Contacts.PhonesColumns.TYPE_MOBILE);
intent.putExtra(Contacts.Intents.Insert.EMAIL, "[email protected]");
intent.putExtra(Contacts.Intents.Insert.EMAIL_TYPE,
Contacts.ContactMethodsColumns.TYPE_WORK);
startActivity(intent);
★intent action大全:
android.intent.action.ALL_APPS
android.intent.action.ANSWER
android.intent.action.ATTACH_DATA
android.intent.action.BUG_REPORT
android.intent.action.CALL
android.intent.action.CALL_BUTTON
android.intent.action.CHOOSER
android.intent.action.CREATE_LIVE_FOLDER
android.intent.action.CREATE_SHORTCUT
android.intent.action.DELETE
android.intent.action.DIAL
android.intent.action.EDIT
android.intent.action.GET_CONTENT
android.intent.action.INSERT
android.intent.action.INSERT_OR_EDIT
android.intent.action.MAIN
android.intent.action.MEDIA_SEARCH
android.intent.action.PICK
android.intent.action.PICK_ACTIVITY
android.intent.action.RINGTONE_PICKER
android.intent.action.RUN
android.intent.action.SEARCH
android.intent.action.SEARCH_LONG_PRESS
android.intent.action.SEND
android.intent.action.SENDTO
android.intent.action.SET_WALLPAPER
android.intent.action.SYNC
android.intent.action.SYSTEM_TUTORIAL
android.intent.action.VIEW
android.intent.action.VOICE_COMMAND
android.intent.action.WEB_SEARCH
android.net.wifi.PICK_WIFI_NETWORK
android.settings.AIRPLANE_MODE_SETTINGS
android.settings.APN_SETTINGS
android.settings.APPLICATION_DEVELOPMENT_SETTINGS
android.settings.APPLICATION_SETTINGS
android.settings.BLUETOOTH_SETTINGS
android.settings.DATA_ROAMING_SETTINGS
android.settings.DATE_SETTINGS
android.settings.DISPLAY_SETTINGS
android.settings.INPUT_METHOD_SETTINGS
android.settings.INTERNAL_STORAGE_SETTINGS
android.settings.LOCALE_SETTINGS
android.settings.LOCATION_SOURCE_SETTINGS
android.settings.MANAGE_APPLICATIONS_SETTINGS
android.settings.MEMORY_CARD_SETTINGS
android.settings.NETWORK_OPERATOR_SETTINGS
android.settings.QUICK_LAUNCH_SETTINGS
android.settings.SECURITY_SETTINGS
android.settings.SETTINGS
android.settings.SOUND_SETTINGS
android.settings.SYNC_SETTINGS
android.settings.USER_DICTIONARY_SETTINGS
android.settings.WIFI_IP_SETTINGS
android.settings.WIFI_SETTINGS
android.settings.WIRELESS_SETTINGS
‘捌’ Android 在一个日期上增加100天得出的日期
Android 在一个日期上增加100天得出的日期
Date 数据类型,Date 变量存储为 IEEE 64 位(8 个字节)浮点数值形式,其可以表示的日期范围从 100 年 1 月 1 日到 9999 年 12 月 31 日,而时间可以从 0:00:00 到 23:59:59。任何可辨认的文本日期都可以赋值给 Date 变量。日期文字须以数字符号 (#) 扩起来,例如,#January 1, 1993# 或 #1 Jan 93#。
‘玖’ 【Android】【数据库】若Cursor中包含的数据‘其数据类型未知’,那我要怎样获取这些数据
把读取的数据存起来就可以了~<pre t="code" l="java"燃郑>ArrayList<HashMap<皮念颂String, Object>> temp = new ArrayList<HashMap<String,Object>>();
if(cursor.moveToFirst()){
do{
HashMap<String, Object> map = new HashMap<String, Object>();
String name = cursor.getString(cursor.getColumnIndex("fromuser"));
String toname = cursor.getString(cursor.getColumnIndex("touser"));
String content = cursor.getString(cursor.getColumnIndex("content"));
String date = cursor.getString(cursor.getColumnIndex("date"));
String type = cursor.getString(cursor.getColumnIndex("高行type"));
map.put("fromuser", name);
//其他数据同
temp.add(map);
}while(cursor.moveToNext());
}
//读取数据
String name1 = temp.get(1).get("name").toString();
‘拾’ 如何将android时间戳转换成时间
时间戳就是如1377216000000 这种格式我们在mysql数据库中会经常用到把时间转换成时间戳或把时间戳转换成日期格式了,下面我来介绍安卓中时间戳操作转换方法。
一、原理
时间戳的原理是把时间格式转为十进制格式,这样就方便时间的计算。好~ 直接进入主题。(下面封装了一个类,有需要的同学可以参考或是直接Copy 就可以用了。)
如: 2013年08月23日 转化后是 1377216000000
二、步骤
1、创建 DateUtilsl类。
代码如下 复制代码
importjava.text.ParseException;
importjava.text.SimpleDateFormat;
importjava.util.Date;
/*
* @author Msquirrel
*/
public class DateUtils {
privateSimpleDateFormat sf = null;
/*获取系统时间 格式为:"yyyy/MM/dd "*/
public static String getCurrentDate() {
Date d = newDate();
sf = newSimpleDateFormat("yyyy年MM月dd日");
returnsf.format(d);
}
/*时间戳转换成字符窜*/
public static String getDateToString(long time) {
Date d = newDate(time);
sf = newSimpleDateFormat("yyyy年MM月dd日");
returnsf.format(d);
}
/*将字符串转为时间戳*/
public static long getStringToDate(String time) {
sdf = newSimpleDateFormat("yyyy年MM月dd日");
Date date = newDate();
try{
date = sdf.parse(time);
} catch(ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
returndate.getTime();
}
2、在对应使用的地方调用就可以了。
代码如下 复制代码
DateUtils.getCurrentDate(); //获取系统当前时间
DateUtils.getDateToString(时间戳); //时间戳转为时间格式
DateUtils.getStringToDate("时间格式");//时间格式转为时间戳