【网学网提醒】:文章导读:在新的一年中,各位网友都进入紧张的学习或是工作阶段。网学会员整理了Android学习笔记总结初学者必看的相关内容供大家参考,祝大家在新的一年里工作和学习顺利!
Android学习笔记总结
第一步:
Android(1)-在Windows下搭建Android开发环境,以及HelloWorld
程序 搭建Android的开发环境,以及写一个简单的示例
程序 ???
在Windows下搭建Android开发环境Android项目的目录结构说明写一个简单的HelloWorld
程序 一、在Windows下搭建Android开发环境1、安装JDK(JavaDevelopmentKit)download.java.net/jdk6/
2、安装AndroidSDKdeveloper.android/sdk
3、安装Eclipseeclipse.org/
4、打开Eclipse,并安装其Android插件(ADT)打开菜单"Help"->"InstallNewSoftware",在"AvailabeSoftware"中加入地址dl-ssl.google/android/eclipse/,然后安装ADT(AndroidDevelopmentTools)
5、新建Android项目"New"->AndroidProject,ProjectName-项目名称;BuildTarget-编译项目的SDK版本;Applicationname-程序名称;Packagename-包名;MinSDKVersion-
程序所支持的最低SDK版本代号(2对应1.1,3对应1.5,4对应1.6)
6、运行Android项目打开菜单"Run"->"RunConfigurations"->Newlaunchconfiguration,设置启动项目名称,在Android选项卡中选择启动项目,在Target选项卡中设置模拟器
7、创建/使用模拟SD卡创建SD卡,运行类似如下命令:mksdcard-lsdcard512Md:\android\sdcard.img模拟器中使用SD卡,在项目配置的Target选项卡的"AdditionalEmulatorCommandLineOptions"框中输入类似如下参数:-sdcardd:\android\sdcard.img
8、配置模拟器运行类似如下命令:androidcreateavd--nameandroid15--target2。或者直接在菜单"Window"->"AndroidAVDManager"中配置模拟器
9、浏览模拟SD卡中的内容调试
程序,在DDMS中选择"FileExplorer",在其中的sdcard目录下就是模拟SD卡中的内容
10、查看日志LogCatWindow->ShowView->Other->Android->LogCat
11、在模拟器中安装/卸载apk安装apk运行类似如下命令:adbinstallname.apk;卸载apk运行类似如下命令:adbuninstallpackagename(注:这里的参数是需要卸载的包名)
12、反编译Android
程序解压apk文件,取出其中的classes.dex文件,运行类似如下命令:dexdump.exe-dclasses.dex>dump.txt(其意思是将classes.dexdump出来,并将反编译后的代码保存到指定的文本文件中)
13、人品不好是出现的某些错误的解决办法如果出现类似如下的错误等noclassfilesspecifiedConversiontoDalvikformatfailedwitherror1解决办法:Project->Clean出现AndroidSDKContentLoader60%(一直卡在60%)解决办法:Project->去掉BuildAutomatically前面的勾
14、查看SDK源代码先想办法搞到源代码,如这个地址digginmobile/android.
asp,然后将其解压到SDK根路径下的sources文件夹内即可
二、Android项目
的目录结构1、src-用于放置源程序2、gen-自动生成R.java文件,用于引用资源文件(即res目录下的数据)3、assets-用于放置原始文件,Android不会对此目录下的文件做任何处理,这是其与res目录不同的地方4、res/drawable-用于放置
图片之类的资源;res/layout-用于放置布局用的xml文件;res/values-用于放置一些常量数据5、AndroidManifest.xml-Android程序的清单文件,相当于配置文件,配置应用
程序名称、图标、Activity、Service、Receiver等
三、HelloWorld
程序1、res/layout/main.xml
代码 引用资源文件内字符串资源的方式:指定的资源名称前加前缀,@string/-->
2、res/values/strings.xml
代码layout直接调用values中的字符串编程方式调用values中的字符串webabcd_hello
3、res/drawable目录下放置一个名为icon.png的图片文件
4、AndroidManifest.xml
代码
5、Main.java
代码packagecom.webabcd.hello;
importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.LinearLayout;importandroid.widget.TextView;
publicclassMainextendsActivity{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);
//将指定的布局文件作为Activity所显示的内容setContentView(R.layout.main);
//动态地在指定的容器控件上添加新的控件TextViewtxt=newTextView(this);txt.setText("动态添加控件");//setContentView(txt);((LinearLayout)this.findViewById(R.id.layout)).addView(txt);
//引用资源文件内的内容作为输出内容TextViewtxt1=(TextView)this.findViewById(R.id.txt);t
xt1.setText(this.getString(R.string.hello2));}}
Android(2)-布局(Layout)和菜单(Menu)
介绍在Android中各种布局的应用,以及菜单效果的实现
?
各种布局方式的应用,FrameLayout,LinearLayout,TableLayout,AbsoluteLayout,RelativeLayout
?
为指定元素配置上下文菜单,为应用程序配置选项菜单,以及多级菜单的实现
1、各种布局方式的演示res/layout/main.xml
代码
FrameLayout内的元素一层覆盖一层地显
ht="1"android:layout_height="wrap_content"android:text="行1列3"/>
android:layout_width="fill_parent">
res/values/strings.xml
HelloLayoutwebabcd_layout
Main.java
代码
packagecom.webabcd.layout;
importandroid.app.Activity;importandroid.os.Bundle;
publicclassMainextendsActivity{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);}}
2、上下文菜单,选项菜单,子菜单res/layout/main.xml
代码
res/values/strings.xml
代码 version="1.0"encoding="utf-8"?>HelloContextMenuHelloContextSubMenuwebabcd_menu
Main.java
代码
packagecom.webabcd.menu;
importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.ContextMenu;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.SubMenu;importandroid.view.View;importandroid.view.ContextMenu.ContextMenuInfo;importandroid.widget.TextView;importandroid.widget.Toast;
//演示两种菜单的实现方式:上下文菜单(通过在某元素上长按,来呼出菜单)和选项菜单(通过按手机上的菜单按钮,来呼出菜单)publicclassMainextendsActivity{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
//为R.id.txt1注册一个上下文菜单(在此TextView上长按,则会呼出上下文菜单)//具体呼出的菜单内容需要重写onCreateContextMenu来创建TextViewtxt1=(TextView)this.findViewById(R.id.txt1);this.registerForContextMenu(txt1);
//为R.id.txt2注册一个上下文菜单TextViewtxt2=(TextView)this.findViewById(R.id.txt2);this.registerForContextMenu(txt2);}
//重写onCreateContextMenu用以创建上下文菜单//重写onContextItemSelected用以响应上下文菜单@OverridepublicvoidonCreateContextMenu(ContextMenumenu,Viewv,ContextMenuInfomenuInfo){super.onCreateContextMenu(menu,v,menuInfo);
//创建R.id.txt1的上下文菜单if(v==(TextView)this.findViewById(R.id.txt1)){
//ContextMenu.setIcon()-设置菜单的图标//ContextMenu.setHeaderTitle()-设置菜单的标题
menu.setHeaderIcon(R.drawable.icon01);menu.setHeaderTitle("我是菜单");//用ContextMenu.add()来增加菜单项,返回值为MenuItem//第一个参数:组ID//第二个参数:菜单项ID//第三个参数:顺序号//第四个参数:菜单项上显示的内容menu.add(1,0,0,"菜单1");//MenuItem-新增菜单项后的返回类型,针对菜单项的其他设置在此对象上操作menu.add(1,1,1,"菜单2").setCheckable(true);
}//创建R.id.txt2的上下文菜单(多级上下文菜单)elseif(v==(TextView)this.findViewById(R.id.txt2)){
//ContextMenu.addSubMenu("菜单名称")-用来添加子菜单。子菜单其实就是一个特殊的菜单SubMenusub=menu.addSubMenu("父菜单1");sub.setIcon(R.drawable.icon01);sub.add(0,0,0,"菜单1");sub.add(0,1,1,"菜单2");sub.setGroupCheckable(1,true,true);
SubMenusub2=menu.addSubMenu("父菜单2");sub2.setIcon(R.drawable.icon01);sub2.add(1,0,0,"菜单3");sub2.add(1,1,1,"菜单4");sub2.setGroupCheckable(1,true,false);
}}
//重写onCreateOptionsMenu用以创建选项菜单@Overridepublicbool
eanonCreateOptionsMenu(Menumenu){
MenuItemmenuItem=menu.add(0,0,0,"菜单111111111111111111111");//MenuItem.setIcon()-设置菜单项的图标//MenuItem.setTitleCondensed()-菜单的简标题,如果指定了简标题的话,菜单项上的标题将会以此简标题为准
//MenuItem.setAlphabeticShortcut()-设置选中此菜单项的快捷键//注:菜单项超过6个的话,第6个菜单将会变为ore菜单之后显示出来menuItem.setIcon(R.drawable.icon01);menuItem.setTitleCondensed("菜单1");menuItem.setAlphabeticShortcut('a');More菜单,多余的菜单会在单击M
menu.add(0,1,1,"菜单2").setIcon(R.drawable.icon02);menu.add(0,2,2,"菜单3").setIcon(R.drawable.icon03);menu.add(0,3,3,"菜单4");menu.add(0,4,4,"菜单5");menu.add(0,5,5,"菜单6");menu.add(0,6,6,"菜单7").setIcon(R.drawable.icon04);menu.add(0,7,7,"菜单8").setIcon(R.drawable.icon05);
returntrue;}
//重写onOptionsItemSelected用以响应选项菜单@OverridepublicbooleanonOptionsItemSelected(MenuItemitem){super.onOptionsItemSelected(item);
Toast.makeText(Main.this,"被单击的菜单项为:"+String.valueOf(item.getItemId()),Toast.LENGTH_SHORT).show();
returnfalse;}}
Android(3)-对话框(Dialog)和通知(Notification)
介绍在Android中种对话框及各种通知效果的应用
??
常用对话框的使用,弹出式对话框、日期选择对话框、时间选择对话框、进度条对话框通知(出现在通知列表)和提示性通知(Toast)的演示
1、常用对话框的演示res/layout/main.xml
代码 android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent">
res/layout/view.xml
代码
res/values/array.xml
- 项目1
- 项目2
Main.java
代码packagecom.webabcd.dialog;
importjava.util.Calendar;
importandroid.app.Activity;importandroid.app.AlertDialog;importandroid.app.DatePickerDialog;importandroid.app.Dialog;importandroid.app.ProgressDialog;importandroid.app.TimePickerDialog;importandroid.app.DatePickerDialog.OnDateSetListener;importandroid.app.TimePickerDialog.OnTimeSetListener;importandroid.content.DialogInterface;importandroid.content.DialogInterface.OnClickListener;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.DatePicker;importandroid.widget.TextView;importandroid.widget.TimePicker;importandroid.widget.Button;
publicclassMainextendsActivity{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
//弹出式对话框的Demo。先调用Builder(),在Create(),需要显示对话框的是后再调用show()AlertDialogdialog=newAlertDialog.Builder(this).setTitle("弹出对话框").create();dialog.show();
//以下是各种对话框的DemoMyButtonClickListenerlistener=newMyButtonClickListener();Buttonbtn1=(Button)this.findViewById(R.id.btn1);btn1.setText("简单的对话框的Demo");btn1.setOnClickListener(listener);
Buttonbtn2=(Button)this.findViewById(R.id.btn2);btn2.setText("包括常用设置的对话框(数据来自xml)");btn2.setOnClickListener(listener);
Buttonbtn3=(Button)this.findViewById(R.id.btn3);btn3.setText("弹出的对话框的内容是一个View");btn3.setOnClickListener(listener);
Buttonbtn4=(Button)this.findViewById(R.id.btn4);btn4.setText("日期选择对话框");btn4.setOnClickListener(listener);
Buttonbtn5=(Button)this.findViewById(R.id.btn5);btn5.setText("时间选择对话框");btn5.setOnClickListener(listener);
Buttonbtn6=(Button)this.findViewById(R.id.btn6);btn6.setText("进度条对话框");btn6.setOnClickListener(listener);}
classMyButtonClickListenerimplementsView.OnClickListener{@OverridepublicvoidonClick(Viewv){
//具体的对话框的实现可以通过重写onCreateDialog完成
switch(v.getId()){caseR.id.btn1:Main.this.showDialog(0);break;caseR.id.btn2:Main.this.showDialog(1);break;caseR.id.btn3:Main.this.showDialog(2);break;caseR.id.btn4:Main.this.showDialog(3);break;caseR.id.btn5:Main.this.showDialog(4);break;
caseR.id.btn6:Main.this.showDialog(5);break;}}}
@OverridepublicDialogonCreateDialog(intid){switch(id){
case0://一个简单的弹出对话框returnnewAlertDialog.Builder(this).setTitle("这是一个简单的弹出
对话框的Demo").create();
case1://一个相对复杂的弹出对话框returnnewAlertDialog.Builder(this).setTitle("标题")//设置标题//.setCustomTitle(View)//以一个View作为标题.setIcon(R.drawable.icon01)//设置标题图片//.setMessage("信息")//需要显示的弹出内容.setPositiveButton("确定",newOnClickListener(){//设置弹框的确认按钮所显示的文本,以及单击按钮后的响应行为@OverridepublicvoidonClick(DialogInterfacea0,inta1){TextViewtxtMsg=(TextView)Main.this.findViewById(R.id.txtMsg);txtMsg.append("单击了对话框上的“确认”按钮\n");}}).setItems(R.array.ary,newDialogInterface.OnClickListener(){//弹框所显示的内容来自一个数组。数组中的数据会一行一行地依次排列publicvoidonClick(DialogInterfacedialog,hich){}})//其他常用方法如下//.setMultiChoiceItems(arg0,arg1,arg2)//.setSingleChoiceItems(arg0,arg1,arg2)//.setNeutralButton(arg0,arg1)//.setNegativeButton(arg0,arg1)intw
.create();
case2://弹出对话框为指定的View的DemoreturnnewAlertDialog.Builder(this).setTitle("此对话框的内容是一个View").setView(this.findViewById(R.layout.view)).create();
case3://弹出日期选择对话框Calendarc=Calendar.getInstance();returnnewDatePickerDialog(this,newOnDateSetListener(){@OverridepublicvoidonDateSet(DatePickerview,intyear,intmonthOfYear,intdayOfMonth){TextViewtxtMsg=(TextView)Main.this.findViewById(R.id.txtMsg);txtMsg.append("新设置的日期为:+String.valueOf(year)+"""+String.valueOf(monthOfYear)+"-"+String.valueOf(dayOfMonth)+"\n");}},c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DATE));
case4://弹出时间选择对话框Calendarc2=Calendar.getInstance();returnnewTimePickerDialog(this,newOnTimeSetListener(){@OverridepublicvoidonTimeSet(TimePickerview,inthourOfDay,intminute){TextViewtxtMsg=(TextView)Main.this.findViewById(R.id.txtMsg);txtMsg.append("新设置的时间为:"+String.valueOf(hourOfDay)+":"+String.valueOf(minute)+"\n");}
},c2.get(Calendar.HOUR),c2.get(Calendar.MINUTE),true);
case5://弹出进度条对话框ProgressDialogprogress=newProgressDialog(this);
progress.setMessage("loading...");returnprogress;
default:returnnull;}}}
2、各种提示效果的演示res/layout/main.xml
代码
res/layout/view.xml
代码
Main.java
代码
packagecom.webabcd.notification;
importandroid.app.Activity;importandroid.app.Notification;importandroid.app.NotificationManager;importandroid.app.PendingIntent;importandroid.content.Context;importandroid.content.Intent;importandroid.os.Bundle;importandroid.util.Log;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.widget.Button;importandroid.widget.TextView;importandroid.widget.Toast;
publicclassMainextendsActivity{
/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
//通过Tost.makeText().show()来实现提示性的通知效果//短时间的提示性通知的DemoButtonbtn1=(Button)this.findViewById(R.id.btn1);btn1.setText("短时间提示");btn1.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){Toast.makeText(Main.this,"我是短时间提示",Toast.LENGTH_SHORT).show();}});
//长时间的提示性通知的DemoButtonbtn2=(Button)this.findViewById(R.id.btn2);btn2.setText("长时间提示");btn2.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){Toast.makeText(Main.this,"我是长时间提示",Toast.LENGTH_LONG).show();}});
//以一个View作为提示性通知的DemoButtonbtn3=(Button)this.findViewById(R.id.btn3);btn3.setText("以一个View做提示");btn3.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){Viewview=inflateView(R.layout.view);TextViewtxtMsg=(TextView)view.findViewById(R.id.txtMsg);txtMsg.setText("提示内容");
Toasttoast=newToast(Main.this);toast.setView(view);toast.setDuration(Toast.LENGTH_LONG);toast.show();}});
Buttonbtn4=(Button)this.findViewById(R.id.btn4);btn4.setText("发出一个通知(Notification)");btn4.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){//实例化通知管理器NotificationManagernm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//指定单击通知后所打开的详细的通知页面(单击通知后打开NotificationView)PendingIntentcontentIntent=PendingIntent.getActivity(Main.this,0,newIntent(Main.this,iew.class),0);NotificationV
//实例化一个通知,并指定其图标和标题(在提示栏上显示)Notificationn=newNotifica
tion(R.drawable.icon01,"我是滚动的通知信息我是滚动的通知信息我是滚动的通知信息",System.currentTimeMillis());//设置通知的发送人和通知的详细内容(打开提示栏后在通知列表中显示)n.setLatestEventInfo(Main.this,"通知发送人","我是详细的通知信息我是详细的通知信息我是详细的通知信息",contentIntent);//100毫秒延迟后,震动250毫秒,暂停100毫秒后,再震动500毫秒n.vibrate=newlong[]{100,250,100,500};
//发出通知(其中第一个参数为通知标识符)
nm.notify(0,n);}});}
//将指定的xml资源转换为一个ViewprivateViewinflateView(intresource){LayoutInflatervi=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);returnvi.inflate(resource,null);}
//打开详细通知页后此Activity会被Pause,从详细通知页返回后此Activity会被Resume@OverrideprotectedvoidonPause(){//TODOAuto-generatedmethodstubsuper.onPause();
Log.d("MyDebug","onPause");}
@OverrideprotectedvoidonResume(){//TODOAuto-generatedmethodstubsuper.onResume();
Log.d("MyDebug","onResume");}}
NotificationView.java
代码packagecom.webabcd.notification;
importandroid.app.Activity;importandroid.app.NotificationManager;importandroid.os.Bundle;importandroid.widget.TextView;
//单击通知列表的某个通知后,所打开的详细的通知页publicclassNotificationViewextendsActivity{protectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);
setContentView(R.layout.view);
TextViewtxtMsg=(TextView)this.findViewById(R.id.txtMsg);txtMsg.setText("点通知之后所链接到的Activity");
NotificationManagernm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);//取消显示在通知列表中的指定通知(参数为通知标识符)nm.cancel(0);
//需要关闭此Activity的话就finish它既可//this.finish();}}
Android(4)-活动(Activity),服务(Service),广播(Broadcast),广播接收器(BroadcastReceiver)
介绍在Android中使用Activity,Service,Broadcast,BroadcastReceiver活动(Activity)-用于表现功能服务(Service)-相当于后台运行的Activity广播(Broadcast)-用于发送广播广播接收器(BroadcastReceiver)-用于接收广播Intent-用于连接以上各个组件,并在其间传递消息
1、演示Activity的基本用法,一个Activity启动另一个Activity,启动另一个Activity时为其传递参数,被启动的Activity返回参数给启动者的ActivityMain.java代码packagecom.webabcd.activity;importimportimportimportimportimportandroid.app.Activity;android.content.Intent;android.os.Bundle;android.util.Log;android.view.View;android.widget.Button;
importandroid.widget.TextView;publicclassMainextendsActivity{TextViewtxt;/**Calledwhentheactivityisfirstcreated.*/@Overridepublicvo
idonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);this.setContentView(R.layout.main);txt=(TextView)this.findViewById(R.id.txt);txt.setText("Activity1");Buttonbtn=(Button)this.findViewById(R.id.btn);btn.setText("启动另一个Activity");btn.setOnClickListener(newButton.OnClickListener(){@OverridepublicvoidonClick(Viewv){//实例化Intent,指定需要启动的ActivityIntentintent=newIntent();intent.setClass(Main.this,MyActivity.class);//实例化Bundle,设置需要传递的参数Bundlebundle=newBundle();bundle.putString("name","webabcd");bundle.putDouble("salary",100.13);//将需要传递的参数赋值给Intent对象intent.putExtras(bundle);//startActivity(intent);//启动指定的Intent(不等待返回结果)//Main.this.finish();//启动指定的Intent,并等待返回结果//其中第二个参数如果大于等于零,则返回结果时会回调onActivityResult()方法startActivityForResult(intent,0);}});
Log.d("MyDebug","onCreate");}//被启动的Activity返回结果时的回调函数@OverrideprotectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){if(resultCode==Activity.RESULT_OK){Bundlebundle=data.getExtras();Stringname=bundle.getString("name");doublesalary=bundle.getDouble("salary");txt.setText("Activity1"+"\n名字:"+name+"\n薪水:"+String.valueOf(salary));}}@OverrideprotectedvoidonStart(){//TODOAuto-generatedmethodstubsuper.onStart();Log.d("MyDebug","onStart");}@OverrideprotectedvoidonStop(){//TODOAuto-generatedmethodstubsuper.onStop();Log.d("MyDebug","onStop");}@OverrideprotectedvoidonRestart(){//TODOAuto-generatedmethodstubsuper.onRestart();Log.d("MyDebug","onRestart");}@OverrideprotectedvoidonPause(){
//TODOAuto-generatedmethodstubsuper.onPause();Log.d("MyDebug","onPause");}@OverrideprotectedvoidonResume(){//TODOAuto-generatedmethodstubsuper.onResume();Log.d("MyDebug","onResume");}@OverrideprotectedvoidonDestroy(){//TODOAuto-generatedmethodstubsuper.onDestroy();Log.d("MyDebug","onDestroy");}}MyActivity.java代码packagecom.webabcd.activity;importimportimportimportimportimportandroid.app.Activity;android.content.Intent;android.os.Bundle;android.view.View;android.widget.Button;android.widget.TextView;
//被另一个Activity所启动的ActivitypublicclassMyActivityextendsActivity{Intentintent;/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);
this.setContentView(R.layout.main2);//获取启动者传递过来的参数intent=this.getIntent();Bundlebundle=intent.getExtras();Stringname=bundle.getString("name");doublesalary=bundle.getDouble("salary");TextViewtxt=(TextView)this.findViewById(R.id.txt);txt.setText("Activity2"+"\n名字:"
+name+"\n薪水:"+String.valueOf(salary));Buttonbtn=(Button)this.findViewById(R.id.btn);btn.setText("返回前一个Activity");btn.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){//返回参数给启动者MyActivity.this.setResult(Activity.RESULT_OK,intent);MyActivity.this.finish();}});}}
AndroidManifest.xml代码
2、Service,Broadcast,BroadcastReceiver的演示Main.java代码packagecom.webabcd.service;importimportimportimportimportimportimportimportimportimportimportimportandroid.app.Activity;android.content.BroadcastReceiver;android.content.ComponentName;android.content.Context;android.content.Intent;android.content.IntentFilter;android.content.ServiceConnection;android.os.Bundle;android.os.IBinder;android.view.View;android.view.View.OnClickListener;android.widget.TextView;
/**startService()和bindService()的区别*startService()-正常理解就好*bindService()-使当前上下文对象(本例中就是Activity)通过一个ServiceConnection对象邦定到指定的Service。这样,如果上下文对象销毁了的话,那么其对应的Service也会被销毁*/publicclassMainextendsActivityimplementsOnClickListener{privateTextViewtxtMsg;@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);
setContentView(R.layout.main);setTitle("android之service");this.findViewById(R.id.btnStart).setOnClickListener(this);this.findViewById(R.id.btnStop).setOnClickListener(this);this.findViewById(R.id.btnBind).setOnClickListener(this);this.findViewById(R.id.btnUnbind).setOnClickListener(this);txtMsg=(TextView)this.findViewById(R.id.txtMsg);//实例化自定义的BroadcastReceiverreceiver=newUpdateReceiver();IntentFilterfilter=newIntentFilter();//为BroadcastReceiver指定action,使之用于接收同action的广播filter.addAction("com.webabcd.service.msg");//以编程方式注册BroadcastReceiver。配置方式注册BroadcastReceiver的例子见AndroidManifest.xml文件//一般在OnStart时注册,在OnStop时取消注册this.registerReceiver(receiver,filter);//this.unregisterReceiver(receiver);}@OverridepublicvoidonClick(Viewv)
{Intentintent=newIntent(Main.this,MyService.class);switch(v.getId()){caseR.id.btnStart:this.startService(intent);break;caseR.id.btnStop:this.stopService(intent);break;caseR.id.btnBind:this.bindService(intent,conn,Context.BIND_AUTO_CREATE);break;caseR.id.btnUnbind:this.unbindService(conn);break;}
}//bindService()所需的ServiceConnection对象privateServiceConnectionconn=newServiceConnection(){@OverridepublicvoidonServiceConnected(ComponentNameclassName,IBinderservice){}@OverridepublicvoidclassName){}};privateStringmsg="";privateUpdateReceiverreceiver;//实现一个BroadcastReceiver,用于接收指定的BroadcastpublicclassUpdateReceiverextendsBroadcastReceiver{@OverridepublicvoidonReceive(Contextcontext,Intentintent){msg=intent.getStringExtra("msg");txtMsg.append(msg+"\n");}}}MyService.java代码packagecom.webabcd.service;importimportimportimportandroid.app.Service;android.content.Intent;android.os.IBinder;android.util.Log;
onServiceDisconnected(ComponentName
//演示Service的生命周期。具体信息运行程序后在LogCat中查看publicclassMyServiceextendsService{
@OverridepublicIBinderonBind(Intentintent){Log.d("MyDebug","onBind");sendMsg("onBind");//TODOAuto-generatedmethodstubreturnnull;}@OverridepublicvoidonCreate(){//TODOAuto-generatedmethodstubsuper.onCreate();Log.d("MyDebug","onCreate");sendMsg("onCreate");}@OverridepublicvoidonDestroy(){//TODOAuto-generatedmethodstubsuper.onDestroy();Log.d("MyDebug","onDestroy");sendMsg("onDestroy");}@OverridepublicvoidonRebind(Intentintent){//TODOAuto-generatedmethodstubsuper.onRebind(intent);Log.d("MyDebug","onRebind");sendMsg("onRebind");}@OverridepublicvoidonStart(Intentintent,intstartId){super.onStart(intent,startId);Log.d("MyDebug","onStart");sendMsg("onStart");}
@OverridepublicbooleanonUnbind(Intentintent){Log.d("MyDebug","onUnbind");sendMsg("onUnbind");//TODOAuto-generatedmethodstubreturnsuper.onUnbind(intent);}//发送广播信息privatevoidsendMsg(Stringmsg){//指定广播目标的action(注:指定了此action的receiver会接收此广播)Intentintent=newIntent("com.webabcd.service.msg");//需要传递的参数intent.putExtra("msg",msg);//发送广播this.sendBroadcast(intent);}}
MyBootReceiver.java代码packagecom.webabcd.service;importimportimportimportandroid.content.BroadcastReceiver;android.content.Context;android.content.Intent;android.util.Log;
publicclassMyBootReceiverextendsBroadcastReceiver{//用于接收满足条件的Broadcast(相应的Broadcast的注册信息详见AndroidManifest.xml,当系统启动完毕后会调用这个广播接收器)@OverridepublicvoidonReceive(Contextarg0,Intentarg1){Log.d("MyDebug","onReceive");//启动服务Intentservice=newIntent(arg0,MyService.class);
ar
g0.startService(service);}}
AndroidManifest.xml代码
Android(5)-控件(View)之TextView,Button,ImageButton,ImageView,CheckBox,RadioButton,AnalogClock,DigitalClock
介绍在Android中使用各种控件(View)
????????
TextView-文本显示控件Button-按钮控件ImageButton-图片按钮控件ImageView-图片显示控件CheckBox-复选框控件RadioButton-单选框控件AnalogClock-钟表(带表盘的那种)控件DigitalClock-电子表控件
1、TextView的Demotextview.xml代码_TextView.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;publicclass_TextViewextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.textview);//设置Activity的标题setTitle("TextView");TextViewtxt=(TextView)this.findViewById(R.id.textView);//设置文本显示控件的文本内容,需要换行的话就用“\n”txt.setText("我是TextView\n显示文字用的");}}
2、Button的Demobutton.xml代码 ndroid:id="@+id/textView"/>_Button.java代码packagecom.webabcd.view;importimportimportimportimportandroid.app.Activity;android.os.Bundle;android.view.View;android.widget.Button;android.widget.TextView;
publicclass_ButtonextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.button);setTitle("Button");Buttonbtn=(Button)this.findViewById(R.id.button);btn.setText("clickme");//setOnClickListener()-响应按钮的鼠标单击事件btn.setOnClickListener(newButton.OnClickListener(){@OverridepublicvoidonClick(Viewv){TextViewtxt=(TextView)_Button.this.findViewById(R.id.textView);txt.setText("按钮被单击了");}});}}
3、ImageButton的Demoimagebutton.xml代码_ImageButton.java代码packagecom.webabcd.view;importimportimportimportimportimportandroid.app.Activity;android.os.Bundle;android.view.View;android.widget.Button;android.widget.ImageButton;android.widget.TextView;
publicclass_ImageButtonextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.imagebutton);
setTitle("ImageButton");ImageButtonimgButton=(ImageButton)this.findViewById(R.id.imageButton);//设置图片按钮的背景imgButton.setBackgroundResource(R.drawable.icon01);//setOnClickListener()-响应图片按钮的鼠标单击事件imgButton.setOnClickListener(newButton.OnClickListener(){@OverridepublicvoidonClick(Viewv){TextViewtxt=(TextView)_ImageButton.this.findViewById(R.id.textView);txt.setText("图片按钮被单击了");}});}}
4、ImageView的Demoimageview.xml代码_ImageView.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bu
ndle;
importandroid.widget.ImageView;publicclass_ImageViewextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.imageview);setTitle("ImageView");ImageViewimgView=(ImageView)this.findViewById(R.id.imageView);//指定需要显示的图片imgView.setBackgroundResource(R.drawable.icon01);}}
5、CheckBox的Democheckbox.xml代码_CheckBox.java代码packagecom.webabcd.view;importimportimportimportimportandroid.app.Activity;android.os.Bundle;android.widget.CheckBox;android.widget.CompoundButton;android.widget.TextView;
publicclass_CheckBoxextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.checkbox);setTitle("CheckBox");CheckBoxchk=(CheckBox)this.findViewById(R.id.chk1);//setOnCheckedChangeListener()-响应复选框的选中状态改变事件chk.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener(){@OverridepublicvoidonCheckedChanged(CompoundButtonbuttonView,booleanisChecked){TextViewtxt=(TextView)_CheckBox.this.findViewById(R.id.textView);txt.setText("CheckBox01的选中状态:"+String.valueOf(isChecked));}});}}
6、RadioButton的Demoradiobutton.xml
代码_RadioButton.java代码packagecom.webabcd.view;importimportimportimportimportandroid.app.Activity;android.os.Bundle;android.widget.RadioButton;android.widget.RadioGroup;android.widget.TextView;
publicclass_RadioButtonextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.radiobutton);setTitle("RadioButton");RadioGroupgroup=(RadioGroup)this.findViewById(R.id.radioGroup);//setOnCheckedChangeListener()-响应单选框组内的选中项发生变化时的事件group.setOnCheckedChangeListener(newRadioGroup.OnCheckedChangeListener(){@OverridepublicvoidonCheckedChanged(RadioGroupgroup,intcheckedId){TextViewtxt=(TextView)_RadioButton.this.findViewById(R.id.textView);txt.setText(((RadioButton)findViewById(checkedId)).getText()+"被选中");}});}}
7、AnalogClock的Demoanalogclock.xml代码_AnalogClock.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bundle;publicclass_AnalogClockextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.analogclcok);setTitle("AnalogClock");}}
8、DigitalClock的Demodigitalclock.xml代码
_DigitalClock.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bundle;publicclass_DigitalClockextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.digitalclcok);setTitle("DigitalClcok");}}
Android(6)-控件(View)之DatePicker,TimePicker,ToggleButton,EditText,ProgressBar,SeekBar,AutoCompleteTextView,MultiAutoCompleteTextView
介绍在Android中使用各种控件(View)
????????
DatePicker-日期选择控件TimePicker-时间选择控件ToggleButton-双状态按钮控件EditText-可编辑文本控件ProgressBar-进度条控件SeekBar-可拖动的进度条控件AutoCompleteTextView-支持自动完成功能的可编辑文本控件MultiAutoCompleteTextView-支持自动完成功能的可编辑文本控件,允许输入多值(多值之间会自动地用指定的分隔符分开)
1、DatePick, er的Demodatepicker.xml代码_DatePicker.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bundle;publicclass_DatePickerextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.datepicker);//具体的应用可参见对话框中的示例setTitle("DatePicker");}}
2、TimePicker的Demotimepicker.xml
代码_TimePicker.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bundle;publicclass_TimePickerextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.timepicker);//具体的应用可参见对话框中的示例setTitle("TimePicker");}}
3、ToggleButton的Demotogglebutton.xml代码 android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"> ht="wrap_content"android:textOn="关闭"android:textOff="打开"/>_ToggleButton.java代码packagecom.webabcd.view;importimportimportimportimportimportandroid.app.Activity;android.os.Bundle;android.view.View;android.widget.Button;android.widget.TextView;android.widget.ToggleButton;
publicclass_ToggleButtonextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.togglebutton);setTitle("ToggleButton");finalToggleButtonbtn=(ToggleButton)this.findViewById(R.id.toggleButton);//setOnClickListener()-响应按钮的鼠标单击事件btn.setOnClickListener(newButton.OnClickListener(){
@OverridepublicvoidonClick(Viewv){TextViewtxt=(TextView)_ToggleButton.this.findViewById(R.id.textView);//ToggleButton.isChecked()-双状态按钮的按钮状态txt.setText("按钮状态:"+String.valueOf(btn.isChecked()));}});}}
4、EditText的Demoedittext.xml代码_EditText.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.EditText;publicclass_EditTextextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){
//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.edittext);setTitle("EditText");EditTexttxt=(EditText)this.findViewById(R.id.editText);txt.setText("我可编辑");}}
5、ProgressBar的Demoprogressbar.xml代码 -->_ProgressBar.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.Window;
//另见对话框中的进度条publicclass_ProgressBarextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);//设置特性以允许在应用程序的标题栏上显示进度条(条状)requestWindowFeature(Window.FEATURE_PROGRESS);//设置特性以允许在应用程序的标题栏上显示进度条(圆圈状)requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);this.setContentView(R.layout.progressbar);setTitle("ProgressBar");//在标题栏上显示进度条(条状)setProgressBarVisibility(true);//在标题栏上显示进度条(圆圈状)setProgressBarIndeterminateVisibility(true);//指定进度条的进度setProgress(50*100);setSecondaryProgress(75*100);
}}
6、SeekBar的Demoseekbar.xml代码_SeekBar.java代码packagecom.webabcd.view;importimportimportimportandroid.app.Activity;android.os.Bundle;android.widget.SeekBar;android.widget.TextView;
publicclass_SeekBarextendsActivityimplements
SeekBar.OnSeekBarChangeListener{SeekBarmSeekBar;TextViewmProgressText;TextViewmTrackingText;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.seekbar);setTitle("SeekBar");mSeekBar=(SeekBar)findViewById(R.id.seekBar);//setOnSeekBarChangeListener()-响应拖动进度条事件mSeekBar.setOnSeekBarChangeListener(this);mProgressText=(TextView)findViewById(R.id.progress);mTrackingText=(TextView)findViewById(R.id.tracking);}//拖动进度条后,进度发生改变时的回调事件publicvoidonProgressChanged(SeekBarseekBar,intprogress,booleanfromTouch){mProgressText.setText(progress+"%");}//拖动进度条前开始跟踪触摸pub
licvoidonStartTrackingTouch(SeekBarseekBar){mTrackingText.setText("开始跟踪触摸");}//拖动进度条后停止跟踪触摸publicvoidonStopTrackingTouch(SeekBarseekBar){mTrackingText.setText("停止跟踪触摸");}}
7、AutoCompleteTextView的Demoautocompletetextview.xml代码
_AutoCompleteTextView.java代码packagecom.webabcd.view;importimportimportimportandroid.app.Activity;android.os.Bundle;android.widget.ArrayAdapter;android.widget.AutoCompleteTextView;
publicclass_AutoCompleteTextViewextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.autocompletetextview);setTitle("AutoCompleteTextView");//实例化适配器,指定显示格式及数据源ArrayAdapteradapter=newArrayAdapter(this,android.R.layout.simple_dropdown_item_1line,ary);AutoCompleteTextViewtextView=(AutoCompleteTextView)findViewById(R.id.editText);//指定自动完成控件的适配器textView.setAdapter(adapter);}
//自动完成控件的所需数据的数据源privateString[]ary=newString[]{"abc","abcd","abcde","abcdef","abcdefg","hij","hijk","hijkl","hijklm","hijklmn",};}
8、MultiAutoCompleteTextView的Demomultiautocompletetextview.xml代码_MultiAutoCompleteTextView.java代码packagecom.webabcd.view;importimportimportimportandroid.app.Activity;android.os.Bundle;android.widget.ArrayAdapter;android.widget.MultiAutoCompleteTextView;
publicclass_MultiAutoCompleteTextViewextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.multiautocompletetextview);setTitle("MultiAutoCompleteTextView");//实例化适配器,指定显示格式及数据源ArrayAdapteradapter=newArrayAdapter(this,android.R.layout.simple_dropdown_item_1line,ary);MultiAutoCompleteTextViewtextView=(MultiAutoCompleteTextView)findViewById(R.id.editText
);textView.setAdapter(adapter);//设置多个值之间的分隔符,此处为逗号textView.setTokenizer(newMultiAutoCompleteTextView.CommaTokenizer());}//自动完成控件的所需数据的数据源privateString[]ary=newString[]{"abc","abcd","abcde","abcdef","abcdefg","hij","hijk","hijkl","hijklm","hijklmn",};}
Android(7)-控件(View)之ZoomControls,Include,VideoView,WebView,RatingBar,Tab,Spinner,Chronometer,ScrollView
介绍在Android中使用各种控件(View)
?????????
ZoomControls-放大/缩小按钮控件Include-整合控件VideoView-视频播放控件WebView-浏览器控件RatingBar-评分控件Tab-选项卡控件Spinner-下拉框控件Chronometer-计时器控件ScrollView-滚动条控件
1、ZoomControls的Demozoomcontrols.xml代码_ZoomControls.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.View;
importandroid.view.View.OnClickListener;importandroid.widget.Toast;importandroid.widget.ZoomControls;publicclass_ZoomControlsextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.zoomcontrols);setTitle("ZoomControls");ZoomControlszoomControls=(ZoomControls)this.findViewById(R.id.zoomControls);//setOnZoomInClickListener()-响应单击放大按钮的事件zoomControls.setOnZoomInClickListener(newOnClickListener(){publicvoidonClick(Viewv){Toast.makeText(_ZoomControls.this,"单击了放大按钮",Toast.LENGTH_SHORT).show();}});//setOnZoomOutClickListener()-响应单击缩小按钮的事件zoomControls.setOnZoomOutClickListener(newOnClickListener(){publicvoidonClick(Viewv){Toast.makeText(_ZoomControls.this,"单击了缩小按钮",Toast.LENGTH_SHORT).show();}});}}
2、Include的Demoinclude.xml代码 android:layout_height="fill_parent">include_1.xml代码
include_2.xml代码_Include.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bundle;publicclass_IncludeextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.include);
setTitle("Include");}}
3、VideoView的Demovideoview.xml代码_VideoView.java代码packagecom.webabcd.view;importimportimportimportimportandroid.app.Activity;android.net.Uri;android.os.Bundle;android.widget.MediaController;android.widget.VideoView;
publicclass_VideoViewextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.videoview);setTitle("VideoView");
VideoViewvideoView=(VideoView)findViewById(R.id.videoView);//指定需要播放的视频的地址videoView.setVideoURI(Uri.parse("android.resource://com.webabcd.view/"+R.raw.demo));//videoView.setVideoPath();//设置播放器的控制条videoView.setMediaController(newMediaController(this));//开始播放视频videoView.start();}}
4、WebView的Demowebview.xml代码_WebView.java代码packagecom.webabcd.view;importimportimportimportandroid.app.Activity;android.os.Bundle;android.webkit.WebSettings;android.webkit.WebView;
publicclass_WebViewextendsActivity{
@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.webview);setTitle("WebView");WebViewwebView=(WebView)findViewById(R.id.webView);//配置浏览器,使其可支持JavaScriptWebSettingswebSettings=webView.getSettings();webSettings.setJavaScriptEnabled(true);//清除浏览器
缓存webView.clearCache(true);//指定浏览器需要解析的url地址webView.loadUrl("webabcdblogs/");//指定浏览器需要解析的html数据//webView.loadData("webabcd","text/html","utf-8");}}
5、RatingBar的Demoratingbar.xml代码
_RatingBar.java代码packagecom.webabcd.view;importimportimportimportandroid.app.Activity;android.os.Bundle;android.widget.RatingBar;android.widget.TextView;
publicclass_RatingBarextendsActivityimplementsRatingBar.OnRatingBarChangeListener{privateRatingBarmRatingBar;privateTextViewmTextView;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.ratingbar);setTitle("RatingBar");mTextView=(TextView)findViewById(R.id.textView);mRatingBar=(RatingBar)findViewById(R.id.ratingBar);//setOnRatingBarChangeListener()-响应评分值发生改变的事件mRatingBar.setOnRatingBarChangeListener(this);}@OverridepublicvoidonRatingChanged(RatingBarratingBar,floatrating,booleanfromUser){mTextView.setText(String.valueOf(rating));}}
6、Tab的Demotab.xml代码_Tab.java代码packagecom.webabcd.view;importimportimportimportimportandroid.app.TabActivity;android.content.Intent;android.os.Bundle;android.view.LayoutInflater;android.widget.TabHost;
//实现Tab功能的话要继承TabActivitypublicclass_TabextendsTabActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);TabHosttabHost=getTabHost();
LayoutInflater.from(this).inflate(R.layout.tab,tabHost.getTabContentView(),true);//Tab1的内容tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("tab
1").setContent(R.id.view1));//Tab2的内容(设置了Tab图片)tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("tab2",getResources().getDrawable(R.drawable.icon01)).setContent(R.id.view2));//Tab3的内容(设置Tab的内容为指定的Activity)tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("tab3").setContent(newIntent(this,_TextView.class)));}}
7、Spinner的Demospinner.xml代码
_Spinner.java代码packagecom.webabcd.view;importimportimportimportimportimportimportandroid.app.Activity;android.os.Bundle;android.view.View;android.widget.AdapterView;android.widget.ArrayAdapter;android.widget.Spinner;android.widget.TextView;
publicclass_SpinnerextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.spinner);setTitle("Spinner");Spinnerspinner=(Spinner)findViewById(R.id.spinner);//设置下拉框控件的标题文本spinner.setPrompt("请选择");//实例化适配器,指定显示格式及数据源ArrayAdapteradapter=ArrayAdapter.createFromResource(this,R.array.colors,android.R.layout.simple_spinner_item);adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);spinner.setAdapter(adapter);//setOnItemSelectedListener()-响应下拉框的选中值发生变化的事件spinner.setOnItemSelectedListener(newAdapterView.OnItemSelectedListener(){@OverridepublicvoidonItemSelected(AdapterView>arg0,Viewarg1,intarg2,longarg3){TextViewtextView=(TextView)_Spinner.this.findViewB
yId(R.id.textView);textView.setText(((TextView)arg1).getText());}@OverridepublicvoidonNothingSelected(AdapterView>arg0){}});}}
8、Chronometer的Demochronometer.xml代码 roid:text="停止计时">
_Chronometer.java代码packagecom.webabcd.view;importimportimportimportimportimportimportandroid.app.Activity;android.os.Bundle;android.os.SystemClock;android.view.View;android.view.View.OnClickListener;android.widget.Button;android.widget.Chronometer;
publicclass_ChronometerextendsActivity{privateChronometermChronometer;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.chronometer);setTitle("Chronometer");Buttonbutton;mChronometer=(Chronometer)findViewById(R.id.chronometer);//设置计时器所显示的时间格式mChronometer.setFormat("计时:(%s)");button=(Button)findViewById(R.id.btnStart);button.setOnClickListener(mStartListener);button=(Button)findViewById(R.id.btnStop);button.setOnClickListener(mStopListener);button=(Button)findViewById(R.id.btnReset);button.setOnClickListener(mResetListener);}
View.OnClickListenermStartListener=newOnClickListener(){publicvoidonClick(Viewv){//启动计时器mChronometer.start();}};View.OnClickListenermStopListener=newOnClickListener(){publicvoidonClick(Viewv){//暂停计时器mChronometer.stop();}};View.OnClickListenermResetListener=newOnClickListener(){publicvoidonClick(Viewv){//复位计时器,即停止计时器mChronometer.setBase(SystemClock.elapsedRealtime());}};}
9、ScrollView的Demoscrollview.xml代码
_ScrollView.java代码packagecom.webabcd.view;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;publicclass_ScrollViewextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.scrollview);setTitle("ScrollView");TextViewtextView=(TextView)this.findViewById(R.id.textView);textView.setText("a\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na");}}
Android(8)-控件(View)之TextSwitcher,Gallery,ImageSwitcher,GridView,ListView,Expan
dableList
介绍在Android中使用各种控件(View)
??????
TextSwitcher-文字转换器控件(改变文字时增加一些动画效果)Gallery-缩略图浏览器控件ImageSwitcher-图片转换器控件(改变图片时增加一些动画效果)GridView-网格控件ListView-列表控件ExpandableList-支持展开/收缩功能的列表控件
1、TextSwitcher的Demotextswitcher.xml代码_TextSwitcher.java代码packagecom.webabcd.view;importjava.util.Random;importimportimportimportimportimportimportimportimportandroid.app.Activity;android.os.Bundle;android.view.View;android.view.animation.Animation;android.view.animation.AnimationUtils;android.widget.Button;android.widget.TextSwitcher;android.widget.TextView;android.widget.ViewSwitcher;
publicclass_TextSwitcherextendsActivityimplementsViewSwitcher.ViewFactory{
@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.textswithcer);setTitle("TextSwithcer");finalTextSwitcherswitcher=(TextSwitcher)findViewById(R.id.textSwitcher);//指定转换器的ViewSwitcher.ViewFactoryswitcher.setFactory(this);//设置淡入和淡出的动画效果Animationin=AnimationUtils.loadAnimation(this,android.R.anim.fade_in);Animationout=AnimationUtils.loadAnimation(this,android.R.anim.fade_out);switcher.setInAnimation(in);switcher.setOutAnimation(out);//单击一次按钮改变一次文字ButtonbtnChange=(Button)this.findViewById(R.id.btnChange);btnChange.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){switcher.setText(String.valueOf(newRandom().nextInt()));}});}//重写ViewSwitcher.ViewFactory的makeView(),返回一个View@OverridepublicViewmakeView(){TextViewtextView=newTextView(this);textView.setTextSize(36);returntextView;}}
2、Gallery的Demogallery.xml
代码 ayout_height="wrap_content"android:spacing="20px"/>_Gallery.java代码packagecom.webabcd.view;importimportimportimportimportimportimportimportimportimportimportandroid.app.Activity;android.content.Context;android.os.Bundle;android.view.View;android.view.ViewGroup;android.widget.AdapterView;android.widget.BaseAdapter;android.widget.Gallery;android.widget.ImageView;android.widget.Toast;android.widget.Gallery.LayoutParams;
publicclass_GalleryextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.gallery);setTitle("Gallery");
Gallerygallery=(Gallery)findViewById(R.id.gallery);//为缩略图浏览器指定一个适配器gallery.setAdapter(newImageAdapter(this));//响应在缩略图列表上选中某个缩略图后的事件gallery.setOnItemSelectedListener(newAdapterView.OnItemSelectedListener(){@OverridepublicvoidonItemSelected(AdapterView>parent,Viewv,intposition,longid){Toast.makeText(_Gallery.this,String.valueOf(position),Toast.LENGTH_SHORT).show();}@OverridepublicvoidonNothingSelected(AdapterView>arg0){}});}//继承BaseAdapter用以实现自定义的图片适配器publicclassImageAdapterextendsBaseAdapter{privateContextmContext;publicImageAdapter(Contextcontext){mContext=context;}publicintgetCount(){returnmThumbIds.length;}publicObjectgetItem(intposition){returnposition;}publiclonggetItemId(intposition){returnposition;}publicViewgetView(intposition,ViewconvertView,ViewGroupparent){ImageViewimage=newImageView(mContext);
image.setImageResource(mThumbIds[position]);image.setAdjustViewBounds(true);image.setLayoutParams(newGallery.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));returnimage;}}//需要显示的图片集合privateInteger[]mThumbIds={R.drawable.icon01,R.drawable.icon02,R.drawable.icon03,R.drawable.icon04,R.drawable.icon05};}
3、ImageSwitcher的Demoimageswitcher.xml代码_ImageSwitcher.java代码
packagecom.webabcd.view;importimportimportimportimportimportimportimportimportimportimportimportimportandroid.app.Activity;android.content.Context;android.os.Bundle;android.view.View;android.view.ViewGroup;android.view.animatio
n.AnimationUtils;android.widget.AdapterView;android.widget.BaseAdapter;android.widget.Gallery;android.widget.ImageSwitcher;android.widget.ImageView;android.widget.ViewSwitcher;android.widget.Gallery.LayoutParams;
//图片转换器的使用基本同文字转换器//以下是一个用ImageSwitcher+Gallery实现的经典的图片浏览器的Demopublicclass_ImageSwitcherextendsActivityimplementsViewSwitcher.ViewFactory{privateImageSwitchermSwitcher;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.imageswithcer);setTitle("ImageSwithcer");mSwitcher=(ImageSwitcher)findViewById(R.id.imageSwitcher);mSwitcher.setFactory(this);mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));Gallerygallery=(Gallery)findViewById(R.id.gallery);gallery.setAdapter(newImageAdapter(this));gallery.setOnItemSelectedListener(newAdapterView.OnItemSelectedListener(){@OverridepublicvoidonItemSelected(AdapterView>parent,Viewv,
intposition,longid){mSwitcher.setImageResource(mImageIds[position]);}@OverridepublicvoidonNothingSelected(AdapterView>arg0){}});}publicclassImageAdapterextendsBaseAdapter{privateContextmContext;publicImageAdapter(Contextcontext){mContext=context;}publicintgetCount(){returnmThumbIds.length;}publicObjectgetItem(intposition){returnposition;}publiclonggetItemId(intposition){returnposition;}publicViewgetView(intposition,ViewconvertView,ViewGroupparent){ImageViewimage=newImageView(mContext);image.setImageResource(mThumbIds[position]);image.setAdjustViewBounds(true);image.setLayoutParams(newGallery.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));returnimage;}}
privateInteger[]mThumbIds={R.drawable.icon01,R.drawable.icon02,R.drawable.icon03,R.drawable.icon04,R.drawable.icon05};privateInteger[]mImageIds={R.drawable.icon01,R.drawable.icon02,R.drawable.icon03,R.drawable.icon04,R.drawable.icon05};@OverridepublicViewmakeView(){ImageViewimage=newImageView(this);image.setMinimumHeight(200);image.setMinimumWidth(200);image.setScaleType(ImageView.ScaleType.FIT_CENTER);image.setLayoutParams(newImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));returnimage;}}
4、GridView的Demogridview.xml代码 :horizontalSpacing="10px"android:numColumns="auto_fit"android:columnWidth="60px"android:stretchMode="columnWidth"android:gravity="center">_GridView.java代码
packagecom.webabcd.view;importimportimportimportimportimportimportimportandroid.app.Activity;android.content.Context;android.os.Bundle;android.view.View;android.view.ViewGroup;android.widget.BaseAdapter;android.widget.GridView;android.widget.ImageView;
publicclass_GridViewextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.gridview);setTitle("GridView");GridViewgridView=(GridView)findViewById(R.id.gridView);//指定网格控件的适配器为自定义的图片适配器gridView.setAdapter(newImageAdapter(this));}//自定义的图片适配器publicclassImageAdapterextendsBaseAdapter{privateContextmContext;publicImageAdapter(Contextcontext){mContext=context;}publicintgetCount(){returnmThumbIds.length;}publicObjectgetItem(intposition){returnposition;}publiclonggetItemId(intposition){
returnposition;}publicViewgetView(intposition,ViewconvertView,ViewGroupparent){ImageViewimageView;if(convertView==null){imageView=newImageView(mContext);imageView.setLayoutParams(newGridView.LayoutParams(48,48));imageView.setAdjustViewBounds(false);imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);imageView.setPadding(5,5,5,5);}else{imageView=(ImageView)convertView;}imageView.setImageResource(mThumbIds[position]);returnimageView;}//网格控件所需图片数据的数据源privateInteger[]mThumbIds={R.drawable.icon01,R.drawable.icon02,R.drawable.icon03,R.drawable.icon04,R.drawable.icon05};}}
5、ListView的Demomain_list_adapter.xml代码
MainListAdapter.java代码packagecom.webabcd.view;importjava.util.List;importimportimportimportimportimportandroid.content.Context;android.view.LayoutInflater;android.view.View;android.view.ViewGroup;android.widget.BaseAdapter;android.widget.TextView;
//继承BaseAdapter以实现自定义的列表适配器publicclassMainListAdapterextendsBaseAdapter{privateLayoutInflatermInflater;privateListmData;publicMainListAdapter(Contextcontext,Listdata){mInflater=LayoutInflater.from(context);mData=data;}@OverridepublicintgetCount(){returnmData.size();}@OverridepublicObjectgetItem(intposition){returnmData.get(po
sition);}@OverridepubliclonggetItemId(intposition){
returnposition;}@OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){TextViewtext;if(convertView==null){//指定一个layout作为自定义列表适配器的layoutconvertView=mInflater.inflate(R.layout.main_list_adapter,null);text=(TextView)convertView.findViewById(R.id.text);convertView.setTag(text);}else{text=(TextView)convertView.getTag();}StringmItem=mData.get(position);text.setText(mItem);returnconvertView;}}Main.java代码packagecom.webabcd.view;importjava.util.ArrayList;importjava.util.List;importimportimportimportimportandroid.app.ListActivity;android.content.Intent;android.os.Bundle;android.view.View;android.widget.ListView;
//此处要继承ListActivity,用以实现ListView的功能publicclassMainextendsListActivity{privateListmData;
/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setTheme(android.R.style.Theme_Light);setContentView(R.layout.main);mData=getData();//使用自定义的列表适配器来展现数据MainListAdapteradapter=newMainListAdapter(this,mData);//如需使用系统内置的列表适配器,则可以使用类似如下的方法//ArrayAdapteradapter=newArrayAdapter(this,android.R.layout.simple_expandable_list_item_1,mData);this.setListAdapter(adapter);}//ListView的数据源privateListgetData(){Listitems=newArrayList();items.add("TextView");items.add("Button");items.add("ImageButton");items.add("ImageView");items.add("CheckBox");items.add("RadioButton");items.add("AnalogClock");items.add("DigitalClock");items.add("DatePicker");items.add("TimePicker");items.add("ToggleButton");items.add("EditText");items.add("ProgressBar");items.add("SeekBar");items.add("AutoCompleteTextView");items.add("MultiAutoCompleteTextView");items.add("ZoomControls");items.add("Include");items.add("VideoView");items.add("WebView");items.add("RatingBar");
items.add("Tab");items.add("Spinner");items.add("Chronometer");items.add("ScrollView");items.add("TextSwitcher");items.add("ListView");items.add("Gallery");items.add("ImageSwitcher");items.add("GridView");items.add("ExpandableList");returnitems;}//ListView中某项被选中后的逻辑@OverrideprotectedvoidonListItemClick(ListViewl,Viewv,intposition,longid){Intentintent=newIntent();intent.setClassName(this,"com.webabcd.view._"+mData.get(position));startActivityForResult(intent,0);}}
6、ExpandableList的Demo_ExpandableList.java代码packagecom.webabcd.view;importimportimportimportimportimportimportimportimportimportimportimportandroid.app.ExpandableListActivity;android.os.Bundle;android.view.ContextMenu;android.view.Gravity;android.view.MenuItem;android.view.View
;android.view.ViewGroup;android.view.ContextMenu.ContextMenuInfo;android.widget.AbsListView;android.widget.BaseExpandableListAdapter;android.widget.ExpandableListAdapter;android.widget.ExpandableListView;
importandroid.widget.TextView;importandroid.widget.Toast;importandroid.widget.ExpandableListView.ExpandableListContextMenuInfo;//ExpandableList-可展开/收缩列表//继承ExpandableListActivity以实现列表的可展开/收缩的功能publicclass_ExpandableListextendsExpandableListActivity{privateExpandableListAdaptermAdapter;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);setTitle("ExpandableList");mAdapter=newMyExpandableListAdapter();setListAdapter(mAdapter);registerForContextMenu(this.getExpandableListView());}//为列表的每一项创建上下文菜单(即长按后呼出的菜单)@OverridepublicvoidonCreateContextMenu(ContextMenumenu,Viewv,ContextMenuInfomenuInfo){menu.setHeaderTitle("ContextMenu");menu.add(0,0,0,"ContextMenu");}//单击上下文菜单后的逻辑@OverridepublicbooleanonContextItemSelected(MenuItemitem){ExpandableListContextMenuInfoinfo=(ExpandableListContextMenuInfo)item.getMenuInfo();Stringtitle=((TextView)info.targetView).getText().toString();inttype=ExpandableListView.getPackedPositionType(info.packedPosition);if(type==ExpandableListView.PACKED_POSITION_TYPE_CHILD){intgroupPos=ExpandableListView.getPackedPositionGroup(info.packedPosition);
intchildPos=ExpandableListView.getPackedPositionChild(info.packedPosition);Toast.makeText(this,title+"-GroupIndex:"+groupPos+"ChildIndex:"+childPos,Toast.LENGTH_SHORT).show();returntrue;}elseif(type==ExpandableListView.PACKED_POSITION_TYPE_GROUP){intgroupPos=ExpandableListView.getPackedPositionGroup(info.packedPosition);Toast.makeText(this,title+"-GroupIndex:"+groupPos,Toast.LENGTH_SHORT).show();returntrue;}returnfalse;}publicclassMyExpandableListAdapterextendsBaseExpandableListAdapter{//父列表数据privateString[]groups={"group1","group2","group3","group4"};//子列表数据privateString[][]children={{"child1"},{"child1","child2"},{"child1","child2","child3"},{"child1","child2","child3","child4"}};@OverridepublicObjectgetChild(intgroupPosition,intchildPosition){returnchildren[groupPosition][childPosition];
}@OverridepubliclonggetChildId(intgroupPosition,intchildPosition){returnchildPosition;}@OverridepublicintgetChildrenCount(intgroupPosition){returnchildren[groupPosition].length;}//取子列表中的某一项的View@OverridepublicViewgetChildView(intgroupPosition,intchildPosition,booleanisLastChild,ViewconvertView,ViewGroupparent){TextViewtextView=getGenericView();textView.setText(getChild(groupPosition,childPosition).toString());returnt
extView;}@OverridepublicObjectgetGroup(intgroupPosition){returngroups[groupPosition];}@OverridepublicintgetGroupCount(){returngroups.length;}@OverridepubliclonggetGroupId(intgroupPosition){returngroupPosition;}//取父列表中的某一项的View@OverridepublicViewgetGroupView(intgroupPosition,booleanisExpanded,ViewconvertView,ViewGroupparent){
TextViewtextView=getGenericView();textView.setText(getGroup(groupPosition).toString());returntextView;}@OverridepublicbooleanhasStableIds(){returntrue;}@OverridepublicbooleanisChildSelectable(intgroupPosition,intchildPosition){returntrue;}//获取某一项的View的逻辑privateTextViewgetGenericView(){AbsListView.LayoutParamslp=newAbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,48);TextViewtextView=newTextView(_ExpandableList.this);textView.setLayoutParams(lp);textView.setGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT);textView.setPadding(32,0,0,0);returntextView;}}}
Android(9)-数据库支持(SQLite),内容提供器(ContentProvider)
介绍在Android中使用SQLite,ContentProvider
??
数据库支持(SQLite)-Android开发平台提供了操作SQLite数据库的相关API内容提供器(ContentProvider)-当数据需要在应用程序之间共享时,可以在某程序中使用ContentProvider定义URI,以使其它应用程序可以通过此URI访问指定的数据
1、SQLite的DemoDatabaseHelper.java
代码packagecom.webabcd.SQLite;
importandroid.content.Context;importandroid.database.sqlite.SQLiteDatabase;importandroid.database.sqlite.SQLiteOpenHelper;importandroid.database.sqlite.SQLiteDatabase.CursorFactory;
//数据库操作的Helper类publicclassDatabaseHelperextendsSQLiteOpenHelper{
DatabaseHelper(Contextcontext,Stringname,CursorFactorycursorFactory,intversion){super(context,name,cursorFactory,version);}
@OverridepublicvoidonCreate(SQLiteDatabasedb){//TODO创建数据库后,对数据库的操作}
@OverridepublicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){//TODO更改数据库版本的操作}
@OverridepublicvoidonOpen(SQLiteDatabasedb){super.onOpen(db);
//TODO每次成功打开数据库后首先被执行}}
Main.java
代码packagecom.webabcd.SQLite;
importjava.util.Random;
importandroid.app.Activity;importandroid.content.ContentValues;importandroid.database.Cursor;importandroid.database.SQLException;importandroid.database.sqlite.SQLiteDatabase;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.TextView;
publicclassMainextendsActivity{
privateDatabaseHelperdbHelper;
privatestaticfinalStringDATABASE_NAME="db.db";privatestaticfinalintDATABASE_VERSION=1;privatestaticfinalStringTABLE_NAME="employee";
TextViewtxtMsg;
/**Calledwhentheactivityisfirstcreated.*/
@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
dbHelper=newDatabaseHelper(this,DATABASE_NAME,null,DATABASE_VERSION);
txtMsg=(TextView)this.findViewById(R.id.txtMsg);
Buttonbtn1=(Button)this.findViewById(R.id.btn1);btn1.setText("创建表");btn1.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){CreateTable();}});
Buttonbtn2=(Button)this.findViewById(R.id.btn2);btn2.setText("插入3条记录");btn2.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){insertItem();}});
Buttonbtn3=(Button)this.findViewById(R.id.btn3);btn3.setText("删除全部记录");btn3.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){deleteItem();}});
Buttonbtn4=(Button)this.findViewById(R.id.btn4);btn4.setText("更新指定数据");btn4.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){updateItem();}});
Buttonbtn5=(Button)this.findViewById(R.id.btn5);btn5.setText("显示全部数据");btn5.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){showItems();}});
Buttonbtn6=(Button)this.findViewById(R.id.btn6);btn6.setText("删除表");btn6.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){dropTable();}});}
//创建数据表privatevoidCreateTable(){SQLiteDatabasedb=dbHelper.getWritableDatabase();
Stringsql="CREATETABLEIFNOTEXISTS"+TABLE_NAME+"(IDINTEGERPRIMARYKEY,NameVARCHAR,AgeINTEGER);";try{db.execSQL(sql);txtMsg.append("数据表成功创建\n");}catch(SQLExceptionex){txtMsg.append("数据表创建错误\n"+ex.toString()+"\n");}}
//插入数据privatevoidinsertItem(){SQLiteDatabasedb=dbHelper.getWritableDatabase();
try{Randomrandom=newRandom();for(inti=0;i<3;i++){Stringsql="insertinto"+TABLE_NAME+"(name,age)values('name"+String.valueOf(i)+"',"+random.nextInt()+")";//execSQL()-执行指定的sqldb.execSQL(sql);}txtMsg.append("成功插入3条数据\n");}catch(SQLExceptionex){txtMsg.append("插入数据失败\n"+ex.toString()+"\n");}}
//删除数据privatevoiddeleteItem(){try{SQLiteDatabasedb=dbHelper.getWritableDatabase();db.delete(TABLE_NAME,"id<999999",null);txtMsg.append("成功删除数据\n");}catch(SQLExceptione){txtMsg.append("删除数据失败\n");}}
//更新数据privatevoidupdateItem(){SQLiteDatabasedb=dbHelper.getWritableDatabase();
try{ContentValuesvalues=newContentValues();values.put("name","批量更新后的名字");
db.update(TABLE_NAME,values,"id",newString[]{"3"});txtMsg.append("成功更新数据\n");}catch(SQLExceptione){txtMsg.append("更新数据失败\n");}}
//查询数据privatevoidshowItems(){SQLiteDatabasedb=dbHelper.getReadableDatabase();
try
{String[]column={"id","name","age"};Cursorcursor=db.query(TABLE_NAME,column,null,null,null,null,null);Integernum=cursor.getCount();txtMsg.append("共"+Integer.toString(num)+"条记录\n");cursor.moveToFirst();
while(cursor.getPosition()!=cursor.getCount()){txtMsg.append(Integer.toString(cursor.getPosition())+","+String.valueOf(cursor.getString(0))+","+cursor.getString(1)+","+String.valueOf(cursor.getString(2))+"\n");cursor.moveToNext();}}catch(SQLExceptionex){txtMsg.append("读取数据失败\n"+ex.toString()+"\n");}}
//删除数据表privatevoiddropTable(){SQLiteDatabasedb=dbHelper.getWritableDatabase();Stringsql="DROPTABLEIFEXISTS"+TABLE_NAME;try{db.execSQL(sql);txtMsg.append("数据表删除成功\n");}catch(SQLExceptionex){txtMsg.append("数据表删除错误\n"+ex.toString()+"\n");
}}}
2、ContentProvider的DemoMyUser.java
代码packagecom.webabcd.contentprovider;
importandroid.net.Uri;importandroid.provider.BaseColumns;
//自定义ContentProvider所需的实体类publicclassMyUser{
//必须要有_id字段。本例中BaseColumn类中已经包含了_id字段publicstaticfinalclassUserimplementsBaseColumns{
//定义CONTENT_URIpublicstaticfinalUriCONTENT_URI=Uri.parse("content://com.webabcd.MyContentProvider");
//表数据列publicstaticfinalStringUSER_NAME="USER_NAME";}}
MyContentProvider.java
代码packagecom.webabcd.contentprovider;
importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;
importorg.apache.http.util.EncodingUtils;
importandroid.content.ContentProvider;importandroid.content.ContentUris;importandroid.content.ContentValues;importandroid.database.Cursor;importandroid.database.MatrixCursor;importan, droid.net.Uri;
//继承ContentProvider以实现自定义的ContentProvider(基于文件的信息存储)publicclassMyContentProviderextendsContentProvider{
privateFilefile;privateFileOutputStreamout;privateFileInputStreamin;
//ContentProvider的删除数据接口@Overridepublicintdelete(Uriuri,Stringselection,String[]selectionArgs){//TODOAuto-generatedmethodstubreturn0;}
@OverridepublicStringgetType(Uriuri){//TODOAuto-generatedmethodstubreturnnull;}
//ContentProvider的插入数据接口@OverridepublicUriinsert(Uriuri,ContentValuesvalues){
try{out=newFileOutputStream(file);out.write(values.getAsString(MyUser.User.USER_NAME).getBytes());out.close();
introwId=0;UrirowUri=ContentUris.appendId(MyUser.User.CONTENT_URI.buildUpon(),rowId).build();getContext().getContentResolver().notifyChange(rowUri,null);
returnrowUri;}catch(Exceptione){returnnull;}}
//创建用于保存信息的文件@OverridepublicbooleanonCreate(){
try{//每个包中应用程序的私有目录为:/data/data/包名///SD卡目录为:/sdcardfile=newFil
e("/data/data/com.webabcd.contentprovider/","demo.txt");if(!file.exists())file.createNewFile();
returntrue;}catch(Exceptionex){returnfalse;}}
//ContentProvider的查询数据接口@OverridepublicCursorquery(Uriuri,String[]projection,Stringselection,String[]selectionArgs,StringsortOrder){
Stringcontent;
try{in=newFileInputStream(file);intlength=(int)file.length();byte[]buffer=newbyte[length];in.read(buffer,0,length);content=EncodingUtils.getString(buffer,"UTF-8");in.close();
String[]columns=newString[]{MyUser.User._ID,MyUser.User.USER_NAME};MatrixCursorcur=newMatrixCursor(columns);String[]values=newString[]{"0",content};cur.moveToFirst();cur.addRow(values);
returncur;}catch(Exceptione){returnnull;}}
//ContentProvider的更新数据接口@Override
publicintupdate(Uriuri,ContentValuesvalues,Stringselection,String[]selectionArgs){//TODOAuto-generatedmethodstubreturn0;}}
Main.java
代码packagecom.webabcd.contentprovider;
importjava.util.Random;
importandroid.app.Activity;importandroid.content.ContentUris;importandroid.content.ContentValues;importandroid.database.Cursor;importandroid.net.Uri;importandroid.os.Bundle;importandroid.provider.Contacts;importandroid.provider.Contacts.People;importandroid.util.Log;importandroid.view.View;importandroid.widget.Button;importandroid.widget.Toast;
/**几个常用的系统内置的ContentProvider如下:*content://media/internal/images这个URI将返回设备上存储的所有图片*content://contacts/people/这个URI将返回设备上的所有联系人信息*content://contacts/people/45这个URI返回单个结果(联系人信息中ID为45的联系人记录)*/publicclassMainextendsActivity{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
Buttonbtn1=(Button)this.findViewById(R.id.btn1);btn1.setText("新增联系人记录");btn1.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){
Randomrandom=newRandom();insertRecords("name"+String.valueOf(random.nextInt()),String.valueOf(random.nextInt()));}});
Buttonbtn2=(Button)this.findViewById(R.id.btn2);btn2.setText("查看联系人记录");btn2.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){displayRecords();}});
Buttonbtn3=(Button)this.findViewById(R.id.btn3);btn3.setText("清除联系人记录");btn3.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){deleteRecords();}});
Buttonbtn4=(Button)this.findViewById(R.id.btn4);btn4.setText("更新联系人记录");btn4.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){//此处只是演示,id来自People._ID,可参见displayRecords()是如何获取id
的intid=0;updateRecord(id,"修改后的name");}});
Buttonbtn5=(Button)this.findViewById(R.id.btn5);btn5.setText("新增记录到MyContentProvider");btn5.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){insertRecord2MyContentProvider("webabcd");}});
Buttonbtn6=(Button)this.findViewById(R.id.btn6);btn6.setText("获取记录从MyContentProvider");
btn6.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){displayRecord2MyContentProvider();}});}
//调用ContentProvider的插入接口privatevoidinsertRecords(Stringname,StringphoneNum){ContentValuesvalues=newContentValues();values.put(People.NAME,name);Uriuri=getContentResolver().insert(People.CONTENT_URI,values);Log.d("MyDebug",uri.toString());UrinumberUri=Uri.withAppendedPath(uri,People.Phones.CONTENT_DIRECTORY);Log.d("MyDebug",numberUri.toString());
values.clear();values.put(Contacts.Phones.TYPE,People.Phones.TYPE_MOBILE);values.put(People.NUMBER,phoneNum);getContentResolver().insert(numberUri,values);}
//调用ContentProvider的查询接口privatevoiddisplayRecords(){String[]columns=newString[]{People._ID,People.NAME,People.NUMBER};Uricontacts=People.CONTENT_URI;Log.d("MyDebug",contacts.toString());Cursorcur=managedQuery(contacts,columns,//要返回的数据字段null,//WHERE子句null,//WHERE子句的参数null//Order-by子句);
if(cur.moveToFirst()){Stringid=null;Stringname=null;StringphoneNo=null;while(cur.getPosition()!=cur.getCount()){id=cur.getString(cur.getColumnIndex(People._ID));name=cur.getString(cur.getColumnIndex(People.NAME));phoneNo=cur.getString(cur.getColumnIndex(People.NUMBER));
Toast.makeText(this,id+"/"+name+"/"+phoneNo,Toast.LENGTH_SHORT).show();cur.moveToNext();}}}
//调用ContentProvider的删除接口privatevoiddeleteRecords(){Uriuri=People.CONTENT_URI;Log.d("MyDebug",uri.toString());getContentResolver().delete(uri,null,null);//getContentResolver().delete(uri,"NAME="+"'name'",null);}
//调用ContentProvider的更新接口privatevoidupdateRecord(intrecordNo,Stringname){Uriuri=ContentUris.withAppendedId(People.CONTENT_URI,recordNo);Log.d("MyDebug",uri.toString());ContentValuesvalues=newContentValues();values.put(People.NAME,name);getContentResolver().update(uri,values,null,null);}
//调用自定义ContentProvider的插入接口privatevoidinsertRecord2MyContentProvider(Stringname){ContentValuesvalues=newContentValues();values.put(MyUser.User.USER_NAME,name);getContentResolver().insert(MyUser.User.CONTENT_URI,values);
}
//调用自定义ContentProvider的查询接口privatevoiddisplayRecord2MyContentProvider(){String[]columns=newString[]{MyUser.User.USER_NAME};Uriuri=MyUser.User.CONTENT_URI;Cursorcur=managedQuery(uri,columns,null,null,null);
while(cur.getPosit
ion()!=cur.getCount()){Stringid=cur.getString(cur.getColumnIndex(People._ID));Stringname=cur.getString(cur.getColumnIndex(MyUser.User.USER_NAME));Toast.makeText(this,
id+"/"+name,Toast.LENGTH_SHORT).show();cur.moveToNext();}}}
AndroidManifest.xml
代码
Android(10)-HTTP通信,XML解析,通过Hander实现异步消息处理
介绍在Android中与服务端做HTTP通信,解析XML,通过Handler实现异步消息处理
???
HTTP通信-与服务端做HTTP通信,分别以GET方式和POST方式做演示XML解析-可以用两种方式解析XML,分别是DOM方式和SAX方式异步消息处理-通过Handler实现异步消息处理,以一个自定义的异步下载类来说明Handler的用法
1、HTTP通信和XML解析的DemoMySAXHandler.java
代码packagecom.webabcdmunication;
importorg.xml.sax.Attributes;importorg.xml.sax.SAXException;importorg.xml.sax.helpers.DefaultHandler;
//继承DefaultHandler以实现指定XML的SAX解析器//DOM-W3C标准,需要把xml数据全部加载完成后才能对其做解析,可对树做任意遍历//SAX-流式解析,通过事件模型解析xml,只能顺序解析publicclassMySAXHandlerextendsDefaultHandler{
privatebooleanmIsTitleTag=false;privatebooleanmIsSalaryTag=false;privatebooleanmIsBirthTag=false;privateStringmResult="";
//打开xml文档的回调函数@OverridepublicvoidstartDocument()throwsSAXException{//TODOAuto-generatedmethodstubsuper.startDocument();}
//关闭xml文档的回调函数@OverridepublicvoidendDocument()throwsSAXException{//TODOAuto-generatedmethodstubsuper.endDocument();}
//一发现元素开始标记就回调此函数@OverridepublicvoidstartElement(Stringuri,StringlocalName,StringqName,
Attributesattributes)throwsSAXException{if(localName=="title")mIsTitleTag=true;elseif(localName=="salary")mIsSalaryTag=true;elseif(localName=="dateOfBirth")mIsBirthTag=true;elseif(localName=="employee")mResult+
="\nname:"+attributes.getValue("name");}
//一发现元素结束标记就回调此函数@OverridepublicvoidendElement(Stringuri,StringlocalName,StringqName)throwsSAXException{if(localName=="title")mIsTitleTag=false;elseif(localName=="salary")mIsSalaryTag=false;elseif(localName=="dateOfBirth")mIsBirthTag=false;}
//一发现元素值或属性值就回调此函数@Overridepublicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException{if(mIsTitleTag)mResult+=newString(ch,start,length);elseif(mIsSalaryTag)mResult+="salary:"+newString(ch,start,length);elseif(mIsBirthTag)mResult+="dateOfBirth:"+newString(ch,start,length);}
publicStringgetResult(){returnmResult;}}
Main.java
代码packagecom.webabcdmunication;
importjava.io.BufferedInputStream;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.net.URL;importjava.net.URLConnection;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.Map;
importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.parsers.SAXParser;importjavax.xml.parsers.SAXParserFactory;
importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.impl.client.DefaultHttpClient;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.protocol.HTTP;importorg.apache.http.util.ByteArrayBuffer;importorg.apache.http.util.EncodingUtils;importorg.w3c.dom.Document;importorg.w3c.dom.Element;importorg.w3c.dom.NodeList;importorg.xml.sax.InputSource;importorg.xml.sax.XMLReader;
importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.TextView;
publicclassMainextendsActivity{
privateTextViewtextView;
/**Calledwhentheactivityisfirstcreated.*/@Override
publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
textView=(TextView)this.findViewById(R.id.textView);
Buttonbtn1=(Button)this.findViewById(R.id.btn1);btn1.setText("httpgetdemo");btn1.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){httpGetDemo();}});
Buttonbtn2=(Button)this.findViewById(R.id.btn2);btn2.setText("httppostdemo");btn2.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){httpPostDemo();}});
Buttonbtn3=(Button)this.findViewById(R.id.btn3);//DOM-DocumentObjectModelbtn3.setText("DOM解析XML");btn3.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){DOMDemo();}});
Buttonbtn4=(Button)this.findViewById(R.id.btn4);//SAX-SimpleAPIfor
XMLbtn4.setText("SAX解析XML");btn4.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){SAXDemo();}});}
//Android调用http协议的get方法//本例:以http协议的get方法获取远程页面响应的内容privatevoidhttpGetDemo(){
try{//模拟器测试时,请使用外网地址URLurl=newURL("xxx.xxx.xxx");URLConnectioncon=url.openConnection();
Stringresult="httpstatuscode:"+((HttpURLConnection)con).getResponseCode()+"\n";//HttpURLConnection.HTTP_OK
InputStreamis=con.getInputStream();BufferedInputStreambis=newBufferedInputStream(is);ByteArrayBufferbab=newByteArrayBuffer(32);intcurrent=0;while((current=bis.read())!=-1){bab.append((byte)current);}result+=EncodingUtils.getString(bab.toByteArray(),HTTP.UTF_8);
bis.close();is.close();
textView.setText(result);}catch(Exceptione){textView.setText(e.toString());}}
//Android调用http协议的post方法//本例:以http协议的post方法向远程页面传递参数,并获取其响应的内容privatevoidhttpPostDemo(){try{//模拟器测试时,请使用外网地址Stringurl="5billion/post.php";Mapdata=newHashMap();data.put("name","webabcd");data.put("salary","100");
DefaultHttpClienthttpClient=newDefaultHttpClient();HttpPosthttpPost=newHttpPost(url);ArrayListpostData=newArrayList();for(Map.Entrym:data.entrySet()){postData.add(newBasicNameValuePair(m.getKey(),m.getValue()));
}
UrlEncodedFormEntityentity=newUrlEncodedFormEntity(postData,HTTP.UTF_8);httpPost.setEntity(entity);
HttpResponseresponse=httpClient.execute(httpPost);
Stringresult="httpstatuscode:"+response.getStatusLine().getStatusCode()+"\n";//HttpURLConnection.HTTP_OK
HttpEntityhttpEntity=response.getEntity();
InputStreamis=httpEntity.getContent();result+=convertStreamToString(is);
textView.setText(result);}catch(Exceptione){textView.setText(e.toString());}}
//以DOM方式解析XML(xml数据详见res/raw/employee.xml)privatevoidDOMDemo(){try{DocumentBuilderFactorydocFactory=DocumentBuilderFactory.newInstance();DocumentBuilderdocBuilder=docFactory.newDocumentBuilder();Documentdoc=docBuilder.parse(this.getResources().openRawResource(R.raw.employee));ElementrootElement=doc.getDocumentElement();NodeListemployeeNodeList=rootElement.getElementsByTagName("employee");
textView.setText("DOMDemo"+"\n");Stringtitle=rootElement.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();textView.append(title);for(inti=0;i ").item(0).getFirstChild(
).getNodeValue();StringdateOfBirth=employeeElement.getElementsByTagName("dateOfBirth").item(0).getFirstChild().getNodeValue();textView.append("\nname:"+name+"salary:"+salary+"dateOfBirth:"+dateOfBirth);}}catch(Exceptione){textView.setText(e.toString());}}
//以SAX方式解析XML(xml数据详见res/raw/employee.xml)//SAX解析器的实现详见MySAXHandler.javaprivatevoidSAXDemo(){try{SAXParserFactorysaxFactory=SAXParserFactory.newInstance();SAXParserparser=saxFactory.newSAXParser();XMLReaderreader=parser.getXMLReader();
MySAXHandlerhandler=newMySAXHandler();reader.setContentHandler(handler);reader.parse(newInputSource(this.getResources().openRawResource(R.raw.employee)));Stringresult=handler.getResult();textView.setText("SAXDemo"+"\n");textView.append(result);}catch(Exceptione){textView.setText(e.toString());}}
//辅助方法,用于把流转换为字符串privateStringconvertStreamToString(InputStreamis){BufferedReaderreader=newBufferedReader(newInputStreamReader(is));StringBuildersb=newStringBuilder();
Stringline=null;try{while((line=reader.readLine())!=null){sb.append(line+"\n");}}catch(IOExceptione){e.printStackTrace();
}finally{try{is.close();}catch(IOExceptione){e.printStackTrace();}}
returnsb.toString();}}
2、用Handler来实现异步消息处理,以一个可以实时汇报下载进度的异步下载类为例开发一个Android类库,本例中此类库名为webabcd_util
New->JavaProject项目上点右键->BuildPath->AddLibraries->UserLibrary->UserLibraries->New->为类库起个名字->选中这个类库->AddJARs导入Android的jar包项目上点右键->BuildPath->AddLibraries->UserLibrary->选择Android库
DownloadManagerAsync.java
代码packagewebabcd.util;
importjava.io.BufferedReader;importjava.io.File;importjava.io.FileOutputStream;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.net.URL;importjava.net.URLConnection;
importorg.apache.http.protocol.HTTP;
importandroid.os.Handler;importandroid.os.Message;importandroid.util.Log;
//以一个实例,即异步下载,来演示Android的异步消息处理(用Handler的方式)publicclassDownloadManagerAsync{
publicDownloadManagerAsync(){
}
//实例化自定义的HandlerEventHandlermHandler=newEventHandler(this);
//按指定url地址下载文件到指定路径publicvoiddownload(finalStringurl,finalStringsavePath){newThread(newRunnable(){publicvoidrun(){try{sendMessage(FILE_DOWNLOAD_CONNECT);URLsourceUrl=newURL(url);URLConnectionconn=sourceUrl.openConnection();InputStreaminputStream=conn.getInputStream();
intfileSize=conn.getContentLength();
Filesavefile=newFile(savePath);if(savefile.exists()){savefile.delete();}savefile.createNewFile();
FileOutputStreamoutputStream=newF
ileOutputStream(savePath,true);
byte[]buffer=newbyte[1024];intreadCount=0;intreadNum=0;intprevPercent=0;while(readCount-1){outputStream.write(buffer);readCount=readCount+readNum;
intpercent=(int)(readCount*100/fileSize);if(percent>prevPercent){//发送下载进度信息sendMessage(FILE_DOWNLOAD_UPDATE,percent,readCount);
prevPercent=percent;}
}}
outputStream.close();sendMessage(FILE_DOWNLOAD_COMPLETE,savePath);
}catch(Exceptione){sendMessage(FILE_DOWNLOAD_ERROR,e);Log.e("MyError",e.toString());}}}).start();}
//读取指定url地址的响应内容publicvoiddownload(finalStringurl){newThread(newRunnable(){publicvoidrun(){try{sendMessage(FILE_DOWNLOAD_CONNECT);URLsourceUrl=newURL(url);URLConnectionconn=sourceUrl.openConnection();conn.setConnectTimeout(3000);BufferedReaderreader=newBufferedReader(newInputStreamReader(conn.getInputStream(),HTTP.UTF_8));
Stringline=null;StringBuffercontent=newStringBuffer();while((line=reader.readLine())!=null){content.append(line);}
reader.close();
sendMessage(FILE_DOWNLOAD_COMPLETE,content.toString());
}catch(Exceptione){sendMessage(FILE_DOWNLOAD_ERROR,e);Log.e("MyError",e.toString());}}}).start();}
//向Handler发送消息privatevoidsendMessage(intwhat,Objectobj){//构造需要向Handler发送的消息Messagemsg=mHandler.obtainMessage(what,obj);//发送消息mHandler.sendMessage(msg);}
privatevoidsendMessage(intwhat){Messagemsg=mHandler.obtainMessage(what);mHandler.sendMessage(msg);}
privatevoidsendMessage(intwhat,intarg1,intarg2){Messagemsg=mHandler.obtainMessage(what,arg1,arg2);mHandler.sendMessage(msg);}
privatestaticfinalintFILE_DOWNLOAD_CONNECT=0;privatestaticfinalintFILE_DOWNLOAD_UPDATE=1;privatestaticfinalintFILE_DOWNLOAD_COMPLETE=2;privatestaticfinalintFILE_DOWNLOAD_ERROR=-1;
//自定义的HandlerprivateclassEventHandlerextendsHandler{privateDownloadManagerAsyncmManager;
publicEventHandler(DownloadManagerAsyncmanager){mManager=manager;}
//处理接收到的消息@OverridepublicvoidhandleMessage(Messagemsg){
switch(msg.what){caseFILE_DOWNLOAD_CONNECT:if(mOnDownloadConnectListener!=null)mOnDownloadConnectListener.onDownloadConnect(mManager);break;caseFILE_DOWNLOAD_UPDATE:if(mOnDownloadUpdateListener!=null)mOnDownloadUpdateListener.onDownloadUpdate(mManager,
msg.arg1);break;caseFILE_DOWNLOAD_COMPLETE:if(mOnDownloadCompleteListener!=null)mOnDownloadCompleteListener.onDownloadComplete(mManager,msg.obj);break;caseFILE_DOWNLOAD_ERROR:if(mOnDownloadErrorListener!=null)mOnDownloadErrorListener.onDownloadError(mManager,(Exception)msg.obj);break;default:break;}}}
//定义连接事件privateOnDownloadConnectListenermOnDownloadConnectListener;
publicinterfaceOnDownloadConnectListener{voidonDownloadConnect(DownloadManagerAsyncmanager);}publicvoidsetOnDownloadConnectListener(OnDownloadConnectListenerlistener){mOnDownloadConnectListener=listener;}
//定义下载进度更新事件privateOnDownloadUpdateListenermOnDownloadUpdateListener;publicinterfaceOnDownloadUpdateListener{voidonDownloadUpdate(DownloadManagerAsyncmanager,intpercent);}publicvoidsetOnDownloadUpdateListener(OnDownloadUpdateListenerlistener){mOnDownloadUpdateListener=listener;}
//定义下载完成事件privateOnDownloadCompleteListenermOnDownloadCompleteListener;publicinterfaceOnDownloadCompleteListener{voidonDownloadComplete(DownloadManagerAsyncmanager,Objectresult);}publicvoidsetOnDownloadCompleteListener(
OnDownloadCompleteListenerlistener){mOnDownloadCompleteListener=listener;}
//定义下载异常事件privateOnDownloadErrorListenermOnDownloadErrorListener;publicinterfaceOnDownloadErrorListener{voidonDownloadError(DownloadManagerAsyncmanager,Exceptione);}publicvoidsetOnDownloadErrorListener(OnDownloadErrorListenerlistener){mOnDownloadErrorListener=listener;}}
调用上面的自定义的Android类库
项目上点右键->Properties->JavaBuildPath->Projects->Add引用上面的类库
Main.java
代码packagecom.webabcd.handler;
importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;
importwebabcd.util.DownloadManagerAsync;
publicclassMainextendsActivityimplementsDownloadManagerAsync.OnDownloadCompleteListener,DownloadManagerAsync.OnDownloadUpdateListener,DownloadManagerAsync.OnDownloadErrorListener{
TextViewtxt;
/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
DownloadManagerAsyncmanager=newDownloadManagerAsync();manager.setOnDownloadCompleteListener(this);
manager.setOnDownloadUpdateListener(this);manager.download("filesblogs/webabcd/Android.rar","/sdcard/Android.rar");
txt=(TextView)this.findViewById(R.id.txt);txt.setText("开始下载");}
publicvoidonDownloadComplete(DownloadManagerAsyncmanager,Objectresult){
txt.setText("下载完成");}
publicvoidonDownloadUpdate(DownloadManagerAsyncmanager,intpercent){
txt.setText("下载进度:"+String.valueOf(percent)+"%");}
publicvoidonDownloadError(DownloadManagerAsyncmanager,Exceptione){
txt.setText("下载出错");}}
OK[源码下载]