//Start.java
import java.awt.*
import javax.swing.*
class Start{
public static void main(String [] args){
DateFrame frame=new DateFrame()
frame.setLocationRelativeTo(frame)
frame.setResizable(false)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setVisible(true)
}
}
//DateInfo.java
import java.util.*
public class DateInfo{
private int mYear, mMonth
private int mDayOfMonth, mFristWeek
public DateInfo(int year, int month) throws DateException{
mYear = year
if (month <0 || month >12){
throw (new DateException())
}
mMonth = month
mDayOfMonth = getDayOfMonth(mYear, mMonth)
mFristWeek = getFristWeek(mYear, mMonth)
}
private int getDayOfMonth(int year, int month){
int[][] ary = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}}
return (ary[isLeapYear(year)][month])
}
private int isLeapYear(int year){
if (year % 4 == 0 &&year % 100 != 0 ||year % 400 == 0){
return (1)
}
else{
return (0)
}
}
private int getFristWeek(int year, int month){
java.util.Calendar cal = Calendar.getInstance()
cal.set(year, month - 1, 1)
return (cal.get(Calendar.DAY_OF_WEEK) - 1)
}
public String toString(){
String str
str = "\t\t" + mYear + "年" + mMonth + "月\n"
str += "日\t一\t二\t三\t四\t五\t六\n"
int i
for (i = 1i <= mFristWeeki++){
str += " \t"
}
for (int j = 1j <= mDayOfMonthj++, i++){
str +=j+"\t"
if (i % 7 == 0){
str += "\n"
}
}
return (str)
}
}
//DateFrame.java
import java.awt.*
import java.awt.event.*
import javax.swing.*
import java.util.Calendar
class DateFrame extends JFrame implements Runnable{
Calendar date=Calendar.getInstance()
String[] str={"1","2","枣禅3","4","5","6","7","8","9","10","11","12"}
JLabel lblYear=new JLabel("年 "弯岩胡)
JLabel lblMonth=new JLabel("月 ")
JLabel lblDate=new JLabel("现在的时间是:")
JLabel lblShowDate=new JLabel()
// javax.swing.JTextField trxt =new JTextField(10)
// trxt.setHorizontalAlignment(JTextField.RIGHT) //设置文本从右边输入
JComboBox cboMonth=new JComboBox(str)
JComboBox cboYear=new JComboBox()
JTextArea txaShow=new JTextArea()
JPanel pnlNorth=new JPanel()
JPanel pnlSOUTH=new JPanel()
JButton btnShow=new JButton("显示")
JButton btnClose=new JButton("关闭")
JScrollPane jsp=new JScrollPane(txaShow)
Container c=this.getContentPane()
public DateFrame(){
Thread thread=new Thread(this)
thread.start()
this.setTitle("玩玩日历拉!!!")
this.setSize(300,260)
for (int i = 1990i<=2025i++) {
cboYear.addItem(""+i)
}
cboYear.setSelectedItem(""+(date.get(Calendar.YEAR)))
cboMonth.setSelectedItem(""+(date.get(Calendar.MONTH)+1))
pnlNorth.add(cboYear)
txaShow.setTabSize(4) //设置tab键的距离
txaShow.setForeground(Color.GREEN)
pnlNorth.add(lblYear)
pnlNorth.add(cboMonth)
pnlNorth.add(lblMonth)
pnlNorth.add(lblDate)
pnlNorth.add(lblShowDate)
c.add(pnlNorth,BorderLayout.NORTH)
c.add(jsp)
pnlSOUTH.add(btnShow)
pnlSOUTH.add(btnClose)
c.add(pnlSOUTH,BorderLayout.SOUTH)
btnShow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int year=Integer.parseInt((String)cboYear.getSelectedItem())
int month=Integer.parseInt((String)cboMonth.getSelectedItem())
try {
DateInfo date=new DateInfo(year,month)
txaShow.setText(""+date)
}
catch (DateException ex) {
ex.printStackTrace()
}
}
})
btnClose.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0)
}
})
}
public void run(){
try {
while(true){
Thread.sleep(1000)
int hour=date.get(Calendar.HOUR)
int minute=date.get(Calendar.MINUTE)
int second=date.get(Calendar.SECOND)
String str=hour+":"+minute+":"+second
lblShowDate.setText(str)
//this.repaint()
}
}
catch (Exception ex) {
ex.printStackTrace()
}
}
}
//DateException.java
public class DateException extends Exception{
public DateException(){
super("日期数据不合法.")
}
}
package TestCalendarimport java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
public class TestCalendar {
public static void main(String[] args) {
Calendar cl=Calendar.getInstance()
System.out.println(cl.get(Calendar.YEAR)+"年"+cl.get(cl.MONTH)+"月"+
cl.get(cl.DAY_OF_MONTH)+"日"+cl.get(cl.HOUR)+":"+cl.get(cl.MINUTE)+":"+cl.get(cl.SECOND))
cl.add(cl.DAY_OF_YEAR,315)
System.out.println(cl.get(Calendar.YEAR)+"年"+cl.get(cl.MONTH)+"月"+
cl.get(cl.DAY_OF_MONTH)+"日"+cl.get(cl.HOUR)+":"+cl.get(cl.MINUTE)+":"+cl.get(cl.SECOND))
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd"培羡笑配含)
SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年派蔽MM月dd日")
try{
Date d=sdf2.parse("2012年05月15日")
System.out.println(sdf2.format(d))
}catch(Exception e){
e.printStackTrace()
}
}
}
因为日历是系统自带的,所以读写它一定要申请权限,也拆衫就是在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~")
//插入hoohbood@gmail.com这个账户
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工程,查看效果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)