Activity跳转转
Intent intent=newIntent();
Intent.setClass(Activity01.this,Activity01.class);
Activity01.this.startActivity(intent);
如需要传递值过去另外一个Activity
Intent.putExtra(“one”,”one”);
Intent.putExtra(“two”,2)
在另一个Activity中获取
Intentintent=getIntent();
Intent.getStringExtra(“one”);
Intent.getIntExtra(“two”);
//当点击了按钮后,会出发前一个Activity的onPause方法
onPause()
//当获得用户焦点的时候调用的方法,如点击按钮等
onResume()
//当这个Activity的界面可以看到的时候调用onstart方法
onStart()
//当启动完了另一个Activity后,就调用这个Activity的onstop方法
onStop()
// 建立Alert框
new AlertDialog.Builder(Activity01.this).setTitle("提示")
setItems用于设置弹出框的列表
setItems(R.array.item_dialog,
newDialogInterface.OnClickListener() {
@Override
publicvoid onClick(DialogInterface dialog,
int which) {
String strBody = getString(R.string.body);
获取string.xml的数组
String[] arr =getResources().getStringArray(R.array.item_dialog);
newAlertDialog.Builder(Activity01.this)
.setMessage(
strBody + arr[which])表示获取第几个
.setNegativeButton(
…………………………………………..
创建自定义AlertDialog
//创建Dialog对象构造函数中的参数一:Context,参数二:对话框的样式,定义在style.xml中
final Dialog dialog = new Dialog(AlertDialogExample.this,R.style.dialog);
dialog.setContentView(R.layout.myalertdialog);//设置对话框的布局资源文件
final ImageButton cancelBut=(ImageButton)dialog.findViewById(R.id.cancel);//获取对话框上的按钮
cancelBut.setOnClickListener(new OnClickListener(){//"取消"按钮的单击事件
@Override
publicvoid onClick(View v) { // TODO Auto-generated method stub dialog.hide();//隐藏对话框
}
});
dialog.show();
style.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="dialog" parent="@android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item><!--Dialog的边框,@null标识无-->
<item name="android:windowIsFloating">true</item><!--是否浮现在activity之上-->
<item name="android:windowIsTranslucent">false</item><!--半透明-->
<item name="android:windowNoTitle">true</item><!-- 无标题 -->
<item name="android:windowBackground">@null</item><!-- 无背景颜色 -->
<item name="android:backgroundDimEnabled">true</item><!--模糊-->
</style>
</resources>
文件操作
/* 产生Bitmap对象,并放入mImageView中 */
/* 检查文件是否存在 */
String fileName = "/data/data/irdc.ex04_22/ex04_22_2.png";
File f = new File(fileName);
if (f.exists())
Bitmap bm =BitmapFactory.decodeFile(fileName);
mImageView.setImageBitmap(bm);
文本输入设置
/*判断输入的类型是何种,并与系统链接*/
Linkify.addLinks(mTextView01,Linkify.WEB_URLS|Linkify. EMAIL_ADDRESSES|Linkify.PHONE_NUMBERS);
//也可以在main.xml里面进行设置
//android:autoLink="web|phone|E-mial" 也可以设置为all,表示全部
Rotate:旋转效果
// 创建一个AnimationSet对象
AnimationSet as = new AnimationSet(true);
RotateAnimation ra= new RotateAnimation(0, 360,
Animation.RELATIVE_TO_PARENT, 1f,
Animation.RELATIVE_TO_PARENT, 0f);
ra.setDuration(1000);
as.addAnimation(ra);
image.startAnimation(as);
Translate:移动效果
TranslateAnimationra = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 1.0f);
ra.setDuration(2000);
as.addAnimation(ra);
image.startAnimation(as);
Scale:缩放效果
ScaleAnimation ra =new ScaleAnimation(1, 0.1f, 1, 0.1f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
ra.setDuration(2000);
as.addAnimation(ra);
image.startAnimation(as);
// 创建一个AlphaAnimation对象
AlphaAnimation aa =new AlphaAnimation(1, 0);
// 这个动画执行的时间有多长,单位为毫秒
aa.setDuration(1000);
// 将对象添加到animationSet对象中
as.addAnimation(aa);
// 使用imageView的startAnimation方法执行动画
image.startAnimation(as);
publicstaticvoidmain(String[]args){
Thread.currentThread().interrupt();
//下面的判断会打印出来这样的语句Interrupt:false
//这样的结果是不是很让人费解呢???
//分析其原因为:
//因为在上面的一句代码可以中断线程,所以if判断线程是否中断就会得到的事true
但是Thread.interrupted()这个方法执行完后就会清除线程的中断状态, 所以最后再次的打印Thread.interrupted()方法就会得到false结果。 if(Thread.interrupted())
System.out.println("Interrupted:"+Thread.interrupted());
else
{
System.out.println("NotInterrupted"+Thread.interrupted());
}
//如果用下面的这个方法来进行if判断就会出现那种情况了,
//Thread.currentThread().isInterrupted();这个方法得到的结果:Interrupt:true
//因为它判断完后就不会清除线程的中断状态,只是返回一个线程状态的结果
}
/**
* 直接打电话的方法
*/
publicvoid call() {
String data = "tel:" + editText.getText();// 电话号码参数字符串
Uri uri = Uri.parse(data);// 将字符串转化为Uri实例
Intentintent = new Intent();// 实例化Intent
intent.setAction(Intent.ACTION_CALL);// 设置Intent的Action属性
intent.setData(uri);// 设置Intent的Data属性
startActivity(intent);// 启动Activity
}
/**
* 启动一个拨号器的方法
*/
publicvoid dial() {
String data = "tel:" + editText.getText();// 电话号码参数字符串
Uri uri = Uri.parse(data);// 将字符串转化为Uri实例
Intent intent = new Intent();// 实例化Intent
intent.setAction(Intent.ACTION_DIAL);// 设置Intent的Action属性
intent.setData(uri);// 设置Intent的Data属性
startActivity(intent);// 启动Activity
}
this.setTitle("Window Icon"); //设置标题栏上的文字
Window window=this.getWindow(); //获取当前Activity的Window
this.requestWindowFeature(Window.FEATURE_LEFT_ICON); //标题栏左侧显示图标
setContentView(R.layout.main);//设置当前窗体的布局管理文件
this.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.webicon);//设置左侧的图标
<!-- 文字居中 -->
<TextView android:id="@+id/testGravity" android:layout_width="fill_parent"
android:layout_height="wrap_content"android:text="居中文字"
android:gravity="center"android:background="#ff00ff00"
android:textColor="#ff000000"android:textSize="18sp" />
<!-- 文字跑马灯效果 -->
<TextView android:id="@+id/testEllipsize"
android:layout_width="100px"android:layout_height="wrap_content"
android:text="跑马灯文字效果" android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"android:singleLine="true"
android:focusable="true"android:focusableInTouchMode="true"
android:textColor="#ff000000"android:textSize="20sp" />
<!-- 设置文字阴影效果 -->
<TextView android:id="@+id/testShadow" android:layout_width="fill_parent"
android:layout_height="wrap_content"android:text="文字阴影效果"
android:textColor="#ff000000"android:shadowColor="#ffff0000"
android:shadowRadius="3.0"/>
<!-- 设置网址超链接效果 -->
<TextView android:id="@+id/testAutoLink1"
android:layout_width="fill_parent"android:layout_height="wrap_content"
android:text="网址超链接:http://www.baidu.com" android:textColor="#ff000000"
android:autoLink="all"android:textColorLink="#ff0000ff" />
<!-- 设置文字超链接效果 -->
<TextView android:id="@+id/testAutoLink2"
android:layout_width="fill_parent"android:layout_height="wrap_content"
android:text="@string/txtlink"android:textColor="#ff000000" />
<!-- 设置电话超链接效果 -->
<TextView android:id="@+id/testAutoLink2"
android:layout_width="fill_parent"android:layout_height="wrap_content"
android:text="@string/tellink"android:textColor="#ff000000" />
<!-- 设置字形 -->
<TextView android:id="@+id/testTextStyle"
android:layout_width="fill_parent"android:layout_height="wrap_content"
android:text="斜体" android:textColor="#ff000000"android:textStyle="italic" />
<!-- 设置文字缩放 -->
<TextView android:id="@+id/testTextScaleX"
android:layout_width="fill_parent"android:layout_height="wrap_content"
android:text="hello0.5f" android:textColor="#ff000000"
android:textScaleX="0.5"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"android:text="hello 1.0f"
android:textColor="#ff000000"android:textScaleX="1.0" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"android:text="hello 1.5f"
android:textColor="#ff000000"android:textScaleX="1.5" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"android:text="hello 2.0f"
android:textColor="#ff000000"android:textScaleX="2.0" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"android:text="hello 2.5f"
android:textColor="#ff000000"android:textScaleX="2.5" />
<!-- 设置行间距 -->
<TextView android:id="@+id/testLineSpacingExtra"
android:layout_width="fill_parent"android:layout_height="wrap_content"
android:text="@string/lineheight1"android:textColor="#ff000000"
android:lineSpacingExtra="4px"/>
<!-- 设置行间距的倍数 -->
<TextView android:id="@+id/testLineSpacingMultiplier"
android:layout_width="fill_parent"android:layout_height="wrap_content"
android:text="@string/lineheight2"android:textColor="#ff000000"
android:lineSpacingMultiplier="1.5"/>
//调用style.xml文件
<TextView style="@style/DefineTextStyle" android:layout_width="fill_parent"
android:layout_height="wrap_content"android:text="@string/hello"
/>
Style.xml文件
<resources>
<style name="DefineTextStyle">
<item name="android:textSize">28px</item>
<item name="android:textColor">@color/darkgreen</item>
<item name="android:gravity">center</item>
<item name="android:textStyle">bold|italic</item>
<item name="android:background">@color/pink</item>
</style>
</resources>
<!--
ScrollView标签为滚动view标签,当内容超出窗口可视范围会自动出现滚动条
android:scrollbarThumbVertical:指定滚动条的背景图片
-->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"android:layout_width="fill_parent"
android:layout_height="fill_parent"android:background="#ffF4F4F4"
android:fadingEdge="vertical"android:fadingEdgeLength="100px"
android:scrollbarThumbVertical="@drawable/scrollbackground">
//获取String.xml文件里面的drawaable的white值
Resourcesres=getBaseContext().getResources();
Drawable dr=res.getDrawable(R.drawable.white);
//设为背景色
tv.setBackgroundDrawable(dr);
//要获取手机分辨率要使用util.DisplayMetrics
DisplayMetrics dm=new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
String strOpt="这是手机屏幕的分辨率:"+dm.widthPixels+"*"+dm.heightPixels;
TextViewfenbian=(TextView) findViewById(R.id.fenbianlv);
fenbian.setText(strOpt);
在第一个Activity:
传递数值(对象)给另一个Activity
/* 新建一个Intent对象 */
Intent intent = new Intent();
/* 指定intent要启动的类 */
intent.setClass(Activity01.this, Activity02.class);
/* 创建Bundler对象,用于传递数据给下一个Activity */
Bundle b = new Bundle();
b.putString("key", "值");
/* 将Bundler对象assign给intent */
intent.putExtras(b);
//调用返回值方法
startActivityForResult(intent,0);
在第二个Activity:
//获取前面Activity传过来的数据
//获取Intent中的Bundle对象
Intent intent=this.getIntent();
Bundle b=intent.getExtras();
//获取Bundler的对象
Stringvalue=b.getString("key");
TextViewt=(TextView) findViewById(R.id.go);
t.setText("获取前一个Acitivity的值:"+value);
在第二个Activity:
//用于将值传回给第一个Acitivity的案例代码
Activity02.this.setResult(RESULT_OK, intent);
//关闭当前Activity02
Activity02.this.finish();
在第一个Activity:
// 用于获取Activity返回过来的值
@Override
protectedvoid onActivityResult(intrequestCode, int resultCode, Intent data) {
switch (resultCode) {
caseRESULT_OK:
/* 取得来自Activity2的数据,显示到TextView中 */
Bundle b = data.getExtras();
String value = b.getString("key");
Button t = (Button)findViewById(R.id.button1);
t.setText(value);
break;
default:
break;
}
}
//得到ContentResolver对象
ContentResolver cr =getContentResolver();
//取得电话本中开始一项的光标
Cursor cursor =cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
//向下移动一下光标
while(cursor.moveToNext())
{
//取得联系人名字
int nameFieldColumnIndex= cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
Stringcontact = cursor.getString(nameFieldColumnIndex);
//取得电话号码
int numberFieldColumnIndex =cursor.getColumnIndex(PhoneLookup.NUMBER);
Stringnumber = cursor.getString(numberFieldColumnIndex);
string+= (contact+":"+number+"\n");
}
cursor.close();
//设置TextView显示的内容
tv.setText(string);
//显示到屏幕
setContentView(tv);
/* 按键按下所触发的事件 */
publicboolean onKeyDown(int keyCode,KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_DPAD_CENTER:
DisplayToast("按下:中键");
break;
case KeyEvent.KEYCODE_DPAD_UP:
DisplayToast("按下:上方向键");
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
DisplayToast("按下:下方向键");
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
DisplayToast("按下:左方向键");
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
DisplayToast("按下:右方向键");
break;
}
returnsuper.onKeyDown(keyCode, event);
}
/* 按键弹起所触发的事件 */
publicboolean onKeyUp(int keyCode,KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_DPAD_CENTER:
DisplayToast("弹起:中键");
break;
case KeyEvent.KEYCODE_DPAD_UP:
DisplayToast("弹起:上方向键");
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
DisplayToast("弹起:下方向键");
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
DisplayToast("弹起:左方向键");
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
DisplayToast("弹起:右方向键");
break;
}
returnsuper.onKeyUp(keyCode, event);
}
/* 触笔事件 */
publicboolean onTouchEvent(MotionEvent event)
{
int iAction = event.getAction();
if (iAction ==MotionEvent.ACTION_CANCEL ||
iAction == MotionEvent.ACTION_DOWN ||
iAction == MotionEvent.ACTION_MOVE)
{
returnfalse;
}
//得到触笔点击的位置
int x = (int) event.getX();
int y = (int) event.getY();
DisplayToast("触笔点击坐标:("+Integer.toString(x)+","+Integer.toString(y)+")");
returnsuper.onTouchEvent(event);
}
publicboolean onKeyDown(int keyCode,KeyEvent event)
{
//这里构建KeyEvent对象,其功能为返回键的功能
//因此我们按任意键都会执行返回键功能
KeyEvent key = newKeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
//这里传入的参数就是我们自己构建的KeyEvent对象key
returnsuper.onKeyDown(key.getKeyCode(), key);
}
例子:
/* 创建LinearLayout布局对象 */
m_LinearLayout = newLinearLayout(this);
/* 设置布局LinearLayout的属性 */
m_LinearLayout.setOrientation(LinearLayout.VERTICAL);
m_LinearLayout.setBackgroundColor(android.graphics.Color.BLACK);
/* 创建ListView对象 */
m_ListView = new ListView(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
m_ListView.setBackgroundColor(Color.BLACK);
/* 添加m_ListView到m_LinearLayout布局 */
m_LinearLayout.addView(m_ListView, param);
/* 设置显示m_LinearLayout布局 */
setContentView(m_LinearLayout);
// 获取数据库Phones的Cursor
Cursor cur = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
startManagingCursor(cur);
//ListAdapter是ListView和后台数据的桥梁
ListAdapter adapter = new SimpleCursorAdapter(this,
// 定义List中每一行的显示模板
// 表示每一行包含两个数据项
android.R.layout.simple_list_item_2,
// 数据库的Cursor对象
cur,
// 从数据库的NAME和NUMBER两列中取数据
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.NUMBER },
// 与NAME和NUMBER对应的Views
newint[] { android.R.id.text1,android.R.id.text2 });
/* 将adapter添加到m_ListView中 */
m_ListView.setAdapter(adapter);
/* 为m_ListView视图添加setOnItemSelectedListener监听 */
m_ListView
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
publicvoid onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
DisplayToast("滚动到第"
+Long.toString(arg0.getSelectedItemId()) + "项");
}
@Override
publicvoid onNothingSelected(AdapterView<?> arg0) {
// 没有选中
}
});
/* 为m_ListView视图添加setOnItemClickListener监听 */
m_ListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
publicvoid onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// 于对选中的项进行处理
DisplayToast("选中了第" + Integer.toString(arg2 + 1) + "项");
}
});
}
Toast toast =Toast.makeText(this, str, Toast.LENGTH_LONG);
//设置toast显示的位置
toast.setGravity(Gravity.TOP, 0, 220);
//显示该Toast
toast.show();
例子
privatestaticfinalString[] m_Countries = { "O型", "A型", "B型", "AB型", "其他" };
//将可选内容与ArrayAdapter连接
adapter = newArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_Countries);
//设置下拉列表的风格
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//将adapter添加到m_Spinner中
m_Spinner.setAdapter(adapter);
//添加Spinner事件监听
m_Spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
publicvoid onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
m_TextView.setText("你的血型是:" + m_Countries[arg2]);
//设置显示当前选择的项
arg0.setVisibility(View.VISIBLE);
}
@Override
publicvoid onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
例子
privatestaticfinalString[] autoString= new String[] { "a2", "abf", "abe", "abcde", "abc2", "abcd3", "abcde2", "abc2", "abcd2", "abcde2" };
//关联关键字
ArrayAdapter<String> adapter = newArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, autoString);
AutoCompleteTextView m_AutoCompleteTextView = (AutoCompleteTextView)findViewById(R.id.AutoCompleteTextView01);
//将adapter添加到AutoCompleteTextView中
m_AutoCompleteTextView.setAdapter(adapter);
///////////////////
MultiAutoCompleteTextView mm_AutoCompleteTextView =(MultiAutoCompleteTextView) findViewById(R.id.MultiAutoCompleteTextView01);
//将adapter添加到AutoCompleteTextView中
mm_AutoCompleteTextView.setAdapter(adapter);
mm_AutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
例子
//获得Gallery对象
Gallery g = (Gallery) findViewById(R.id.Gallery01);
//添加ImageAdapter给Gallery对象
g.setAdapter(new ImageAdapter(this));
//设置Gallery的背景
g.setBackgroundResource(R.drawable.bg0);
//设置Gallery的事件监听
g.setOnItemClickListener(new OnItemClickListener() {
publicvoid onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Toast.makeText(Activity01.this,"你选择了"+(position+1)+" 号图片",
Toast.LENGTH_SHORT).show();
}
});
ImageAdapter:
// 定义Context
private Context mContext;
// 定义整型数组即图片源
private Integer[] mImageIds =
{
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6,
R.drawable.img7,
R.drawable.img8,
};
// 声明 ImageAdapter
public ImageAdapter(Context c)
{
mContext = c;
}
// 获取图片的个数
publicint getCount()
{
returnmImageIds.length;
}
// 获取图片在库中的位置
public Object getItem(int position)
{
return position;
}
// 获取图片ID
publiclong getItemId(int position)
{
return position;
}
public View getView(int position,View convertView, ViewGroup parent)
{
ImageView imageview = new ImageView(mContext);
// 给ImageView设置资源
imageview.setImageResource(mImageIds[position]);
// 设置布局图片120¡Á120显示
imageview.setLayoutParams(new Gallery.LayoutParams(120, 120));
// 设置显示比例类型
imageview.setScaleType(ImageView.ScaleType.FIT_CENTER);
return imageview;
}
例子:
//声明通知(消息)管理器
NotificationManager m_NotificationManager;
Intent m_Intent;
PendingIntent m_PendingIntent;
//声明Notification对象
Notification m_Notification;
//初始化NotificationManager对象
m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//点击通知时转移内容
m_Intent = newIntent(Activity01.this, Activity02.class);
//主要是设置点击通知时显示内容的类
m_PendingIntent = PendingIntent.getActivity(Activity01.this, 0, m_Intent, 0);
//构造Notification对象
m_Notification = newNotification();
m_Button1.setOnClickListener(new Button.OnClickListener() {
publicvoid onClick(View v)
{
//设置通知在状态栏显示的图标
m_Notification.icon = R.drawable.img1;
//当我们点击通知时显示的内容
m_Notification.tickerText = "Button1通知内容...........";
//通知时发出默认的声音
m_Notification.defaults = Notification.DEFAULT_SOUND;
//设置通知显示的参数
m_Notification.setLatestEventInfo(Activity01.this, "Button1", "Button1通知", m_PendingIntent);
//可以理解为执行这个通知
m_NotificationManager.notify(0, m_Notification);
}
});
m_Button2.setOnClickListener(newButton.OnClickListener() {
publicvoid onClick(View v)
{
m_Notification.icon = R.drawable.img2;
m_Notification.tickerText = "Button2通知内容...........";
//通知时震动
m_Notification.defaults = Notification.DEFAULT_VIBRATE;
m_Notification.setLatestEventInfo(Activity01.this, "Button2", "Button2通知", m_PendingIntent);
m_NotificationManager.notify(0, m_Notification);
}
});
m_Button3.setOnClickListener(new Button.OnClickListener() {
publicvoid onClick(View v)
{
m_Notification.icon = R.drawable.img3;
m_Notification.tickerText = "Button3通知内容...........";
//通知时屏幕发亮
m_Notification.defaults = Notification.DEFAULT_LIGHTS;
m_Notification.setLatestEventInfo(Activity01.this, "Button3", "Button3通知", m_PendingIntent);
m_NotificationManager.notify(0, m_Notification);
}
});
m_Button4.setOnClickListener(new Button.OnClickListener() {
publicvoid onClick(View v)
{
m_Notification.icon = R.drawable.img4;
m_Notification.tickerText = "Button4通知内容..........";
//通知时既震动又屏幕发亮还有默认的声音
m_Notification.defaults = Notification.DEFAULT_ALL;
m_Notification.setLatestEventInfo(Activity01.this, "Button4", "Button4通知", m_PendingIntent);
m_NotificationManager.notify(0, m_Notification);
}
});
圆形
//创建ProgressDialog对象
m_pDialog = new ProgressDialog(Activity01.this);
// 设置进度条风格,风格为圆形,旋转的
m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// 设置ProgressDialog 标题
m_pDialog.setTitle("提示");
// 设置ProgressDialog 提示信息
m_pDialog.setMessage("这是一个圆形进度条对话框");
// 设置ProgressDialog 标题图标
m_pDialog.setIcon(R.drawable.img1);
// 设置ProgressDialog 的进度条是否不明确
m_pDialog.setIndeterminate(false);
// 设置ProgressDialog 是否可以按退回按键取消
m_pDialog.setCancelable(true);
// 设置ProgressDialog 的一个Button
m_pDialog.setButton("确定", new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dialog, int i)
{
//点击“确定按钮”取消对话框
dialog.cancel();
}
});
// 让ProgressDialog显示
m_pDialog.show();
长弹出框:
m_count = 0;
// 创建ProgressDialog对象
m_pDialog = new ProgressDialog(Activity01.this);
// 设置进度条风格,风格为长形
m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// 设置ProgressDialog 标题
m_pDialog.setTitle("提示");
// 设置ProgressDialog 提示信息
m_pDialog.setMessage("这是一个长形对话框进度条");
// 设置ProgressDialog 标题图标
m_pDialog.setIcon(R.drawable.img2);
// 设置ProgressDialog 进度条进度
m_pDialog.setProgress(100);
// 设置ProgressDialog 的进度条是否不明确
m_pDialog.setIndeterminate(false);
// 设置ProgressDialog 是否可以按退回按键取消
m_pDialog.setCancelable(true);
// 让ProgressDialog显示
m_pDialog.show();
new Thread()
{
publicvoid run()
{
try
{
while (m_count <= 100)
{
// 由线程来控制进度。
m_pDialog.setProgress(m_count++);
Thread.sleep(100);
}
m_pDialog.cancel();
}
catch(InterruptedException e)
{
m_pDialog.cancel();
}
}
}.start();
例子:
//取得TabHost对象
mTabHost = getTabHost();
/* 为TabHost添加标签 */
//新建一个newTabSpec(newTabSpec)
//设置其标签和图标(setIndicator)
//设置内容(setContent)
mTabHost.addTab(mTabHost.newTabSpec("tab_test1")
.setIndicator("TAB 1",getResources().getDrawable(R.drawable.img1))
.setContent(R.id.textview1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2")
.setIndicator("TAB 2",getResources().getDrawable(R.drawable.img2))
.setContent(R.id.textview2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3")
.setIndicator("TAB 3",getResources().getDrawable(R.drawable.img3))
.setContent(R.id.textview3));
//设置TabHost的背景颜色
mTabHost.setBackgroundColor(Color.argb(150, 22, 70, 150));
//设置TabHost的背景图片资源
//mTabHost.setBackgroundResource(R.drawable.bg0);
//设置当前显示哪一个标签
mTabHost.setCurrentTab(0);
//标签切换事件处理,setOnTabChangedListener
mTabHost.setOnTabChangedListener(newOnTabChangeListener()
{
// TODO Auto-generated method stub
@Override
publicvoid onTabChanged(String tabId)
{
Dialogdialog = new AlertDialog.Builder(Activity01.this)
.setTitle("提示")
.setMessage("当前选中:"+tabId+"标签")
.setPositiveButton("确定",
new DialogInterface.OnClickListener()
{
publicvoid onClick(DialogInterface dialog, int whichButton)
{
dialog.cancel();
}
}).create();//创建按钮
dialog.show();
}
});
例子:
/* 取得屏幕分辨率大小 */
DisplayMetrics dm=new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
displayWidth=dm.widthPixels;
/* 屏幕高度须扣除下方Button高度 */
displayHeight=dm.heightPixels-80;
/* 初始化相关变量 */
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.ex04_23);
/* 图片缩小的method */
privatevoid small()
{
int bmpWidth=bmp.getWidth();
int bmpHeight=bmp.getHeight();
/* 设定图片缩小的比例 */
doublescale=0.8;
/* 计算出这次要缩小的比例 */
scaleWidth=(float) (scaleWidth*scale);
scaleHeight=(float) (scaleHeight*scale);
/* 生成reSize后的Bitmap对象 */
Matrix matrix = newMatrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizeBmp = Bitmap.createBitmap(bmp,0,0,bmpWidth,bmpHeight,matrix,true);
if(id==0)
{
/* 如果是第一次按,就移除原来设定的ImageView */
layout1.removeView(mImageView);
}
else
{
/* 如果不是第一次按,就移除上次放大缩小所生成的ImageView*/
layout1.removeView((ImageView)findViewById(id));
}
/* 产生新的ImageView,放入reSize的Bitmap对象,再放入Layout中 */
id++;
ImageView imageView = new ImageView(EX04_23.this);
imageView.setId(id);
imageView.setImageBitmap(resizeBmp);
layout1.addView(imageView);
setContentView(layout1);
/* 因为图片放到最大时放大按钮会disable,所以在缩小时把他重设为enable */
mButton02.setEnabled(true);
}
/* 图片放大的method */
privatevoid big()
{
int bmpWidth=bmp.getWidth();
int bmpHeight=bmp.getHeight();
/* 设定图片放大的比例 */
doublescale=1.25;
/* 计算这次要放大的比例 */
scaleWidth=(float)(scaleWidth*scale);
scaleHeight=(float)(scaleHeight*scale);
/* 产生reSize后的Bitmap对象 */
Matrix matrix = newMatrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizeBmp = Bitmap.createBitmap(bmp,0,0,bmpWidth,bmpHeight,matrix,true);
if(id==0)
{
/* 如果是第一次按,就移除原来设定的ImageView */
layout1.removeView(mImageView);
}
else
{
/* 如果不是第一次按,就移除上次放大缩小所生成的ImageView*/
layout1.removeView((ImageView)findViewById(id));
}
/* 产生新的ImageView,放入reSize的Bitmap对象,再放入Layout中 */
id++;
ImageView imageView = new ImageView(EX04_23.this);
imageView.setId(id);
imageView.setImageBitmap(resizeBmp);
layout1.addView(imageView);
setContentView(layout1);
/* 如果再放大会超过屏幕大小,就把Button disable */
if(scaleWidth*scale*bmpWidth>displayWidth||scaleHeight*scale*bmpHeight>displayHeight)
{
mButton02.setEnabled(false);
}
}
例子:
publicboolean onKeyDown(int keyCode,KeyEvent event)
{
if (keyCode ==KeyEvent.KEYCODE_BACK)
{
//退出应用程序时保存数据
/* 发送邮件的地址 */
Uri uri = Uri.parse("mailto:[email protected]");
/* 创建Intent */
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
/* 设置邮件的主题 */
it .putExtra(android.content.Intent.EXTRA_SUBJECT, "数据备份");
/* 设置邮件的内容 */
it .putExtra(android.content.Intent.EXTRA_TEXT, "本次计数:"+miCount);
/* 开启 */
startActivity(it);
this.finish();
returntrue;
}
returnsuper.onKeyDown(keyCode, event);
}
例子:
TextView tv = new TextView(this);
String myString = null;
try
{
/* 定义我们要访问的地址url */
URL uri = new URL("http://192.168.1.110:8080/android.txt");
/* 打开这个url连接 */
URLConnection ucon =uri.openConnection();
/* 从上面的链接中取得InputStream */
InputStream is =ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(100);
int current =0;
/* 一直读到文件结束 */
while ((current =bis.read()) != -1)
{
baf.append((byte) current);
}
myString = new String(baf.toByteArray());
}
catch (Exceptione)
{
myString = e.getMessage();
}
/* 将信息设置到TextView */
tv.setText(myString);
/* 将TextView显示到屏幕上 */
this.setContentView(tv);
例子:
public class Activity01 extends Activity
{
private static int miCount = 0;
/* 数据库对象 */
private SQLiteDatabase mSQLiteDatabase = null;
/* 数据库名 */
private final static String DATABASE_NAME ="Examples_06_05.db";
/* 表名 */
private final static String TABLE_NAME ="table1";
/* 表中的字段 */
private final static String TABLE_ID ="_id";
private final static String TABLE_NUM ="num";
private final static String TABLE_DATA ="data";
/* 创建表的sql语句 */
private final static String CREATE_TABLE ="CREATE TABLE " + TABLE_NAME + " (" + TABLE_ID + "INTEGER PRIMARY KEY," + TABLE_NUM + " INTERGER,"+ TABLE_DATA +" TEXT)";
/* 线性布局 */
LinearLayout m_LinearLayout = null;
/* 列表视图-显示数据库中的数据 */
ListView m_ListView =null;
/** Called when the activity isfirst created. */
@Override
public void onCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);
/* 创建LinearLayout布局对象 */
m_LinearLayout = new LinearLayout(this);
/* 设置布局LinearLayout的属性 */
m_LinearLayout.setOrientation(LinearLayout.VERTICAL);
m_LinearLayout.setBackgroundColor(android.graphics.Color.BLACK);
/* 创建ListView对象 */
m_ListView = newListView(this);
LinearLayout.LayoutParams param= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
m_ListView.setBackgroundColor(Color.BLACK);
/* 添加m_ListView到m_LinearLayout布局 */
m_LinearLayout.addView(m_ListView,param);
/* 设置显示m_LinearLayout布局 */
setContentView(m_LinearLayout);
// 打开已经存在的数据库
mSQLiteDatabase =this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
// 获取数据库Phones的Cursor
try
{
/* 在数据库mSQLiteDatabase中创建一个表 */
mSQLiteDatabase.execSQL(CREATE_TABLE);
}
catch (Exception e)
{
UpdataAdapter();
}
}
public boolean onKeyUp(intkeyCode, KeyEvent event)
{
switch (keyCode)
{
caseKeyEvent.KEYCODE_DPAD_LEFT:
AddData();
break;
caseKeyEvent.KEYCODE_DPAD_RIGHT:
DeleteData();
break;
case KeyEvent.KEYCODE_1:
UpData();
break;
case KeyEvent.KEYCODE_2:
DeleteTable();
break;
case KeyEvent.KEYCODE_3:
DeleteDataBase();
break;
}
return true;
}
/* 删除数据库 */
public void DeleteDataBase()
{
this.deleteDatabase(DATABASE_NAME);
this.finish();
}
/* 删除一个表 */
public void DeleteTable()
{
mSQLiteDatabase.execSQL("DROPTABLE " + TABLE_NAME);
this.finish();
}
/* 更新一条数据 */
public void UpData()
{
ContentValues cv = new ContentValues();
cv.put(TABLE_NUM, miCount);
cv.put(TABLE_DATA, "修改后的数据" + miCount);
/* 更新数据 */
mSQLiteDatabase.update(TABLE_NAME,cv, TABLE_NUM + "=" + Integer.toString(miCount - 1), null);
UpdataAdapter();
}
/* 向表中添加一条数据 */
public void AddData()
{
ContentValues cv = newContentValues();
cv.put(TABLE_NUM, miCount);
cv.put(TABLE_DATA, "测试数据库数据" + miCount);
/* 插入数据 */
mSQLiteDatabase.insert(TABLE_NAME,null, cv);
miCount++;
UpdataAdapter();
}
/* 从表中删除指定的一条数据 */
public void DeleteData()
{
/* 删除数据 */
mSQLiteDatabase.execSQL("DELETEFROM " + TABLE_NAME + " WHERE _id=" +Integer.toString(miCount));
miCount--;
if (miCount < 0)
{
miCount = 0;
}
UpdataAdapter();
}
/* 更行试图显示 */
public void UpdataAdapter()
{
// 获取数据库Phones的Cursor
Cursor cur =mSQLiteDatabase.query(TABLE_NAME, new String[] { TABLE_ID, TABLE_NUM,TABLE_DATA }, null, null, null, null, null);
miCount = cur.getCount();
if (cur != null &&cur.getCount() >= 0)
{
// ListAdapter是ListView和后台数据的桥梁
ListAdapter adapter = newSimpleCursorAdapter(this,
// 定义List中每一行的显示模板
// 表示每一行包含两个数据项
android.R.layout.simple_list_item_2,
// 数据库的Cursor对象
cur,
// 从数据库的TABLE_NUM和TABLE_DATA两列中取数据
new String[] {TABLE_NUM, TABLE_DATA },
// 与NAME和NUMBER对应的Views
new int[] {android.R.id.text1, android.R.id.text2 });
/* 将adapter添加到m_ListView中 */
m_ListView.setAdapter(adapter);
}
}
/* 按键事件处理 */
public boolean onKeyDown(intkeyCode, KeyEvent event)
{
if (keyCode ==KeyEvent.KEYCODE_BACK)
{
/* 退出时,不要忘记关闭 */
mSQLiteDatabase.close();
this.finish();
return true;
}
returnsuper.onKeyDown(keyCode, event);
}
}
例子:
/* 取得EditText中用户输入的字符串 */
String strInput = mEditText1.getText().toString();
if (isPhoneNumberValid(strInput) == true) {
/* 建构一个新的Intent并执行action.CALL的常数与透过Uri将字符串带入 */
Intent myIntentDial = new Intent(
"android.intent.action.CALL", Uri.parse("tel:"
+ strInput));
/* 在startActivity()方法中带入自定义的Intent对象以执行拨打电话的工作 */
startActivity(myIntentDial);
mEditText1.setText("");
} else {
mEditText1.setText("");
Toast.makeText(EX05_02.this, "输入的电话格式不符",
Toast.LENGTH_LONG).show();
}
/* 检查字符串是否为电话号码的方法,并回传true or false的判断值 */
publicstaticboolean isPhoneNumberValid(String phoneNumber) {
boolean isValid = false;
/*
* 可接受的电话格式有: * ^\\(? : 可以使用 "(" 作为开头 * (\\d{3}): 紧接着三个数字 * \\)? :
* 可以使用")"接续 * [- ]? : 在上述格式后可以使用具选择性的 "-". * (\\d{3}) : 再紧接着三个数字 * [-
* ]? : 可以使用具选择性的 "-" 接续. * (\\d{4})$: 以四个数字结束. * 可以比对下列数字格式: *
* (123)456-7890,123-456-7890, 1234567890, (123)-456-7890
*/
String expression = "^\\(?(\\d{3})\\)?[-]?(\\d{3})[- ]?(\\d{4})$";
String expression2 = "^\\(?(\\d{2})\\)?[-]?(\\d{4})[- ]?(\\d{4})$";
CharSequence inputStr = phoneNumber;
/* 建立Pattern */
Pattern pattern = Pattern.compile(expression);
/* 将Pattern 以参数传入Matcher作Regularexpression */
Matcher matcher = pattern.matcher(inputStr);
/* 建立Pattern2 */
Pattern pattern2 = Pattern.compile(expression2);
/* 将Pattern2 以参数传入Matcher2作Regularexpression */
Matcher matcher2 = pattern2.matcher(inputStr);
if (matcher.matches() || matcher2.matches()) {
isValid = true;
}
return isValid;
}
例子:
/*由EditText1取得简讯收件人电话*/
String strDestAddress = mEditText1.getText().toString();
/*由EditText2取得简讯文字内容*/
String strMessage = mEditText2.getText().toString();
/*建构一取得default instance的 SmsManager对象 */
SmsManager smsManager = SmsManager.getDefault();
// TODO Auto-generatedmethod stub
/*检查收件人电话格式与简讯字数是否超过70字符*/
if(isPhoneNumberValid(strDestAddress)==true && iswithin70(strMessage)==true)
{
try
{
/*两个条件都检查通过的情况下,发送简讯 *
* 先建构一PendingIntent对象并使用getBroadcast()方法进行Broadcast *
* 将PendingIntent,电话,简讯文字等参数传入sendTextMessage()方法发送简讯*/
PendingIntent mPI = PendingIntent.getBroadcast(EX05_03.this, 0, new Intent(), 0);
smsManager.sendTextMessage(strDestAddress, null, strMessage, mPI, null);
}
catch(Exception e)
{
e.printStackTrace();
}
Toast.makeText(EX05_03.this, "送出成功!!" , Toast.LENGTH_SHORT).show();
mEditText1.setText("");
mEditText2.setText("");
}
/*电话格式与简讯文字不符合条件时,使用Toast告知用户检查*/
else
{
/*电话格式不符*/
if (isPhoneNumberValid(strDestAddress)==false)
{
/*且字数超过70字符*/
if(iswithin70(strMessage)==false)
{
Toast.makeText(EX05_03.this, "电话号码格式错误+短信内容超过70字,请检查!!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(EX05_03.this, "电话号码格式错误,请检查!!" , Toast.LENGTH_SHORT).show();
}
}
/*字数超过70字符*/
elseif (iswithin70(strMessage)==false)
{
Toast.makeText(EX05_03.this, "短信内容超过70字,请删除部分内容!!", Toast.LENGTH_SHORT).show();
}
}
}
});
}
/*检查字符串是否为电话号码的方法,并回传true or false的判断值*/
publicstaticboolean isPhoneNumberValid(String phoneNumber)
{
boolean isValid = false;
/* 可接受的电话格式有: * ^\\(? : 可以使用 "(" 作为开头 * (\\d{3}):
* 紧接着三个数字 * \\)? : 可以使用")"接续 * [- ]? :
* 在上述格式后可以使用具选择性的 "-". * (\\d{3}) :
* 再紧接着三个数字 * [- ]? :
* 可以使用具选择性的 "-" 接续. * (\\d{4})$:
* 以四个数字结束. * 可以比对下列数字格式:
** (123)456-7890, 123-456-7890, 1234567890, (123)-456-7890 */
String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
/* 可接受的电话格式有: * ^\\(? :
* 可以使用 "(" 作为开头 * (\\d{2}):
* 紧接着两个数字 * \\)? : 可以使用")"接续 * [- ]? :
* 在上述格式后可以使用具选择性的 "-". * (\\d{4}) :
* 再紧接着四个数字 * [- ]? :
* 可以使用具选择性的 "-" 接续. * (\\d{4})$:
* 以四个数字结束. * 可以比对下列数字格式: *
*(123)456-7890, 123-456-7890, 1234567890, (123)-456-7890 */
String expression2 ="^\\(?(\\d{2})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
CharSequence inputStr = phoneNumber;
/*建立Pattern*/ Pattern pattern = Pattern.compile(expression);
/*将Pattern 以参数传入Matcher作Regularexpression*/
Matcher matcher =pattern.matcher(inputStr);
/*建立Pattern2*/ Pattern pattern2 =Pattern.compile(expression2);
/*将Pattern2 以参数传入Matcher2作Regularexpression*/
Matcher matcher2=pattern2.matcher(inputStr);
if(matcher.matches()||matcher2.matches())
{
isValid = true;
}
return isValid;
}
publicstaticboolean iswithin70(String text)
{
if (text.length()<= 70)
returntrue;
else
returnfalse;
}
}
例子:
@Override
publicboolean onKey(View v, int keyCode, KeyEventevent)
{
// TODO Auto-generatedmethod stub
/*若使用者键入为正规email文字,则enable 按钮反之则disable 按钮*/
if(isEmail(mEditText01.getText().toString()))
{
mButton01.setEnabled(true);
}
else
{
mButton01.setEnabled(false);
}
returnfalse;
}
});
/*设定onClickListener 让使用者点选Button时送出email*/
mButton01.setOnClickListener(new Button.OnClickListener()
{
@Override
publicvoid onClick(View v)
{
// TODO Auto-generatedmethod stub
/*透过Intent来发送邮件*/
Intent mEmailIntent =
new Intent(android.content.Intent.ACTION_SEND);
/*设定邮件格式为plain/text*/
mEmailIntent.setType("plain/text");
/*取得EditText01,02,03,04的值作为收件人地址,附件,主题,内容*/
strEmailReciver = new String[]{mEditText01.getText().toString()};
strEmailCc = new String[]{mEditText02.getText().toString()};
strEmailSubject = mEditText03.getText().toString();
strEmailBody = mEditText04.getText().toString();
/*将取得的字符串放入mEmailIntent中*/
mEmailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, strEmailReciver);
mEmailIntent.putExtra(android.content.Intent.EXTRA_CC, strEmailCc);
mEmailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, strEmailSubject);
mEmailIntent.putExtra(android.content.Intent.EXTRA_TEXT, strEmailBody);
/*开启Gmail并将相关参数传入*/
startActivity(Intent.createChooser(mEmailIntent,getResources().getString(R.string.str_message)));
}
});
}
/*确认字符串是否为email格式并回传true or false*/
publicstaticboolean isEmail(String strEmail)
{
String strPattern = "^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strEmail);
return m.matches();
}
}
显示具有图片的Toast:
// TODO Auto-generatedmethod stub
ImageView mView01 = new ImageView(EX05_07.this);
TextView mTextView = new TextView(EX05_07.this);
LinearLayout lay = newLinearLayout(EX05_07.this);
/*设定mTextView去抓取string值*/
mTextView.setText(R.string.app_url);
/*判断mTextView的内容为何,并与系统做链接*/
Linkify.addLinks(mTextView,Linkify.WEB_URLS| Linkify.EMAIL_ADDRESSES|Linkify.PHONE_NUMBERS);
/*用Toast方式显示*/
Toast toast = Toast.makeText(EX05_07.this, mTextView.getText(), Toast.LENGTH_LONG);
View textView = toast.getView();lay.setOrientation(LinearLayout.HORIZONTAL);
/*在Toast里加上图片*/
mView01.setImageResource(R.drawable.icon);
/*在Toast里显示图片*/lay.addView(mView01);
/*在Toast里显示文字*/lay.addView(textView);
toast.setView(lay);
toast.show();
例子:
/*声明对象变量*/
private NotificationManager myNotiManager;
private Spinner mySpinner;
private ArrayAdapter<String> myAdapter;
privatestaticfinal String[] status =
{ "在线","离开","忙碌中","马上回来","脱机" };
@Override
protectedvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
/* 载入main.xml Layout */
setContentView(R.layout.main);
/* 初始化对象 */
myNotiManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mySpinner=(Spinner)findViewById(R.id.mySpinner);
myAdapter=new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,status);
/* 套用myspinner_dropdown自定义下拉菜单样式 */
myAdapter.setDropDownViewResource(R.layout.myspinner_dropdown);
/* 将ArrayAdapter加入Spinner对象中 */
mySpinner.setAdapter(myAdapter);
/* 将mySpinner加入OnItemSelectedListener */
mySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
{
@Override
publicvoid onItemSelected(AdapterView<?>arg0,View arg1,
int arg2,long arg3)
{
/* 依照选择的item来判断要发哪一个notification */
if(status[arg2].equals("在线"))
{
setNotiType(R.drawable.msn,"在线");
}
elseif(status[arg2].equals("离开"))
{
setNotiType(R.drawable.away,"离开");
}
elseif(status[arg2].equals("忙碌中"))
{
setNotiType(R.drawable.busy,"忙碌中");
}
elseif(status[arg2].equals("马上回来"))
{
setNotiType(R.drawable.min,"马上回来");
}
else
{
setNotiType(R.drawable.offine,"脱机");
}
}
@Override
publicvoid onNothingSelected(AdapterView<?> arg0)
{
}
});
}
/* 发出Notification的method */
privatevoid setNotiType(int iconId, String text)
{
/* 建立新的Intent,作为点选Notification留言条时,
* 会执行的Activity */
Intent notifyIntent=new Intent(this,EX05_08_1.class);
notifyIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
/* 建立PendingIntent作为设定递延执行的Activity */
PendingIntent appIntent=PendingIntent.getActivity(EX05_08.this,0,
notifyIntent,0);
/* 建立Notication,并设定相关参数 */
Notification myNoti=new Notification();
/* 设定statusbar显示的icon */
myNoti.icon=iconId;
/* 设定statusbar显示的文字讯息 */
myNoti.tickerText=text;
/* 设定notification发生时同时发出预设声音 */
myNoti.defaults=Notification.DEFAULT_SOUND;
/* 设定Notification留言条的参数 */
myNoti.setLatestEventInfo(EX05_08.this,"MSN登入状态",text,appIntent);
/* 送出Notification */
myNotiManager.notify(0,myNoti);
}
例子:
/* 以getSystemService取得WIFI_SERVICE */
mWiFiManager01 = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
/* 判断执行程序后的WiFi状态是否启动或启动中 */
if(mWiFiManager01.isWifiEnabled())
{
/* 判断WiFi状态是否已启动 */
if(mWiFiManager01.getWifiState()==WifiManager.WIFI_STATE_ENABLED)
{
/* 若WiFi已启动,将核取项打勾 */
mCheckBox01.setChecked(true);
/* 更改核取项文字为关闭WiFi*/
mCheckBox01.setText(R.string.str_uncheck);
}
else
{
/* 若WiFi未启动,将核取项勾选取消 */
mCheckBox01.setChecked(false);
/* 变更核取项文字为启动WiFi*/
mCheckBox01.setText(R.string.str_checked);
}
}
/* 调用拨号的画面 */
Intent myIntentDial = new Intent("android.intent.action.CALL_BUTTON");
权限
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
例子:
// 定义一个List,该List对象为一级条目提供数据
List<Map<String, String>> groups = newArrayList<Map<String, String>>();
Map<String, String> group1 = new HashMap<String, String>();
group1.put("group", "group1");
Map<String, String> group2 = new HashMap<String, String>();
group2.put("group", "group2");
groups.add(group1);
groups.add(group2);
// 定义一个List为一级条目中第一条一级条目里面的内容
List<Map<String, String>> child1s = newArrayList<Map<String, String>>();
Map<String, String> child1 = new HashMap<String, String>();
child1.put("child", "child1");
Map<String, String> child2 = new HashMap<String, String>();
child2.put("child", "child1");
child1s.add(child1);
child1s.add(child2);
// 定义一个List为一级条目中第一条一级条目里面的内容
List<Map<String, String>> child2s = newArrayList<Map<String, String>>();
Map<String, String> child2Data = new HashMap<String,String>();
child2Data.put("child", "child2");
child2s.add(child2Data);
// 最终将两个二级条目的数据放在一个list中
List<List<Map<String, String>>> childs = newArrayList<List<Map<String, String>>>();
childs.add(child1s);
childs.add(child2s);
/*
* 分析以下参数的含义
* 1.context
* 2.一级条目的数据
* 3.用来设置一级条目样式的布局文件
* 4.指定一级条目数据的keygroup1.put("group", "group1");
* 5.指定一级条目数据显示控件的ID
* 6.指定二级条目的数据
* 7.用来设置二级条目样式的布局文件
* 8.指定一级条目数据的key
* 9.指定二级条目数据显示控件的ID
*/
SimpleExpandableListAdapter sela = new SimpleExpandableListAdapter(
this, groups, R.layout.group, new String[] { "group" },
newint[] { R.id.groupTo }, childs, R.layout.child,
new String[] { "child" }, newint[] { R.id.childTo });
setListAdapter(sela);
//设置ImageButton的背景图片,方法原型为setImageDrawable(Drawable draw)
//getResources():返回当前应用程序包下的所有资源
((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.pinkrose));
setTitle(" "+keyCode); //将当前按键的keyCode显示到标题栏中,方便测试观察
解释JSON,需要加入json.lib包
private String jsonData="[{\"name\":\"jack\",\"age\":\"20\"},{\"name\":\"rose\",\"age\":\"60\"}]";
JsonUtils ju=new JsonUtils();
ju.parseJson(jsonData);
publicvoid parseJson(String jsonData) throws Exception
{
//如果需要解析Json数据,首先要生成一个JsonReader对象
JsonReader jr=new JsonReader(newStringReader(jsonData));
jr.beginArray();
while(jr.hasNext())
{
jr.beginObject();
while(jr.hasNext())
{
StringtagName=jr.nextName();
if(tagName.equals("name"))
{
System.out.println("name---->"+jr.nextString());
}
elseif(tagName.equals("age"))
{
System.out.println("age---->"+jr.nextInt());
}
}
jr.endObject();
}
jr.endArray();
}
liearLayout = (LinearLayout) this.findViewById(R.id.layout);
//获取main.xml中id为layout的liearLayout对象
TextView txtFont = new TextView(this);//声明一个TextView对象
ViewGroup.LayoutParamslayoutParams = new ViewGroup.LayoutParams(//声明ViewGroup.LayoutParams对象
ViewGroup.LayoutParams.FILL_PARENT,
//设置布局参数对象的宽度
ViewGroup.LayoutParams.WRAP_CONTENT);
//设置布局参数对象的高度
txtFont.setLayoutParams(layoutParams);
//将txtFont以layoutParams对象指定宽度和高度布局
txtFont.setText("通过代码实现布局示例1");
//设置txtFont上面显示的文字
txtFont.setTextColor(Color.BLACK);
//设置字体颜色为黑色
liearLayout.addView(txtFont);
//将txtFont添加到liearLayout布局上
liearLayoutMain = (LinearLayout) this.findViewById(R.id.layout); // 获取main.xml中id为layout的liearLayout对象
TextView bookName = new TextView(this);// 声明一个TextView对象
ViewGroup.LayoutParams bookNameParams = newViewGroup.LayoutParams(// 声明ViewGroup.LayoutParams对象
ViewGroup.LayoutParams.FILL_PARENT, // 设置布局参数对象的宽度
ViewGroup.LayoutParams.WRAP_CONTENT); // 设置布局参数对象的高
bookName.setLayoutParams(bookNameParams);// 设置bookName的布局方式
bookName.setText("桂林上水甲天下"); // 设置bookName上面显示的文字
bookName.setTextColor(Color.BLACK);// 设置bookName的文字颜色
bookName.setGravity(Gravity.CENTER);// 设置bookName文字居中显示
TextPaint bttp = bookName.getPaint();// 获取TextPaint对象
bttp.setFakeBoldText(true);// 设置bookName加粗显示
TextView bookDesc = new TextView(this);// 声明一个TextView对象
LinearLayout.LayoutParams bookDescParams = newLinearLayout.LayoutParams(// 声明ViewGroup.LayoutParams对象
ViewGroup.LayoutParams.WRAP_CONTENT, // 设置布局参数对象的宽度
ViewGroup.LayoutParams.WRAP_CONTENT); // 设置布局参数对象的高度
bookDesc.setLayoutParams(bookDescParams);// 设置bookDesc的布局方式
bookDesc.setText(R.string.desc); // 设置txtFont上面显示的文字
bookDesc.setTextColor(Color.BLACK);
ImageView bookPic = new ImageView(this);// 声明一个ImageView对象
LinearLayout.LayoutParams bookPicParams = newLinearLayout.LayoutParams(
251, 183);
bookPicParams.setMargins(25, 0, 0, 5);// 设置边距,方法原型void setMargins (int
// left, int top, int right, int
// bottom)
bookPic.setLayoutParams(bookPicParams);
bookPic.setBackgroundResource(R.drawable.guilin);// 设置ImageView的背景图
liearLayoutMain.addView(bookName); // 将bookName添加到liearLayoutMain布局上
liearLayoutMain.addView(bookPic);// 将bookPic添加到liearLayoutMain布局上
liearLayoutMain.addView(bookDesc);// 将bookDesc添加到liearLayoutMain布局上
QQ登陆页面:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="@drawable/loginbackground">
<!-- 登录上半部分界面布局-->
<LinearLayout android:orientation="vertical"
android:layout_width="300px" android:layout_height="200px"
android:background="@drawable/loginbg" android:layout_marginTop="51px"
android:layout_marginLeft="10px" android:layout_marginRight="10px">
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginLeft="10px" android:layout_marginRight="10px"
android:layout_marginTop="10px">
<!-- QQ头像图片 -->
<!--ImageView:图片组件,用来显示图片的。该组件的详细属性使用会在第4章中详细讲解 -->
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/qqpic" />
<!-- 账号密码文本框-->
<TableLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- 第一行 -->
<TableRow>
<!--
EditText:文本框组件,android:singleLine="true":表示该文本框为单行
该组件的详细属性使用会在第4章中详细讲解
-->
<EditText android:hint="账号" android:layout_width="210px"
android:layout_height="wrap_content" android:singleLine="true" />
</TableRow>
<!-- 第二行 -->
<TableRow>
<!--android:password="true":表示该文本框是用来输入密码的,输入的字符会以某种回显字符方式显示 -->
<EditText android:hint="密码" android:layout_width="210px"
android:layout_height="wrap_content" android:singleLine="true"
android:password="true" />
</TableRow>
</TableLayout>
</LinearLayout>
<!-- 记住密码和自动登录复选框的TableLayout布局 -->
<TableLayout android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="10px">
<!-- 第一行 -->
<TableRow>
<!--
CheckBox:复选框组件,android:checked="true":默认选中,该组件的详细属性使用会在第4章中详细讲解
-->
<CheckBox android:checked="true"android:text="记住密码"
android:textColor="#FF000000" />
<CheckBox android:checked="true"android:layout_marginLeft="68px"
android:textColor="#FF000000" android:text="自动登录" />
</TableRow>
</TableLayout>
<!-- 登录按钮 -->
<!-- ImageButton:图片按钮,该按钮上面可以显示图片,该组件的详细属性使用会在第4章中详细讲解 -->
<ImageButton android:layout_width="164px"
android:layout_height="35px" android:layout_gravity="center"
android:background="@drawable/loginbutt" />
</LinearLayout>
<!-- 界面底部的四个复选框的TableLayout布局-->
<TableLayout android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="10px"
android:layout_marginTop="40px">
<TableRow>
<CheckBox android:text="隐身登录" android:textColor="#FF000000"/>
<CheckBox android:layout_marginLeft="68px"
android:textColor="#FF000000" android:text="开启振动" />
</TableRow>
<TableRow>
<CheckBox android:text="接收群消息" android:textColor="#FF000000"/>
<CheckBox android:layout_marginLeft="68px"
android:textColor="#FF000000" android:text="静音登录" />
</TableRow>
</TableLayout>
</LinearLayout>
例子:
publicclass MyAccelerometer_Activity extends Activity
{
SensorManager mySensorManager;//SensorManager对象引用
//加速度传感器
Sensor myAccelerometer;
TextView tvX; //TextView对象引用
TextView tvY; //TextView对象引用
TextView tvZ; //TextView对象引用
TextView info;
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvX = (TextView)findViewById(R.id.tvX); //用于显示x轴方向加速度
tvY = (TextView)findViewById(R.id.tvY); //用于显示y轴方向加速度
tvZ = (TextView)findViewById(R.id.tvZ); //用于显示z轴方向加速度
info= (TextView)findViewById(R.id.info);//用于显示手机中加速度传感器的相关信息
mySensorManager =(SensorManager)getSystemService(SENSOR_SERVICE);//获得SensorManager对象
myAccelerometer=mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
String str="\n名字: "+myAccelerometer.getName()+"\n电池 :"+myAccelerometer.getPower()+
"\n类型 :"+myAccelerometer.getType()+"\nVendor:"+myAccelerometer.getVendor()+
"\n版本: "+myAccelerometer.getVersion()+"\n幅度: "+myAccelerometer.getMaximumRange();
info.setText(str);//将信息字符串赋予名为info的TextView
}
@Override
protectedvoid onResume() //重写onResume方法
{
super.onResume();
mySensorManager.registerListener(mySensorListener, myAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protectedvoid onPause()//重写onPause方法
{
super.onPause();
mySensorManager.unregisterListener(mySensorListener);//取消注册监听器
}
private SensorEventListener mySensorListener = newSensorEventListener()
{//开发实现了SensorEventListener接口的传感器监听器
@Override
publicvoid onAccuracyChanged(Sensor sensor, int accuracy)
{
}
@Override
publicvoid onSensorChanged(SensorEvent event)
{
float []values=event.values;//获取三个轴方向感上的加速度值
tvX.setText("x轴方向上的加速度为:"+values[0]);
tvY.setText("y轴方向上的加速度为:"+values[1]);
tvZ.setText("z轴方向上的加速度为:"+values[2]);
}
};
例子:
publicclass MyGyroscope_Activity extends Activity {
SensorManager mySensorManager;//SensorManager对象引用
Sensor myGyroscope; //陀螺仪传感器
TextView tvX; //TextView对象引用
TextView tvY; //TextView对象引用
TextView tvZ; //TextView对象引用
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvX = (TextView)findViewById(R.id.tvX); //用于显示x轴方向加速度
tvY = (TextView)findViewById(R.id.tvY); //用于显示y轴方向加速度
tvZ = (TextView)findViewById(R.id.tvZ); //用于显示z轴方向加速度
mySensorManager =(SensorManager)getSystemService(SENSOR_SERVICE);//获得SensorManager对象
myGyroscope=mySensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
}
@Override
protectedvoid onResume() //重写onResume方法
{
super.onResume();
mySensorManager.registerListener(mySensorListener, myGyroscope, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protectedvoid onPause()//重写onPause方法
{
super.onPause();
mySensorManager.unregisterListener(mySensorListener);//取消注册监听器
}
private SensorEventListener mySensorListener = newSensorEventListener()
{//开发实现了SensorEventListener接口的传感器监听器
@Override
publicvoid onAccuracyChanged(Sensor sensor, int accuracy)
{
}
@Override
publicvoid onSensorChanged(SensorEvent event)
{
float []values=event.values;//获取三个轴方向感上的加速度值
System.out.println(values.length);
tvX.setText("沿x轴旋转的角速度为:"+values[0]);
tvY.setText("沿y轴旋转的角速度为:"+values[1]);
tvZ.setText("沿z轴旋转的角速度为:"+values[2]);
}
};
例子:
publicclass MyLightSensor_Activity extends Activity
{
//SensorManager对象引用
SensorManager mySensorManager;
//光照传感器
Sensor myLightSensor;
TextView tvX; //TextView对象引用
TextView info;
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvX = (TextView)findViewById(R.id.tvX);
info= (TextView)findViewById(R.id.info);
//获得SensorManager对象
mySensorManager =(SensorManager)getSystemService(SENSOR_SERVICE);
myLightSensor=mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
String str="\n名字: "+myLightSensor.getName()+"\n电池 :"+myLightSensor.getPower()+
"\n类型 :"+myLightSensor.getType()+"\nVendor:"+myLightSensor.getVendor()+
"\n版本: "+myLightSensor.getVersion()+"\n幅度: "+myLightSensor.getMaximumRange();
info.setText(str);//将信息字符串赋予名为info的TextView
}
@Override
protectedvoid onResume() //重写onResume方法
{
mySensorManager.registerListener(mySensorListener, myLightSensor,SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
@Override
protectedvoid onPause()
{ //重写onPause方法
mySensorManager.unregisterListener(mySensorListener); //取消注册监听器
super.onPause();
}
//开发实现了SensorEventListener接口的传感器监听器
private SensorEventListener mySensorListener = newSensorEventListener()
{
@Override
publicvoid onAccuracyChanged(Sensor sensor, int accuracy)
{
}
@Override
publicvoid onSensorChanged(SensorEvent event)
{
float []values=event.values;
tvX.setText("光强为:"+values[0]);
}
};
}
例子:
publicclass MyMagneticFieldSensor_Activity extends Activity
{
//SensorManager对象引用
SensorManager mySensorManager;
//温度传感器
Sensor myMagnetic_field_Sensor;
TextView tvX,tvY,tvZ,info; //TextView对象引用
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvX = (TextView)findViewById(R.id.tvX);
tvY = (TextView)findViewById(R.id.tvY);
tvZ = (TextView)findViewById(R.id.tvZ);
info=(TextView)findViewById(R.id.info);
//获得SensorManager对象
mySensorManager =(SensorManager)getSystemService(SENSOR_SERVICE);
myMagnetic_field_Sensor=mySensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
String str="\n名字: "+myMagnetic_field_Sensor.getName()+"\n电池 :"+myMagnetic_field_Sensor.getPower()+
"\n类型 :"+myMagnetic_field_Sensor.getType()+"\nVendor:"+myMagnetic_field_Sensor.getVendor()+
"\n版本: "+myMagnetic_field_Sensor.getVersion()+"\n幅度: "+myMagnetic_field_Sensor.getMaximumRange();
info.setText(str);//将信息字符串赋予名为info的TextView
}
@Override
protectedvoid onResume()//重写onResume方法
{
mySensorManager.registerListener(mySensorListener, myMagnetic_field_Sensor, SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
@Override
protectedvoid onPause()
{ //重写onPause方法
mySensorManager.unregisterListener(mySensorListener); //取消注册监听器
super.onPause();
}
//开发实现了SensorEventListener接口的传感器监听器
private SensorEventListener mySensorListener = newSensorEventListener()
{
@Override
publicvoid onAccuracyChanged(Sensor sensor, int accuracy)
{
}
@Override
publicvoid onSensorChanged(SensorEvent event)
{
float []values=event.values;
System.out.println(values.length+"=======");
tvX.setText("X轴方向磁场为:"+values[0]);
tvY.setText("Y轴方向磁场为:"+values[1]);
tvZ.setText("Z轴方向磁场为:"+values[2]);
}
};
}
例子:
publicclass MyOrientation_Activity extends Activity {
SensorManager mySensorManager;//SensorManager对象引用
Sensor myOrientation_Sensor;//方向传感器
TextView tvX,tvY,tvZ,info; //TextView对象引用
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvX = (TextView)findViewById(R.id.tvX);
tvY = (TextView)findViewById(R.id.tvY);
tvZ = (TextView)findViewById(R.id.tvZ);
info=(TextView)findViewById(R.id.info);
//获得SensorManager对象
mySensorManager =(SensorManager)getSystemService(SENSOR_SERVICE);
myOrientation_Sensor=mySensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
String str="\n名字: "+myOrientation_Sensor.getName()+"\n电池 :"+myOrientation_Sensor.getPower()+
"\n类型 :"+myOrientation_Sensor.getType()+"\nVendor:"+myOrientation_Sensor.getVendor()+
"\n版本: "+myOrientation_Sensor.getVersion()+"\n幅度: "+myOrientation_Sensor.getMaximumRange();
info.setText(str);//将信息字符串赋予名为info的TextView
}
@Override
protectedvoid onResume()//重写onResume方法
{
mySensorManager.registerListener(mySensorListener,
myOrientation_Sensor, SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
@Override
protectedvoid onPause() //重写onPause方法
{
mySensorManager.unregisterListener(mySensorListener); //取消注册监听器
super.onPause();
}
//开发实现了SensorEventListener接口的传感器监听器
private SensorEventListener mySensorListener = newSensorEventListener()
{
@Override
publicvoid onAccuracyChanged(Sensor sensor, int accuracy)
{
}
@Override
publicvoid onSensorChanged(SensorEvent event)
{
float []values=event.values;
System.out.println(values.length+"=======");
tvX.setText("手机沿Yaw轴转过的角度为:"+values[0]);
tvY.setText("手机沿Pitch轴转过的角度为:"+values[1]);
tvZ.setText("手机沿Roll轴转过的角度为:"+values[2]);
}
};
}
例子:
publicclass MyProximity_Activity extends Activity {
SensorManager mySensorManager;//SensorManager对象引用
Sensor myProximity_Sensor;//距离传感器
TextView tvX,info; //TextView对象引用
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvX = (TextView)findViewById(R.id.tvX);
info=(TextView)findViewById(R.id.info);
//获得SensorManager对象
mySensorManager =(SensorManager)getSystemService(SENSOR_SERVICE);
myProximity_Sensor=mySensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
String str="\n名字: "+myProximity_Sensor.getName()+"\n电池 :"+myProximity_Sensor.getPower()+
"\n类型 :"+myProximity_Sensor.getType()+"\nVendor:"+myProximity_Sensor.getVendor()+
"\n版本: "+myProximity_Sensor.getVersion()+"\n幅度: "+myProximity_Sensor.getMaximumRange();
info.setText(str);//将信息字符串赋予名为info的TextView
}
@Override
protectedvoid onResume()//重写onResume方法
{
mySensorManager.registerListener(mySensorListener,
myProximity_Sensor, SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
@Override
protectedvoid onPause() //重写onPause方法
{
mySensorManager.unregisterListener(mySensorListener); //取消注册监听器
super.onPause();
}
//开发实现了SensorEventListener接口的传感器监听器
private SensorEventListener mySensorListener = newSensorEventListener()
{
@Override
publicvoid onAccuracyChanged(Sensor sensor, int accuracy)
{
}
@Override
publicvoid onSensorChanged(SensorEvent event)
{
float []values=event.values;
tvX.setText("手机距离物体的距离为:"+values[0]);
}
};
}
例子:
publicclass MyTemperatureSensor_Activity extends Activity
{
//SensorManager对象引用
SensorManagermySensorManager;
//温度传感器
Sensor myTemperatureSensor;
TextView tvX,info; //TextView对象引用
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvX = (TextView)findViewById(R.id.tvX);
info=(TextView)findViewById(R.id.info);
//获得SensorManager对象
mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
myTemperatureSensor=mySensorManager.getDefaultSensor(Sensor.TYPE_TEMPERATURE);
String str="\n名字: "+myTemperatureSensor.getName()+"\n电池 :"+myTemperatureSensor.getPower()+
"\n类型 :"+myTemperatureSensor.getType()+"\nVendor:"+myTemperatureSensor.getVendor()+
"\n版本: "+myTemperatureSensor.getVersion()+"\n幅度: "+myTemperatureSensor.getMaximumRange();
info.setText(str);//将信息字符串赋予名为info的TextView
}
@Override
protectedvoid onResume()//重写onResume方法
{
mySensorManager.registerListener(mySensorListener, myTemperatureSensor, SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
@Override
protectedvoid onPause()
{ //重写onPause方法
mySensorManager.unregisterListener(mySensorListener); //取消注册监听器
super.onPause();
}
//开发实现了SensorEventListener接口的传感器监听器
private SensorEventListener mySensorListener = newSensorEventListener()
{
@Override
publicvoid onAccuracyChanged(Sensor sensor, int accuracy)
{
}
@Override
publicvoid onSensorChanged(SensorEvent event)
{
float []values=event.values;
tvX.setText("温度为:"+values[0]);
}
};
}
例子:
publicclass OptionsMenuExample extends Activity {
/** Called when the activity is firstcreated. */
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//加载资源文件
}
//点击Menu时,系统会调用该方法,初始化选项菜单(OptionsMenu)
//并传入一个menu对象供你使用
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
//add()方法是添加一个新的菜单项到menu中,四个参数含义为
//第一个参数:组标识,如果不分组的话值为Menu.NONE
//第二个参数:菜单项id,是菜单项的唯一标识,可以通过它判断操作了哪个菜单项
//第三个参数:菜单项摆放的顺序
//第四个参数:菜单项上显示的文字
MenuItem homeMenuItem = menu.add(Menu.NONE, 0, 0, "主页");//添加菜单项
homeMenuItem.setIcon(R.drawable.home);//为菜单项设置图标
MenuItem printMenuItem = menu.add(Menu.NONE, 1, 1, "打印");
printMenuItem.setIcon(R.drawable.print);
MenuItem saveMenuItem = menu.add(Menu.NONE, 2, 2, "保存");
saveMenuItem.setIcon(R.drawable.save);
MenuItem searchMenuItem = menu.add(Menu.NONE, 3, 3, "搜索");
searchMenuItem.setIcon(R.drawable.search);
MenuItem delMenuItem = menu.add(Menu.NONE, 4, 4, "删除");
delMenuItem.setIcon(R.drawable.del);
MenuItem settingMenuItem = menu.add(Menu.NONE, 5, 5, "设置");
settingMenuItem.setIcon(R.drawable.setting);
MenuItem aboutMenuItem = menu.add(Menu.NONE, 6, 6, "关于");
aboutMenuItem.setIcon(R.drawable.about);
returnsuper.onCreateOptionsMenu(menu);
}
// 菜单项被选择触发该方法
@Override
publicboolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {//获取菜单项的id
case 0:
//item.getTitle():获取菜单项上显示的文字
Toast.makeText(this, "点击了’"+item.getTitle()+"‘菜单", Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(this, "点击了‘"+item.getTitle()+"’菜单", Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(this, "点击了‘"+item.getTitle()+"’菜单", Toast.LENGTH_LONG).show();
break;
case 3:
Toast.makeText(this, "点击了‘"+item.getTitle()+"’菜单", Toast.LENGTH_LONG).show();
break;
case 4:
Toast.makeText(this, "点击了‘"+item.getTitle()+"’菜单", Toast.LENGTH_LONG).show();
break;
case 5:
Toast.makeText(this, "点击了‘"+item.getTitle()+"’菜单", Toast.LENGTH_LONG).show();
break;
case 6:
Toast.makeText(this, "点击了‘"+item.getTitle()+"’菜单", Toast.LENGTH_LONG).show();
break;
}
returntrue;
}
//选项菜单(OptionsMenu)被关闭时触发该方法,三种情况下选项菜单(OptionsMenu)会被关闭
//1.back按钮被点击,2.menu按钮被再次按下,3.选择了某一个菜单项
@Override
publicvoid onOptionsMenuClosed(Menu menu) {
Toast.makeText(this, "选项菜单(OptionsMenu)被关闭了", Toast.LENGTH_LONG).show();
}
//选项菜单(OptionsMenu)显示之前调用该方法
//返回值:false:此方法就把用户点击menu的动作给屏蔽了,onCreateOptionsMenu方法将不会被调用
@Override
publicboolean onPrepareOptionsMenu(Menu menu) {
Toast.makeText(this,
"选项菜单(OptionsMenu)显示之前onPrepareOptionsMenu方法会被调用",
Toast.LENGTH_LONG).show();
returntrue;
}
}
String mobile =mobileText.getText().toString();//得到了用户输入的手机号
Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:"+ mobile));
startActivity(intent);
例子:
// 将数据保存到SharePreperence里
// 第一个参数为文件名,会自动帮你创建不用指定文件名后缀,会自动添加上.xml
// 第二个参数为访问的模式,Context.MODE_PRIVATE表示只可以本程序访问
//参数为:Context.MODE_WORLD_READABLE表示外部程序可以访问
SharedPreferences sp = getSharedPreferences("itcast",
Context.MODE_WORLD_READABLE);
@Override
publicvoid onClick(View v) {
// 判读点击的是哪一个按钮
switch (v.getId()) {
// 如果是保存按钮
case R.id.save:
String name = ming.getText().toString();
String a = age.getText().toString();
// 要保存数据要先获取编辑器对象
Editor e = sp.edit();
// 下面两个是放在内存中的
e.putString("name", name);
e.putString("age", a);
// 如果不真执行commit()方法,那么上面的就是保存在内存中,没有保存在文件中
e.commit();
// 显示提示框
Toast.makeText(MainActivity.this, R.string.success, 1).show();
break;
//如果是恢复按钮
case R.id.huifu:
//将值设置进文本中,在sharePreference里面拿出值来
ming.setText(sp.getString("name", ""));
age.setText(sp.getString("age", ""));
break;
}
}
<!--
android:numStars="5"表示显示多少个星星
android:stepSize="1.0"表示一次亮0.5颗星,因为上面设置了5个星
-->
<RatingBar android:id="@+id/rating" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:numStars="5"
android:stepSize="0.5" />
// 获取string.xml文件的文本
final CharSequence title = getString(R.string.title);
final CharSequence content = getString(R.string.content);
final CharSequence title = getString(R.string.title);
final CharSequence content = getString(R.string.content);
// 顯示Progress對話框
pd = ProgressDialog.show(Activity01.this, title, content);
// 啟動線程
new Thread() {
publicvoid run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally
{
//卸载所创建的Dialoy对象
pd.dismiss();
}
}
}.start();
// 设置进度条的最大值
seek.setMax(100);
// 进度条发生变化
seek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
// 当用户结束滑动滑块时
@Override
publicvoid onStopTrackingTouch(SeekBar seekBar) {
System.out.println("stop-->" + seekBar.getProgress());
}
// 当用户开始滑动滑块时
@Override
publicvoid onStartTrackingTouch(SeekBar seekBar) {
System.out.println("start-->" + seekBar.getProgress());
}
// 当进度条发生变化时
@Override
publicvoid onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
System.out.println(progress);
}
});
// 短信管理器
SmsManager smsManager =SmsManager.getDefault();
// 把短信内容拆分,因为短信太大要进行两条短信发送,要用本身提供的方法
ArrayList<String> arrList= smsManager.divideMessage(con);
for (String text : arrList) {
// hao为发送到的地址,text为短信内容,
smsManager.sendTextMessage(hao,null, text, null, null);
}
// 短信发送成功,提示信息
/*
* 第一个参数表示上下文,应用所运行到的信息,相当于applicaiton第二个参数表示提示的信息第三个参数表示显示的时间
*/
Toast.makeText(MainActivity.this, R.string.successful,2).show();
// 构建一个Default的SmsManager对象
SmsManager smsManager =SmsManager.getDefault();
// 构建PendingIntent对象,并使用getBroadcast()广播
PendingIntent pendingIntent =PendingIntent.getBroadcast(
SendActivity.this, 0, new Intent(), 0);
smsManager.sendTextMessage(strAddressee,null, strMessage,
pendingIntent, null);// 发送短信消息
Toast.makeText(SendActivity.this, "短信发送成功", 1000).show();//信息提示方法
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
蓝牙
// 得到一个本地蓝牙适配器, getDefaultAdapter()函数用于获取本地蓝牙适配器
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {// 如果适配器为null,则不支持蓝牙
Toast.makeText(this, "该设备不支持蓝牙", Toast.LENGTH_LONG).show();
finish();// 关闭程序
return;
}
if (bluetoothAdapter.isEnabled()) {// 判断蓝牙是否开启
statusText.setText("蓝牙状态:开启");// 设置蓝牙状态提示
} else {
statusText.setText("蓝牙状态:关闭");// 设置蓝牙状态提示
}
/**
* 打开蓝牙方法
*/
publicvoid openBluetooth() {
if (!bluetoothAdapter.isEnabled()) {// 判断蓝牙是否打开
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);// 打开蓝牙
startActivity(enableIntent);
// 提示蓝牙正在开启中
Toast.makeText(this, "蓝牙开启中......", Toast.LENGTH_SHORT).show();
} else {
// 提示蓝牙已经开启
Toast.makeText(this, "蓝牙已经开启", Toast.LENGTH_SHORT).show();
}
}
/**
* 关闭蓝牙方法
*/
publicvoid closeBluetooth() {
if (bluetoothAdapter.isEnabled()) {// 判断蓝牙是否打开
bluetoothAdapter.disable();// 关闭蓝牙
// 提示蓝牙已经关闭
Toast.makeText(this, "蓝牙已经关闭", Toast.LENGTH_SHORT).show();
} else {
// 提示蓝牙是关闭的
Toast.makeText(this, "蓝牙是关闭的", Toast.LENGTH_SHORT).show();
}
}
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH" />
SharedPreferences例子
private String info = "user_info";// 共享文件名
/**
* 把user(用户名),password(密码)保存到文件
*/
publicvoid saveData() {
SharedPreferences sPreferences = getSharedPreferences(info, 0);//获取SharedPreferences
Editor editor =sPreferences.edit();//打开SharedPreferences的编辑状态
editor.putString("User", user);//存储用户名
editor.putString("Password", password);//存储密码
editor.commit();//保存数据
//提示用户登录成功,并获取先保存的文件中
new AlertDialog.Builder(SharedData.this).setTitle("登录信息").setMessage(
"用户 " + sPreferences.getString("User", "") + " 登录成功")
.setPositiveButton("确定", new OnClickListener() {
@Override
publicvoid onClick(DialogInterface arg0, int arg1) {
}
}).show();
}
/**
* 获取文件中的数据,如果文件中存在相应的数据,把该数据赋值到相应的EditText组件对象
*/
publicvoid getData() {
SharedPreferences sPreferences = getSharedPreferences(info, 0);//获取SharedPreferences
user = sPreferences.getString("User", "");//获取info文件中User对应的数据
password = sPreferences.getString("Password", "");//获取info文件中Password对应的数据
userText.setText(user);//把user赋值给用户EditText组件对象
passwordText.setText(password);//把password赋值给密码EditText组件对象
}
例子:
/**
* 这是TCP通信协议的服务器端
*/
@Override
publicvoid run() {
// 声明一个ServerScoket对象
ServerSocket ss = null;
try {
// 创建一个ServerSocket对象,并让这个Scoekt在4567端口监听s
ss = new ServerSocket(4567);
// 调用ServerSocket的accept()方法,接受客户端发送的请求
// 当客户端没有发送请求,accept处于阻塞的一种状态,不再往下运行
Socket s = ss.accept();
// 从Socket当中得到IntputStream(),读取客户端传过来的数据
InputStream is = s.getInputStream();
byte[] buff = newbyte[1024 * 4];
int temp = 0;
// 从InputStream中读取客户端所发送的数据
while ((temp = is.read(buff)) != -1) {
System.out.println(new String(buff, 0, temp));
}
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
/**
* 这是UDP通信协议的服务器端
*/
@Override
publicvoid run() {
try {
//创建一个DatagramSocket对象,监听4567端口
DatagramSocket ds=new DatagramSocket(4567);
byte data[]=newbyte[1024];
//使用UDP所发送的数据包,创建一个空的DatagramPacket用于接收客户端的内容
DatagramPacketdp=new DatagramPacket(data, data.length);
//使用receive方法接收客户端所发送过来的数据,同样是一个阻塞的方法
ds.receive(dp);
System.out.println(dp.getLength());
//这样可以获取包的数据
String result=new String(dp.getData());
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
例子:
// 第二步:为下拉列表项定义适配器
// createFromResource(Context context, int textArrayResId, int
// textViewResId) 参数的含义为
// 1.context:应用上下文
// 2.textArrayResId:适配器的数据源,这里的R.array.colors是在res/values/arrays.xml中定义的数组
// 3.Spinner上显示数据的视图。这里用Android自带的简单的下拉菜单方式
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.colors, android.R.layout.simple_spinner_item);
// 第三步:设置当Spinner按下时在下拉列表里显示数据视图。
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// 第四步:为Spinner添加适配器
mySpinner.setAdapter(adapter);
// 第五步:为Spinner添加事件监听,setOnItemSelectedListener该事件在菜单被选中时触发
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
/*
* 功能:Spinner的项被选择时触发该方法 parent 当前被选择的对象所在的 AdapterView view
* 在AdapterView中被点击的View position 当前点击项在View的位置,从0开始,0是第一项 id
* 被选择项的id
*/
@Override
publicvoid onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generatedmethod stub
// 将当前点击项的坐标和id显示出来
//getSelectedItem():获取选中项的值
Toast.makeText(
SpinnerExample.this,
"position:" + position + " id:" + id + "value:"
+ mySpinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
@Override
publicvoid onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generatedmethod stub
Toast.makeText(SpinnerExample.this, "unselected",
Toast.LENGTH_SHORT).show();
}
});
例子:
allCitys = new ArrayList<String>();// 创建城市ArrayList,并添加三个元素
allCitys.add("北京");
allCitys.add("上海");
allCitys.add("深圳");
mySpinner = (Spinner) this.findViewById(R.id.mySpinner);// 从XML布局文件中获取Spinner对象
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, allCitys);
adapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);// 设置下拉菜单下拉项的布局
mySpinner.setAdapter(adapter);// 为Spinner添加适配器
// 添加按钮单击事件
addBut.setOnClickListener(new OnClickListener() {
@Override
publicvoid onClick(View v) {
// TODO Auto-generatedmethod stub
StringnewCity = newCityEdit.getText().toString();// 获取文本框中输入的城市
for (int i = 0; i < adapter.getCount(); i++) {
if (newCity.equals(adapter.getItem(i))) {// 判断当前选中的项和文本框中输入的是否相同
Toast.makeText(SpinnerExample2.this, "该项已存在",
Toast.LENGTH_SHORT).show();
return;
}
}
if (!newCity.trim().equals("")) {// 文本框的内容不为“”时
adapter.add(newCity);// 将文本框中输入的信息添加到adapter中
int position = adapter.getPosition(newCity);// 获取newCity在ArrayAdapter中的位置
mySpinner.setSelection(position);// 选中下拉菜单中下标为position的项
newCityEdit.setText("");// 清空文本框
}
}
});
// 删除按钮单击事件
removeBut.setOnClickListener(new OnClickListener() {
@Override
publicvoid onClick(View v) {
// TODO Auto-generatedmethod stub
if (mySpinner.getSelectedItem() != null) {
adapter.remove(mySpinner.getSelectedItem().toString());// 从adapter中删除当前选中的项目
newCityEdit.setText("");
if (adapter.getCount() == 0) {// 如果adapter中没有项目,提示用户
Toast.makeText(SpinnerExample2.this, "没有项目可以移除",
Toast.LENGTH_SHORT).show();
}
}
}
});
// 当选择mySpinner中项目时触发该事件
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
publicvoid onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generatedmethod stub
newCityEdit.setText(parent.getSelectedItem().toString());// 将当前选中的项目显示在newCityEdit上
}
@Override
publicvoid onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generatedmethod stub
}
});
}
例子:
//点击Menu时,系统会调用该方法,初始化选项菜单(OptionsMenu)
//并传入一个menu对象供你使用
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generatedmethod stub
SubMenu fileMenu = menu.addSubMenu(1,1,1,"File");//给menu添加子菜单
fileMenu.setHeaderIcon(R.drawable.file);//设置子菜单弹出框的标题图标
fileMenu.setHeaderTitle("File");//设置子菜单弹出框的标题文字
fileMenu.setIcon(R.drawable.file);//设置子菜单的图标
fileMenu.add(2,11,11,"New");//为子菜单添加二级菜单
fileMenu.add(2,12,12,"Save");//为子菜单添加二级菜单
fileMenu.add(2,13,13,"Close");//为子菜单添加二级菜单
SubMenu editMenu = menu.addSubMenu(1,2,2,"Edit");
editMenu.setHeaderIcon(R.drawable.edit);
editMenu.setHeaderTitle("Edit");
editMenu.setIcon(R.drawable.edit);
editMenu.add(2,21,21,"Redo");
editMenu.add(2,22,22,"UndoTyping");
returnsuper.onCreateOptionsMenu(menu);
}
// 菜单项被选择触发该方法
@Override
publicboolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generatedmethod stub
switch(item.getItemId()){
case 1:
Toast.makeText(this, "点击了’"+item.getTitle()+"‘菜单", Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(this, "点击了’"+item.getTitle()+"‘菜单", Toast.LENGTH_LONG).show();
break;
case 11:
Toast.makeText(this, "点击了File子菜单’"+item.getTitle()+"‘", Toast.LENGTH_LONG).show();
break;
case 12:
Toast.makeText(this, "点击了File子菜单’"+item.getTitle()+"‘", Toast.LENGTH_LONG).show();
break;
case 13:
Toast.makeText(this, "点击了File子菜单’"+item.getTitle()+"‘", Toast.LENGTH_LONG).show();
break;
case 21:
Toast.makeText(this, "点击了Edit子菜单’"+item.getTitle()+"‘", Toast.LENGTH_LONG).show();
break;
case 22:
Toast.makeText(this, "点击了Edit子菜单’"+item.getTitle()+"‘", Toast.LENGTH_LONG).show();
break;
}
returnsuper.onOptionsItemSelected(item);
}
例子:
Calendar myCalendar = Calendar.getInstance(Locale.CHINA); //初始化Calendar日历对象。
Date myDate=new Date();//获取当前日期Date对象
myCalendar.setTime(myDate);//为Calendar对象设置时间为当前日期
year=myCalendar.get(Calendar.YEAR); //获取Calendar对象中的年
month=myCalendar.get(Calendar.MONTH);//获取Calendar对象中的月,0表示1月,1表示2月....
day=myCalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天
hour=myCalendar.get(Calendar.HOUR_OF_DAY);//获取小时信息
minus=myCalendar.get(Calendar.MINUTE);//获取分钟信息
showTime.setText(year+"-"+(month+1)+"-"+day+" "+hour+":"+minus);//设置TextView组件上显示的日期信息
setTime.setOnClickListener(new OnClickListener(){//“设置日期”按钮的单击事件
@Override
publicvoid onClick(View v) {
// TODO Auto-generatedmethod stub
//创建TimePickerDialog对象
//构造函数原型:TimePickerDialog(Context context,TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, intminute, boolean is24HourView)
//参数含义依次为context:组件运行Activity,TimePickerDialog.OnTimeSetListener:选择时间事件
//hourOfDay:当前组件上显示小时,minute:当前组件上显示的分钟,is24HourView:是否是24小时方式显示,或者AM/PM方式显示
TimePickerDialog tpd=new TimePickerDialog(TimePickerDialogExample.this,newTimePickerDialog.OnTimeSetListener(){
@Override
publicvoid onTimeSet(TimePicker view, int hourOfDay,
int myminute) {
// TODO Auto-generatedmethod stub
showTime.setText(year+"-"+(month+1)+"-"+day+" "+hourOfDay+":"+myminute);
hour=hourOfDay;
minus=myminute;
}
},hour,minus,false);
tpd.show();
}
});
Toast例子:
toast = Toast.makeText(ToastExample.this, R.string.ToastText,
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout view =(LinearLayout) toast.getView();// getView():获取Toast的View对象
ImageView imgView = newImageView(ToastExample.this);// 创建ImageView对象
imgView.setImageResource(R.drawable.icon);// 设置imgView的背景图片
view.addView(imgView);// 将imgView添加到View上
toast.setView(view);// 将view显示在Toast上
toast.show();// 显示Toast
toast = new Toast(ToastExample.this);
LayoutInflater inflater = getLayoutInflater();// 获取LayoutInflater对象
// inflate():将Layout文件转换为View,这里是将definetoast.xml中的myToastLayout组件转化为View
View myToastLayout =inflater.inflate(R.layout.definetoast,
(ViewGroup) findViewById(R.id.myToastLayout));
// 设置提示信息出现的位置
toast.setGravity(Gravity.RIGHT | Gravity.BOTTOM, 40, 40);
toast.setDuration(Toast.LENGTH_LONG);// 设置如何显示提示信息
toast.setView(myToastLayout);// 将myToastLayout显示在Toast上
toast.show();// 显示Toast
Window window=this.getWindow();//获取当前Activity的Window
//隐藏窗体的状态栏
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //隐藏窗体上方的标题栏
setContentView(R.layout.main);
this.setTitle("progressing...."); //设置标题栏上的文字
Window window=this.getWindow(); //获取当前Activity的Window
this.requestWindowFeature(Window.FEATURE_PROGRESS); //标题栏显示滚动条
setContentView(R.layout.main);//设置当前窗体的布局管理文件
this.setProgressBarVisibility(true);//设置进度条可见
this.setProgress(1800);//设置第一进度条的长度
this.setSecondaryProgress(8000);//设置第二进度条的长度
MP3播放
/**
* MP3开始播放方法
*/
publicvoid start() {
try {
if (mediaPlayer != null) {// 判断MediaPlayer对象不为空
if (mediaPlayer.isPlaying()) {// 判断MediaPlayer对象正在播放中,并不执行以下程序
return;
}
}
stop();// 调用停止播放方法
mediaPlayer = MediaPlayer.create(this, R.raw.dudong);// 加载资源文件里的MP3文件
// 文件播放完毕监听事件
mediaPlayer
.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
@Override
publicvoid onCompletion(MediaPlayer arg0) {// 覆盖文件播出完毕事件
// 解除资源与MediaPlayer的赋值关系,让资源可以为其它程序利用
arg0.release();
startButton.setText("播放");
}
});
// 文件播放错误监听
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
publicboolean onError(MediaPlayer arg0, int arg1, int arg2) {
// 解除资源与MediaPlayer的赋值关系,让资源可以为其它程序利用
arg0.release();
returnfalse;
}
});
mediaPlayer.start();// 开始播放
startButton.setText("正在播放");
pauseButton.setText("暂停");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* MP3播放暂停方法
*/
publicvoid pause() {
try {
if (mediaPlayer != null) {// 判断MediaPlayer对象不为空
if (mediaPlayer.isPlaying()) {// 判断MediaPlayer对象正在播放中
mediaPlayer.pause();// 暂停播放
pauseButton.setText("取消暂停");
} else {
mediaPlayer.start();// 开始播放
pauseButton.setText("暂停");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* MP3停止播放方法
*/
publicvoid stop() {
try {
if (mediaPlayer != null) {// 判断MediaPlayer对象不为空
mediaPlayer.stop();// 停止播放
startButton.setText("播放");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Sdcard获取MP3播放:
/**
* MP3开始播放方法
*/
publicvoid start() {
try {
if (mediaPlayer != null) {// 判断MediaPlayer对象不为空
if (mediaPlayer.isPlaying()) {// 判断MediaPlayer对象正在播放中,并不执行以下程序
return;
}
}
if (isPause) {// 判断MediaPlayer对象是否暂停,如果暂停就不重新播放
return;
}
mediaPlayer = new MediaPlayer();
// 文件播放完毕监听事件
mediaPlayer
.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
@Override
publicvoid onCompletion(MediaPlayer arg0) {// 覆盖文件播出完毕事件
// 解除资源与MediaPlayer的赋值关系,让资源可以为其它程序利用
mediaPlayer.release();
startButton.setText("播放");
isPause = false;// 取消暂停状态
mediaPlayer=null;
}
});
// 文件播放错误监听
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
publicboolean onError(MediaPlayer arg0, int arg1, int arg2) {
// 解除资源与MediaPlayer的赋值关系,让资源可以为其它程序利用
mediaPlayer.release();
isPause = false;// 取消暂停状态
mediaPlayer=null;
returnfalse;
}
});
String sdCard = Environment.getExternalStorageDirectory().getPath();
mediaPlayer.setDataSource(sdCard + File.separator + "dudong.mp3");// 为MediaPlayer设置数据源
mediaPlayer.prepare();// 准备播放
mediaPlayer.start();// 开始播放
startButton.setText("正在播放");
pauseButton.setText("暂停");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* MP3播放暂停方法
*/
publicvoid pause() {
try {
if (mediaPlayer != null) {// 判断MediaPlayer对象不为空
if (mediaPlayer.isPlaying()) {// 判断MediaPlayer对象正在播放中
mediaPlayer.pause();// 暂停播放
pauseButton.setText("取消暂停");
isPause = true;// 暂停状态
} else {
mediaPlayer.start();// 开始播放
pauseButton.setText("暂停");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* MP3停止播放方法
*/
publicvoid stop() {
try {
if (mediaPlayer != null) {// 判断MediaPlayer对象不为空
mediaPlayer.stop();// 停止播放
startButton.setText("播放");
pauseButton.setText("暂停");
isPause = false;// 取消暂停状态
}
} catch (Exception e) {
e.printStackTrace();
}
}
网络MP3播放:
/**
* MP3开始播放方法
*/
publicvoid start() {
try {
if (mediaPlayer != null) {// 判断MediaPlayer对象不为空
if (mediaPlayer.isPlaying()) {// 判断MediaPlayer对象正在播放中,并不执行以下程序
return;
}
}
if (isPause) {// 判断MediaPlayer对象是否暂停,如果暂停就不重新播放
return;
}
mediaPlayer = new MediaPlayer();
// 文件播放完毕监听事件
mediaPlayer
.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
@Override
publicvoid onCompletion(MediaPlayer arg0) {// 覆盖文件播出完毕事件
// 解除资源与MediaPlayer的赋值关系,让资源可以为其它程序利用
mediaPlayer.release();
startButton.setText("播放");
isPause = false;// 取消暂停状态
mediaPlayer = null;
}
});
// 文件播放错误监听
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
publicboolean onError(MediaPlayer arg0, int arg1, int arg2) {
// 解除资源与MediaPlayer的赋值关系,让资源可以为其它程序利用
mediaPlayer.release();
isPause = false;// 取消暂停状态
mediaPlayer = null;
returnfalse;
}
});
//MP3网络资源路径
String path = "http://5.gaosu.com/download/ring/000/086/8e2c23ec414592efdfad5353c21ce888.mp3";
mediaPlayer.setDataSource(path);// 为MediaPlayer设置数据源
mediaPlayer.prepare();// 准备播放
mediaPlayer.start();// 开始播放
startButton.setText("正在播放");
pauseButton.setText("暂停");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* MP3播放暂停方法
*/
publicvoid pause() {
try {
if (mediaPlayer != null) {// 判断MediaPlayer对象不为空
if (mediaPlayer.isPlaying()) {// 判断MediaPlayer对象正在播放中
mediaPlayer.pause();// 暂停播放
pauseButton.setText("取消暂停");
isPause = true;// 暂停状态
} else {
mediaPlayer.start();// 开始播放
pauseButton.setText("暂停");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* MP3停止播放方法
*/
publicvoid stop() {
try {
if (mediaPlayer != null) {// 判断MediaPlayer对象不为空
mediaPlayer.stop();// 停止播放
startButton.setText("播放");
pauseButton.setText("暂停");
isPause = false;// 取消暂停状态
}
} catch (Exception e) {
e.printStackTrace();
}
}
例子:
privateintselectedItem = -1;
private String[] mString;
staticfinalprivateintMENU_LIST1 = Menu.FIRST;
staticfinalprivateintMENU_LIST2 = Menu.FIRST + 1;
private ArrayAdapter<String> mla;
@Override
protectedvoid onCreate(Bundle savedInstanceState)
{
// TODO Auto-generatedmethod stub
super.onCreate(savedInstanceState);
}
@Override
protectedvoid onListItemClick(ListView l, View v, int position, long id)
{
// TODO Auto-generatedmethod stub
selectedItem = position;
Toast.makeText(EX04_20.this, mString[selectedItem], Toast.LENGTH_SHORT)
.show();
super.onListItemClick(l, v, position, id);
}
@Override
publicboolean onCreateOptionsMenu(Menu menu)
{
// TODO Auto-generatedmethod stub
/* menu群组ID */
int idGroup1 = 0;
/* Theorder position of the item */
int orderMenuItem1 = Menu.NONE;
int orderMenuItem2 = Menu.NONE + 1;
menu.add(idGroup1, MENU_LIST1,orderMenuItem1, R.string.str_menu_list1);
menu.add(idGroup1, MENU_LIST2,orderMenuItem2, R.string.str_menu_list2);
returnsuper.onCreateOptionsMenu(menu);
}
@Override
publicboolean onOptionsItemSelected(MenuItem item)
{
// TODO Auto-generatedmethod stub
switch (item.getItemId())
{
case (MENU_LIST1):
mString = new String[]
{
getResources().getString(R.string.str_list1),
getResources().getString(R.string.str_list2),
getResources().getString(R.string.str_list3),
getResources().getString(R.string.str_list4)
};
mla = new ArrayAdapter<String>(EX04_20.this, R.layout.main, mString);
EX04_20.this.setListAdapter(mla);
break;
case (MENU_LIST2):
mString = new String[]
{
getResources().getString(R.string.str_list5),
getResources().getString(R.string.str_list6),
getResources().getString(R.string.str_list7),
getResources().getString(R.string.str_list8)
};
mla = new ArrayAdapter<String>(EX04_20.this, R.layout.main, mString);
EX04_20.this.setListAdapter(mla);
break;
}
returnsuper.onOptionsItemSelected(item);
}
/*用于定于使用的语言*/
Resources res=getResources();
//更改语系
Configuration conf=res.getConfiguration();
conf.locale=Locale.CHINESE;
DisplayMetrics dm=res.getDisplayMetrics();
res.updateConfiguration(conf, dm);
// 如果选中的话
if (cb.isChecked()) {
// 设置EditText的内容为可见的
// 使用et.setTransformationMethod(HideReturnsTransformationMethod.getInstance())进行显示;
et.setTransformationMethod(HideReturnsTransformationMethod
.getInstance());
} else
et.setTransformationMethod(PasswordTransformationMethod
.getInstance());
{
}
例子:
private Vibrator mVibrator01;
/** Calledwhen the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* 设定ToggleButton的对象 */
mVibrator01 = (Vibrator) getApplication().getSystemService(
Service.VIBRATOR_SERVICE);
final ToggleButton mtogglebutton1 = (ToggleButton)findViewById(R.id.myTogglebutton1);
final ToggleButton mtogglebutton2 = (ToggleButton)findViewById(R.id.myTogglebutton2);
final ToggleButton mtogglebutton3 = (ToggleButton)findViewById(R.id.myTogglebutton3);
/* 设定ToggleButton使用OnClickListener来启动事件 */
mtogglebutton1.setOnClickListener(new OnClickListener()
{
publicvoid onClick(View v)
{
if (mtogglebutton1.isChecked())
{
/* 设定震动的周期 */
mVibrator01.vibrate(newlong[]
{ 100, 10, 100, 1000 }, -1);
/* 用Toast显示震动启动 */
Toast.makeText(EX05_06.this,getString(R.string.str_ok),
Toast.LENGTH_SHORT).show();
} else
{
/* 取消震动 */mVibrator01.cancel();
/* 用Toast显示震动取消 */
Toast.makeText(EX05_06.this, getString(R.string.str_end),
Toast.LENGTH_SHORT).show();
}
}
});
/* 设定ToggleButton使用OnClickListener来启动事件 */
mtogglebutton2.setOnClickListener(new OnClickListener()
{
publicvoid onClick(View v)
{
if (mtogglebutton2.isChecked())
{
/* 设定震动的周期 */mVibrator01.vibrate(newlong[]
{ 100, 100, 100, 1000 }, 0);
/* 用Toast显示震动启动 */
Toast.makeText(EX05_06.this,getString(R.string.str_ok),
Toast.LENGTH_SHORT).show();
} else
{
/* 取消震动 */
mVibrator01.cancel();
/* 用Toast显示震动取消 */
Toast.makeText(EX05_06.this,getString(R.string.str_end),
Toast.LENGTH_SHORT).show();
}
}
});
mtogglebutton3.setOnClickListener(new OnClickListener()
{
publicvoid onClick(View v)
{
if (mtogglebutton3.isChecked())
{
/* 设定震动的周期 */
mVibrator01.vibrate(newlong[]
{ 1000, 50, 1000, 50, 1000 }, 0);
/* 用Toast显示震动启动 */
Toast.makeText(EX05_06.this,getString(R.string.str_ok),
Toast.LENGTH_SHORT).show();
} else
{
/* 取消震动 */
mVibrator01.cancel();
/* 用Toast显示震动取消 */
Toast.makeText(EX05_06.this,getString(R.string.str_end),
Toast.LENGTH_SHORT).show();
}
}
});
例子:
/* 声明四个UI变量与一个常数作为Activity接收回传值用 */
private TextView mTextView01;
private Button mButton01;
private EditText mEditText01;
private EditText mEditText02;
privatestaticfinalintPICK_CONTACT_SUBACTIVITY = 2;
/** Calledwhen the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* 透过findViewById建构子来建构一个TextView,两个EditText,一个Button对象* */
mTextView01 = (TextView) findViewById(R.id.myTextView1);
mEditText01 = (EditText) findViewById(R.id.myEditText01);
mEditText02 = (EditText) findViewById(R.id.myEditText02);
mButton01 = (Button) findViewById(R.id.myButton1);
/* 设定onClickListener 让使用者点选Button时搜寻联系人 */
mButton01.setOnClickListener(new Button.OnClickListener()
{
@Override
publicvoid onClick(View v)
{
// TODO Auto-generated method stub
/* 建构Uri来取得联络人的资源位置 */
// Uri uri =Uri.parse("content://contacts/people/");
/* 透过Intent来取得联络人数据并回传所选的值 */
// Intent intent = new Intent(Intent.ACTION_PICK, uri);
/* 开启新的Activity并期望该Activity回传值 */
// startActivityForResult(intent, PICK_CONTACT_SUBACTIVITY);
startActivityForResult(new Intent(Intent.ACTION_PICK,
android.provider.ContactsContract.Contacts.CONTENT_URI),
PICK_CONTACT_SUBACTIVITY);
}
});
}
@Override
protectedvoid onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generatedmethod stub
try
{
switch (requestCode)
{
casePICK_CONTACT_SUBACTIVITY:
final Uri uriRet = data.getData();
if (uriRet != null)
{
try
{
/* 必须要有android.permission.READ_CONTACTS权限 */
Cursor c = managedQuery(uriRet, null, null, null, null);
/* 将Cursor移到资料最前端 */
c.moveToFirst();
/* 取得联络人的姓名 */
String strName = c
.getString(c
.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
/* 将姓名写入EditText01中 */
mEditText01.setText(strName);
/* 取得联络人的电话 */
int contactId = c.getInt(c
.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phones =getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
+ contactId, null, null);
StringBuffer sb = new StringBuffer();
int typePhone, resType;
String numPhone;
if (phones.getCount() > 0)
{
phones.moveToFirst();
/* 2.0可以允许User设定多组电话号码,但本范例只捞一组电话号码作示范 */
typePhone = phones
.getInt(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
numPhone = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
resType = ContactsContract.CommonDataKinds.Phone
.getTypeLabelResource(typePhone);
sb.append(getString(resType) + ": " + numPhone+ "\n");
/* 将电话写入EditText02中 */
mEditText02.setText(numPhone);
} else
{
sb.append("no Phone number found");
}
/* Toast是否读取到完整的电话种类与电话号码 */
Toast.makeText(this, sb.toString(),Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
/* 将错误信息在TextView中显示 */
mTextView01.setText(e.toString());
e.printStackTrace();
}
}
break;
default:
break;
}
} catch (Exception e)
{
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode,data);
}
<!--取得讀取通訊錄的權限 -->
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
/* 清除背景图案 */
@Override
publicvoid clearWallpaper() throws IOException
{
// TODO Auto-generatedmethod stub
super.clearWallpaper();
}
图片例子:
protectedstatic InputStream is;
private ImageAdapter mImageAdapter01;
/** Calledwhen the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*设定图片*/
Integer[] myImageIds = { R.drawable.google, R.drawable.helloking,R.drawable.chamberlain, R.drawable.king, R.drawable.with, };
mImageAdapter01 = new ImageAdapter(EX05_13.this, myImageIds);
/*设定图为Gallery的显示方式*/
Gallery g = (Gallery) findViewById(R.id.mygallery);
g.setAdapter(mImageAdapter01);
g.setOnItemClickListener(newGallery.OnItemClickListener()
{
@Override
publicvoid onItemClick(AdapterView <?> parent,View v, finalint position, long id)
{
// TODO Auto-generated method stub
new AlertDialog.Builder(EX05_13.this).setTitle(R.string.app_about)
/*设定弹出窗口的图式*/
.setIcon(mImageAdapter01.myImageIds[position])
/*设定弹出窗口的讯息*/
.setMessage(R.string.app_about_msg)
/*确认窗口*/
.setPositiveButton(R.string.str_ok, newDialogInterface.OnClickListener()
{
publicvoid onClick(DialogInterface dialoginterface, int i)
{
Resources resources =getBaseContext().getResources();
is = resources.openRawResource(mImageAdapter01.myImageIds [position]);
try
{
/*更换桌布*/
setWallpaper(is);
/*用Toast来显示桌布已更换*/
Toast.makeText(EX05_13.this,getString(R.string. my_gallery_text_pre),Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
};
}
})
/*设定跳出窗口的返回事件*/
.setNegativeButton(R.string.str_no, newDialogInterface.OnClickListener()
{
publicvoid onClick(DialogInterface dialoginterface, int i)
{
/*用Toast来显示桌布已取消*/
Toast.makeText(EX05_13.this,getString(R.string. my_gallery_text_no),Toast.LENGTH_SHORT).show(); } }) .show();
}
});
}
publicclass ImageAdapter extends BaseAdapter
{
intmGalleryItemBackground;
private Context mContext;
private Integer[] myImageIds;
public ImageAdapter(Context c,Integer[] aid)
{
mContext = c; myImageIds = aid;
TypedArray a =obtainStyledAttributes(R.styleable.Gallery);
mGalleryItemBackground = a.getResourceId( R.styleable.Gallery_android_galleryItemBackground, 0);
a.recycle();
}
@Override
publicint getCount()
{
// TODO Auto-generatedmethod stub
returnmyImageIds.length;
}
@Override
public Object getItem(int position)
{
// TODO Auto-generatedmethod stub
returnnull;
}
@Overridepubliclong getItemId(int position)
{
// TODO Auto-generatedmethod stub
return position;
}
@Override
public View getView(int position, ViewconvertView, ViewGroup parent)
{
// TODO Auto-generatedmethod stub
/*产生ImageView对象*/
ImageView i = new ImageView(mContext);
/*设定图片给imageView对象*/
i.setImageResource(myImageIds[position]);
/*重新设定图片的宽高*/
i.setScaleType(ImageView.ScaleType.FIT_XY);
/*重新设定Layout的宽高*/
i.setLayoutParams(new Gallery.LayoutParams(138,108));
/*设定Gallery背景图*/
i.setBackgroundResource(mGalleryItemBackground);
/*传回imageView对象*/
return i;
}
}
@Override
publicvoid setWallpaper(InputStream data) throws IOException
{
// TODO Auto-generatedmethod stub
super.setWallpaper(data);
}
}
wifi例子:
/* 以getSystemService取得WIFI_SERVICE */
mWiFiManager01 = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
/* 判断执行程序后的WiFi状态是否启动或启动中 */
if(mWiFiManager01.isWifiEnabled())
{
/* 判断WiFi状态是否已启动 */
if(mWiFiManager01.getWifiState()==WifiManager.WIFI_STATE_ENABLED)
{
/* 若WiFi已启动,将核取项打勾 */
mCheckBox01.setChecked(true);
/* 更改核取项文字为关闭WiFi*/
mCheckBox01.setText(R.string.str_uncheck);
}
else
{
/* 若WiFi未启动,将核取项勾选取消 */
mCheckBox01.setChecked(false);
/* 变更核取项文字为启动WiFi*/
mCheckBox01.setText(R.string.str_checked);
}
}
else
{
mCheckBox01.setChecked(false);
mCheckBox01.setText(R.string.str_checked);
}
/* 捕捉CheckBox的点击事件 */
mCheckBox01.setOnClickListener(new CheckBox.OnClickListener()
{
@Override
publicvoid onClick(View v)
{
// TODO Auto-generated method stub
/* 当核取项为取消核取状态 */
if(mCheckBox01.isChecked()==false)
{
/* 尝试关闭Wi-Fi服务 */
try
{
/* 判断WiFi状态是否为已启动 */
if(mWiFiManager01.isWifiEnabled() )
{
/* 关闭WiFi */
if(mWiFiManager01.setWifiEnabled(false))
{
mTextView01.setText(R.string.str_stop_wifi_done);
}
else
{
mTextView01.setText(R.string.str_stop_wifi_failed);
}
}
else
{
/* WiFi状态不为已启动状态时 */
switch(mWiFiManager01.getWifiState())
{
/* WiFi正在启动过程中,导致无法关闭... */
case WifiManager.WIFI_STATE_ENABLING:
mTextView01.setText
(
getResources().getText(R.string.str_stop_wifi_failed)+":"+
getResources().getText(R.string.str_wifi_enabling)
);
break;
/* WiFi正在关闭过程中,导致无法关闭... */
case WifiManager.WIFI_STATE_DISABLING:
mTextView01.setText
(
getResources().getText(R.string.str_stop_wifi_failed)+":"+
getResources().getText(R.string.str_wifi_disabling)
);
break;
/* WiFi已经关闭 */
case WifiManager.WIFI_STATE_DISABLED:
mTextView01.setText
(
getResources().getText(R.string.str_stop_wifi_failed)+":"+
getResources().getText(R.string.str_wifi_disabled)
);
break;
/* 无法取得或辨识WiFi状态 */
case WifiManager.WIFI_STATE_UNKNOWN:
default:
mTextView01.setText
(
getResources().getText(R.string.str_stop_wifi_failed)+":"+
getResources().getText(R.string.str_wifi_unknow)
);
break;
}
mCheckBox01.setText(R.string.str_checked);
}
}
catch (Exception e)
{
Log.i("HIPPO", e.toString());
e.printStackTrace();
}
}
elseif(mCheckBox01.isChecked()==true)
{
/* 尝试开启Wi-Fi服务 */
try
{
/* 确认WiFi服务是关闭且不在启动操作中 */
if(!mWiFiManager01.isWifiEnabled() && mWiFiManager01.getWifiState()!=WifiManager.WIFI_STATE_ENABLING )
{
if(mWiFiManager01.setWifiEnabled(true))
{
switch(mWiFiManager01.getWifiState())
{
/* WiFi正在启动启过程中,导致无法启动... */
case WifiManager.WIFI_STATE_ENABLING:
mTextView01.setText
(
getResources().getText(R.string.str_wifi_enabling)
);
break;
/* WiFi已经为启动,无法再次启动... */
case WifiManager.WIFI_STATE_ENABLED:
mTextView01.setText
(
getResources().getText(R.string.str_start_wifi_done)
);
break;
/* 其他未知的错误 */
default:
mTextView01.setText
(
getResources().getText(R.string.str_start_wifi_failed)+":"+
getResources().getText(R.string.str_wifi_unknow)
);
break;
}
}
else
{
mTextView01.setText(R.string.str_start_wifi_failed);
}
}
else
{
switch(mWiFiManager01.getWifiState())
{
/* WiFi正在启动过程中,导致无法启动... */
case WifiManager.WIFI_STATE_ENABLING:
mTextView01.setText
(
getResources().getText(R.string.str_start_wifi_failed)+":"+
getResources().getText(R.string.str_wifi_enabling)
);
break;
/* WiFi正在关闭过程中,导致无法启动... */
case WifiManager.WIFI_STATE_DISABLING:
mTextView01.setText
(
getResources().getText(R.string.str_start_wifi_failed)+":"+
getResources().getText(R.string.str_wifi_disabling)
);
break;
/* WiFi已经关闭 */
case WifiManager.WIFI_STATE_DISABLED:
mTextView01.setText
(
getResources().getText(R.string.str_start_wifi_failed)+":"+
getResources().getText(R.string.str_wifi_disabled)
);
break;
/* 无法取得或辨识WiFi状态 */
case WifiManager.WIFI_STATE_UNKNOWN:
default:
mTextView01.setText
(
getResources().getText(R.string.str_start_wifi_failed)+":"+
getResources().getText(R.string.str_wifi_unknow)
);
break;
}
}
mCheckBox01.setText(R.string.str_uncheck);
}
catch (Exception e)
{
Log.i("HIPPO", e.toString());
e.printStackTrace();
}
}
}
});
}
publicvoid mMakeTextToast(String str, boolean isLong)
{
if(isLong==true)
{
Toast.makeText(EX05_17.this, str, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(EX05_17.this, str, Toast.LENGTH_SHORT).show();
}
}
@Override
protectedvoid onResume()
{
// TODO Auto-generatedmethod stub
/* 于onResume重写事件为取得开启程序当前WiFi的状态 */
try
{
switch(mWiFiManager01.getWifiState())
{
/* WiFi已经为启动状态... */
case WifiManager.WIFI_STATE_ENABLED:
mTextView01.setText
(
getResources().getText(R.string.str_wifi_enabling)
);
break;
/* WiFi正在启动过程中状态... */
case WifiManager.WIFI_STATE_ENABLING:
mTextView01.setText
(
getResources().getText(R.string.str_wifi_enabling)
);
break;
/* WiFi正在关闭过程中... */
case WifiManager.WIFI_STATE_DISABLING:
mTextView01.setText
(
getResources().getText(R.string.str_wifi_disabling)
);
break;
/* WiFi已经关闭 */
case WifiManager.WIFI_STATE_DISABLED:
mTextView01.setText
(
getResources().getText(R.string.str_wifi_disabled)
);
break;
/* 无法取得或辨识WiFi状态 */
case WifiManager.WIFI_STATE_UNKNOWN:
default:
mTextView01.setText
(
getResources().getText(R.string.str_wifi_unknow)
);
break;
}
}
catch(Exception e)
{
mTextView01.setText(e.toString());
e.getStackTrace();
}
super.onResume();
}
@Override
protectedvoid onPause()
{
// TODO Auto-generatedmethod stub
super.onPause();
}
取得正在运行的例子:
private Button mButton01;
private ListView mListView01;
private ArrayAdapter<String> aryAdapter1;
private ArrayList<String> arylistTask;
/* 类成员设定取并最?几笔的Task数量 */
privateintintGetTastCounter=30;
/* 类成员ActivityManager对象 */
private ActivityManager mActivityManager;
/** Calledwhen the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton01 = (Button)findViewById(R.id.myButton1);
mListView01 = (ListView)findViewById(R.id.myListView1);
mButton01.setOnClickListener(new Button.OnClickListener()
{
@Override
publicvoid onClick(View v)
{
// TODO Auto-generated method stub
try
{
/* ActivityManager对象守系统取得ACTIVITY_SERVICE */
mActivityManager =(ActivityManager)EX05_21.this.getSystemService(ACTIVITY_SERVICE);
arylistTask = new ArrayList<String>();
/* 以getRunningTasks方法取并正在运行中的程序TaskInfo */
List<ActivityManager.RunningTaskInfo> mRunningTasks = mActivityManager.getRunningTasks(intGetTastCounter);
//List<ActivityManager.RunningServiceInfo> mRunningTasks =mActivityManager.getRunningServices(intGetTastCounter);
int i = 1;
/* 以循环及baseActivity方式取得名称与ID */
for (ActivityManager.RunningTaskInfo amTask :mRunningTasks)
//for (ActivityManager.RunningServiceInfo amTask : mRunningTasks)
{
/* baseActivity.getClassName */
arylistTask.add("" + (i++) + ": "+ amTask.baseActivity.getClassName()+ "(ID=" + amTask.id +")");
//arylistTask.add("" + (i++) + ": "+ amTask.process +"(ID=" + amTask.pid +")");
}
aryAdapter1 = new ArrayAdapter<String>(EX05_21.this, R.layout.simple_list_item_1, arylistTask);
if(aryAdapter1.getCount()==0)
{
/* 当没有任何运行的操作,则提示信息 */
mMakeTextToast
(
getResources().getText(R.string.str_err_no_running_task).toString(),
//getResources().getText(R.string.str_err_no_running_service).toString(),
true
);
}
else
{
/* 发现后台运行程序,以ListView Widget条在出现 */
mListView01.setAdapter(aryAdapter1);
}
}
catch(SecurityException e)
{
/* 当无GET_TASKS权限时(SecurityException例?)提示信息 */
mMakeTextToast
(
getResources().getText(R.string.str_err_permission).toString(),
true
);
}
}
});
/* 当User运行选择时的事件处理 */
mListView01.setOnItemSelectedListener(new ListView.OnItemSelectedListener()
{
@Override
publicvoid onItemSelected(AdapterView<?> parent,View v, int id, long arg3)
{
// TODO Auto-generated method stub
/* 由于将运行,故以id取出数组元素名称 */
mMakeTextToast(arylistTask.get(id).toString(),false);
}
@Override
publicvoid onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
/* 当User运行点击时的事件处理 */
mListView01.setOnItemClickListener(new ListView.OnItemClickListener()
{
@Override
publicvoid onItemClick(AdapterView<?> parent,View v, int id, long arg3)
{
// TODO Auto-generated method stub
/* 由于将运行?囫北阵在?放,故北id取叨阵在元素宅称 */
mMakeTextToast(arylistTask.get(id).toString(), false);
}
});
}
publicvoid mMakeTextToast(String str, boolean isLong)
{
if(isLong==true)
{
Toast.makeText(EX05_21.this, str, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(EX05_21.this, str, Toast.LENGTH_SHORT).show();
}
}
旋转屏幕例子:
/* 方法又需要用到的Display对象 */
final Display defaultDisplay =getWindow().getWindowManager().getDefaultDisplay();
mButton01 = (Button)findViewById(R.id.myButton1);
mTextView01 = (TextView)findViewById(R.id.myTextView1);
if(getRequestedOrientation()==-1)
{
mTextView01.setText(getResources().getText(R.string.str_err_1001));
}
/* 当按下按钮旋转屏幕画面 */
mButton01.setOnClickListener(new Button.OnClickListener()
{
@Override
publicvoid onClick(View arg0)
{
/* 方法一:重写getRequestedOrientation */
/* 若无法取得screenOrientation属性 */
if(getRequestedOrientation()==-1)
{
/* 提示无法进行画面旋转叫能,帆无法??Orientation */
mTextView01.setText(getResources().getText(R.string.str_err_1001));
}
else
{
if(getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
{
/* 若当前为横式,则变更为直式显示 */
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
elseif(getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
{
/* 若当前为直式,则变更为横式显示 */
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
/* 方法二:判断屏幕宽高比(扩展学习) */
int h= defaultDisplay.getHeight();
int w = defaultDisplay.getWidth();
/* 否分辨率为按钮按下当下的分辨率 */
mTextView01.setText(Integer.toString(h)+"x"+Integer.toString(w));
//if(w > h)
//{
/* Landscape */
/* 重写Activity里的setRequestedOrientation()方法 */
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//}
//else
//{
/* Portrait */
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//}
}
});
}
@Override
publicvoid setRequestedOrientation(int requestedOrientation)
{
// TODO Auto-generatedmethod stub
/* 判断要变更的方向,以Toast提示 */
switch(requestedOrientation)
{
case (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE):
mMakeTextToast
(
getResources().getText(R.string.str_msg1).toString(),
false
);
break;
case (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT):
mMakeTextToast
(
getResources().getText(R.string.str_msg2).toString(),
false
);
break;
}
super.setRequestedOrientation(requestedOrientation);
}
@Override
publicint getRequestedOrientation()
{
// TODO Auto-generatedmethod stub
/* 此重写getRequestedOrientation方法,可取得当前屏幕的方向 */
returnsuper.getRequestedOrientation();
}
publicvoid mMakeTextToast(String str, boolean isLong)
{
if(isLong==true)
{
Toast.makeText(EX05_22.this, str, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(EX05_22.this, str, Toast.LENGTH_SHORT).show();
}
}
例子:
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
/* 设定ContentView为自定义的MyView */
MyView myView = new MyView(this);
setContentView(myView);
}
/* 自定义继承View的MyView */
privateclass MyView extends View
{
public MyView(Context context)
{
super(context);
}
/* 覆写onDraw() */
@Override
protectedvoid onDraw(Canvas canvas)
{
super.onDraw(canvas);
/* 设定背景为白色 */
canvas.drawColor(Color.WHITE);
Paint paint = new Paint();
/* 去锯齿 */
paint.setAntiAlias(true);
/* 设定paint的颜色 */
paint.setColor(Color.RED);
/* 设定paint的style为STROKE:空心的 */
paint.setStyle(Paint.Style.STROKE);
/* 设定paint的外框宽度 */
paint.setStrokeWidth(3);
/* 画一个空心圆形 */
canvas.drawCircle(40, 40, 30, paint);
/* 画一个空心正方形 */
canvas.drawRect(10, 90, 70, 150, paint);
/* 画一个空心长方形 */
canvas.drawRect(10, 170, 70, 200, paint);
/* 画一个空心椭圆形 */
RectF re = new RectF(10, 220, 70, 250);
canvas.drawOval(re, paint);
/* 画一个空心三角形 */
Path path = new Path();
path.moveTo(10, 330);
path.lineTo(70, 330);
path.lineTo(40, 270);
path.close();
canvas.drawPath(path, paint);
/* 画一个空心梯形 */
Path path1 = new Path();
path1.moveTo(10, 410);
path1.lineTo(70, 410);
path1.lineTo(55, 350);
path1.lineTo(25, 350);
path1.close();
canvas.drawPath(path1, paint);
/* 设定paint的style为FILL:实心 */
paint.setStyle(Paint.Style.FILL);
/* 设定paint的颜色 */
paint.setColor(Color.BLUE);
/* 画一个实心圆 */
canvas.drawCircle(120, 40, 30, paint);
/* 画一个实心正方形 */
canvas.drawRect(90, 90, 150, 150, paint);
/* 画一个实心长方形 */
canvas.drawRect(90, 170, 150, 200,paint);
/* 画一个实心椭圆形 */
RectF re2 = new RectF(90, 220, 150, 250);
canvas.drawOval(re2, paint); /* 画一个实心三角形 */
Path path2 = new Path();
path2.moveTo(90, 330);
path2.lineTo(150, 330);
path2.lineTo(120, 270);
path2.close();
canvas.drawPath(path2, paint); /* 画一个实心梯形 */
Path path3 = new Path();
path3.moveTo(90, 410);
path3.lineTo(150, 410);
path3.lineTo(135, 350);
path3.lineTo(105, 350);
path3.close();
canvas.drawPath(path3, paint); /* 设定渐层色 */
Shader mShader = new LinearGradient(0,0, 100, 100, newint[]
{ Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW }, null,
Shader.TileMode.REPEAT);
paint.setShader(mShader); /* 画一个渐层色的圆形 */
canvas.drawCircle(200, 40, 30, paint); /* 画一个渐层色的正方形 */
canvas.drawRect(170, 90, 230, 150,paint); /* 画一个渐层色的长方形 */
canvas.drawRect(170, 170, 230, 200,paint); /* 画一个渐层色的椭圆形 */
RectF re3 = new RectF(170, 220, 230, 250);
canvas.drawOval(re3, paint); /* 画一个渐层色的三角形 */
Path path4 = new Path();
path4.moveTo(170, 330);
path4.lineTo(230, 330);
path4.lineTo(200, 270);
path4.close();
canvas.drawPath(path4, paint); /* 画一个渐层色的梯形 */
Path path5 = new Path();
path5.moveTo(170, 410);
path5.lineTo(230, 410);
path5.lineTo(215, 350);
path5.lineTo(185, 350);
path5.close();
canvas.drawPath(path5, paint); /* 写字 */
paint.setTextSize(24);
canvas.drawText(getResources().getString(R.string.str_text1),
240, 50, paint);
canvas.drawText(getResources().getString(R.string.str_text2),
240, 120, paint);
canvas.drawText(getResources().getString(R.string.str_text3),
240, 190, paint);
canvas.drawText(getResources().getString(R.string.str_text4),
240, 250, paint);
canvas.drawText(getResources().getString(R.string.str_text5),
240, 320, paint);
canvas.drawText(getResources().getString(R.string.str_text6),
240, 390, paint);
}
}
点击屏幕图片跟随例子:
/* 宣告ImageView变量 */
private ImageView mImageView01; /* 宣告相关变量作为储存图片宽高,位置使用 */
privateintintWidth, intHeight, intDefaultX, intDefaultY;
privatefloatmX, mY; /* 宣告储存屏幕的分辨率变量 */
privateintintScreenX, intScreenY;
/** Calledwhen the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main); /* 取得屏幕对象 */
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm); /* 取得屏幕解析像素 */
intScreenX = dm.widthPixels;
intScreenY = dm.heightPixels; /* 设定图片的宽高 */
intWidth = 100;
intHeight = 100; /* 透过findViewById建构子建立ImageView对象 */
mImageView01 = (ImageView) findViewById(R.id.myImageView1); /* 将图片从Drawable指派给ImageView来呈现 */
mImageView01.setImageResource(R.drawable.baby); /* 初始化按钮位置置中 */
RestoreButton(); /* 当按下ImageView,还原初始位置 */
mImageView01.setOnClickListener(new Button.OnClickListener()
{
@Override
publicvoid onClick(View v)
{
RestoreButton();
}
});
} /* 覆写触控事件 */
@Override
publicboolean onTouchEvent(MotionEvent event)
{ /* 取得手指触控屏幕的位置 */
float x = event.getX();
float y = event.getY();
try
{ /* 触控事件的处理 */
switch (event.getAction())
{ /* 点选屏幕 */
case MotionEvent.ACTION_DOWN:
picMove(x, y);
break; /* 移动位置 */
case MotionEvent.ACTION_MOVE:
picMove(x, y);
break; /* 离开屏幕 */
case MotionEvent.ACTION_UP:
picMove(x, y);
break;
}
} catch (Exception e)
{
e.printStackTrace();
}
returntrue;
} /* 移动图片的方法 */
privatevoid picMove(float x, float y)
{ /* 默认微调图片与指针的相对位置 */
mX = x - (intWidth / 2);
mY = y - (intHeight / 2); /* 防图片超过屏幕的相关处理 *//* 防止屏幕向右超过屏幕 */
if ((mX + intWidth) > intScreenX)
{
mX = intScreenX - intWidth;
} /* 防止屏幕向左超过屏幕 */elseif (mX < 0)
{
mX = 0;
} /* 防止屏幕向下超过屏幕 */elseif ((mY + intHeight) > intScreenY)
{
mY = intScreenY - intHeight;
} /* 防止屏幕向上超过屏幕 */elseif (mY < 0)
{
mY = 0;
} /* 透过log 来检视图片位置 */
Log.i("jay", Float.toString(mX) + "," + Float.toString(mY)); /*
* 以setLayoutParams方法,
* 重新安排Layout上的位置
*/
mImageView01.setLayoutParams(new AbsoluteLayout.LayoutParams(intWidth,
intHeight, (int) mX, (int) mY));
} /* 还原ImageView位置的事件处理 */
publicvoid RestoreButton()
{
intDefaultX = ((intScreenX - intWidth) / 2);
intDefaultY = ((intScreenY - intHeight) / 2); /* Toast还原位置坐标 */
mMakeTextToast("(" + Integer.toString(intDefaultX) + ","
+ Integer.toString(intDefaultY) + ")", true); /*
* 以setLayoutParams方法,重新安排Layout上的位置
*/
mImageView01.setLayoutParams(new AbsoluteLayout.LayoutParams(intWidth,
intHeight, intDefaultX, intDefaultY));
} /* 自定义一发出讯息的方法 */
publicvoid mMakeTextToast(String str, boolean isLong)
{
if (isLong == true)
{
Toast.makeText(EX07_04.this, str, Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(EX07_04.this, str, Toast.LENGTH_SHORT).show();
}
}
播放音乐例子:
/*声明一个 ImageButton,TextView,MediaPlayer变量*/
private ImageButton mButton01, mButton02, mButton03;
private TextView mTextView01;
private MediaPlayer mMediaPlayer01;
/*声明一个Flag做为确认音乐是否暂停的变量并预设为false*/
privatebooleanbIsPaused = false;
/** Calledwhen the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*透过findViewById建构巳建立TextView与ImageView对象*/
mButton01 =(ImageButton) findViewById(R.id.myButton1);
mButton02 =(ImageButton) findViewById(R.id.myButton2);
mButton03 =(ImageButton) findViewById(R.id.myButton3);
mTextView01 = (TextView) findViewById(R.id.myTextView1);
/*onCreate时建立MediaPlayer对象 */
mMediaPlayer01 = new MediaPlayer();
/* 将音乐以Import的方式保存?res/raw/always.mp3 */
mMediaPlayer01 = MediaPlayer.create(EX07_09.this, R.raw.big);
/* 执行播放音乐的按钮 */
mButton01.setOnClickListener(new ImageButton.OnClickListener()
{
@Override
/*重写OnClick事件*/
publicvoid onClick(View v)
{
// TODO Auto-generated method stub
try
{
if (mMediaPlayer01 != null)
{
mMediaPlayer01.stop();
}
/*?MediaPlayer取得播放资源与stop()之后
* 要准备Playback的状态前几定要使用MediaPlayer.prepare()*/
mMediaPlayer01.prepare();
/*开始或反复播放*/
mMediaPlayer01.start();
/*改变TextView为开始播放状态*/
mTextView01.setText(R.string.str_start);
}
catch (Exception e)
{
// TODO Auto-generated catch block
mTextView01.setText(e.toString());
e.printStackTrace();
}
}
});
/* 停止播放 */
mButton02.setOnClickListener(new ImageButton.OnClickListener()
{
@Override
publicvoid onClick(View arg0)
{
// TODO Auto-generated method stub
try
{
if (mMediaPlayer01 != null)
{
/*停止播放*/
mMediaPlayer01.stop();
/*改变TextView为停止播放状态*/
mTextView01.setText(R.string.str_close);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
mTextView01.setText(e.toString());
e.printStackTrace();
}
}
});
/* 暂停播放 */
mButton03.setOnClickListener(new ImageButton.OnClickListener()
{
@Override
publicvoid onClick(View arg0)
{
// TODO Auto-generated method stub
try
{
if (mMediaPlayer01 != null)
{
/*是?为暂停状态=?*/
if(bIsPaused==false)
{
/*暂停播放*/
mMediaPlayer01.pause();
/*设定Flag为treu表示 Player状态为暂停*/
bIsPaused = true;
/*改变TextView为暂停播放*/
mTextView01.setText(R.string.str_pause);
}
/*是?为暂停状态=是*/
elseif(bIsPaused==true)
{
/*并复播叨状态*/
mMediaPlayer01.start();
/*设定Flag为false表示 Player状态为非暂停状态*/
bIsPaused = false;
/*改变TextView为开始播放*/
mTextView01.setText(R.string.str_start);
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
mTextView01.setText(e.toString());
e.printStackTrace();
}
}
});
/* 当MediaPlayer.OnCompletionLister会执行的Listener */
mMediaPlayer01.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
//@Override
/*重写文件播放完毕事件*/
publicvoid onCompletion(MediaPlayer arg0)
{
try
{
/*解除资源与MediaPlayer的指派关系
* 资源*/
mMediaPlayer01.release();
/*改变TextView为播放结束*/
mTextView01.setText(R.string.str_OnCompletionListener);
}
catch (Exception e)
{
mTextView01.setText(e.toString());
e.printStackTrace();
}
}
});
/* 当MediaPlayer.OnErrorListener会执行的Listener */
mMediaPlayer01.setOnErrorListener(new MediaPlayer.OnErrorListener()
{
@Override
/*重写错误处理事件*/
publicboolean onError(MediaPlayer arg0, int arg1, int arg2)
{
// TODO Auto-generated method stub
try
{
/*发生错误时夕解除资源与MediaPlayer的指派*/
mMediaPlayer01.release();
mTextView01.setText(R.string.str_OnErrorListener);
}
catch (Exception e)
{
mTextView01.setText(e.toString());
e.printStackTrace();
}
returnfalse;
}
});
}
@Override
/*重写加程序暂停状态事件*/
protectedvoid onPause()
{
// TODO Auto-generatedmethod stub
try
{
/*圳加程序暂停时解除资源与MediaPlayer的指派关系*/
mMediaPlayer01.release();
}
catch (Exception e)
{
mTextView01.setText(e.toString());
e.printStackTrace();
}
super.onPause();
}
获取网页:
publicclass HtmlRequest {
/**
* @param args
* @throws Exception
*/
publicstaticvoid main(String[] args) throws Exception {
//URL对象专门用于获取网络信息的一个对象
URL url=new URL("http://www.sohu.com/");
//打开连接
HttpURLConnection con= (HttpURLConnection)url.openConnection();
//HTTP有两种请求方式,一种是get,一种是post
con.setRequestMethod("GET");
//设置链接超时,设置为5秒
con.setConnectTimeout(5000);
//通过输入流获取HTML代码
InputStream is= con.getInputStream();
//得到HTML(文字)的二进制数据
byte[] img=readInputStream(is);
//将二进制的文字转换为字符串
String html=new String(img);
System.out.println(html);
}
//用于读取数据的方法
publicstaticbyte[] readInputStream(InputStream is) throws IOException
{
//定义一个输出流
ByteArrayOutputStream out=new ByteArrayOutputStream();
//定义一个缓冲区
byte [] buff=newbyte[1024];
int len=0;
while((len=is.read(buff))!=-1)
{
out.write(buff,0, len);
}
//将输入流的数据返回出去
return out.toByteArray();
}
}