【网学网提醒】:网学会员为您提供android基本功能实现方法参考,解决您在android基本功能实现方法学习中工作中的难题,参考学习。
android代码速查,常用一些基本功能实现方法
0android创建按钮
Buttonbutton=newButton(this);
1android创建输入框
EditTexteditText=newEditText(this);
2android创建文本
TextViewtextView=newTextView(this);
3android设置文本显示内容
TextViewtextView=newTextView(this);
textView.setText("helloworld!");
4android设置文本背景色
TextViewtextView=newTextView(this);
textView.setBackgroundColor(Color.YELLOW);
5android设置文本颜色
TextViewtextView=newTextView(this);
textView.setTextColor(Color.YELLOW);
6android设置文本文字大小
TextViewtextView=newTextView(this);
textView.setTextSize(18);
7android设置输入框宽度
EditTexteditText=newEditText(this);
editText.setWidth(200);
8android设置输入框为密码框
EditTexteditText=newEditText(this);
editText.setTransformationMethod(
PasswordTransformationMethod.getInstance());
9android设置输入框为密码框(xml配置)
android:password="true"
10android提示对话框的使用
AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
builder.setTitle("你好");
builder.setPositiveButton("OK",this);
builder.show()
需实现android.content.DialogInterface.OnClickListener接口
11androidListView的使用
ListViewlistView=newListView(this);
ArrayList
>list=newArrayList>();
SimpleAdapteradapter=newSimpleAdapter(this,list,R.layout.list,newString[]{"标题"},newint[]{R.id.TextView01});
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
然后实现OnItemClickListener接口
publicvoidonItemClick(AdapterView>parent,Viewview,intposition,longid){}
12android更新ListView
ListViewlistView=newListView(this);
ArrayList>list=newArrayList>();
SimpleAdapteradapter=newSimpleAdapter(this,list,R.layout.list,newString[]{"标题"},newint[]{R.id.TextView01});
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();//通知更新ListView
13android创建LinearLayout
LinearLayoutlayoutParant=newLinearLayout(this);
14android时间设置对话框的使用
DatePickerDialogdlg=newDatePickerDialog(this,this,year,month,day);
dlg.show();
/*yearmonthday均为int型,第二个参数为this时,该类需要implementsOnDateSetListener并重写
publicvoidonDateSet(DatePickerview,intyear,intmonthOfYear,intdayOfMonth){}*/
15android创建FrameLayout
FrameLayoutlayout=newFrameLayout(this);
16android触发键盘事件
layout.setOnKeyListener(this);
//需要implementsOnKeyListener并重写以下方法
publicbooleanonKey(Viewv,intkeyCode,KeyEventevent){
returnfalse;//返回是否销毁该事件以接收新的事件,比如返回true按下时可以不断执行这个方法,返回false则执行一次。
}
17android触发鼠标事件
layout.OnTouchListener(this)
;
//需要implementsOnTouchListener并重写以下方法
publicbooleanonTouch(Viewv,MotionEventevent){
returnfalse;//返回是否销毁该事件以接收新的事件,比如返回true按下时可以不断执行这个方法,返回false则执行一次。
}
18android获得屏幕宽度和高度
intwidth=this.getWindow().getWindowManager().getDefaultDisplay().getWidth();
intheight=this.getWindow().getWindowManager().getDefaultDisplay().getHeight();
19android布局添加控件
LinearLayoutlayout=newLinearLayout(this);
Buttonbutton=newButton(this);
layout.addView(button);
20androidintent实现activit之间跳转
Intentintent=newIntent();
intent.setClass(this,DestActivity.class);
startActivity(intent);
21androidintent设置action
Intentintent=newIntent();
intent.setAction(intent.ACTION_DIAL);
22androidintent设置data
Intentintent=newIntent();
intent.setData(Uri.parse("tel:00000000"));
23androidintent传数据
Intentintent=newIntent();
intent.putExtra("data",value);//value可以是很多种类型,在接收activity中取出后强制转换或调用相应类型的get函数。
24androidintent取数据
Stringvalue=(String)getIntent().getExtras().get("data");
//or
Stringvalue=getIntent().getExtras().getString("data");
25android利用paint和canvas画图
setContentView(newMyView(this));
classMyViewextendsView
{
publicMyView(Contextcontext)
{
super(context);
}
publicvoidonDraw(Canvascanvas)
{
Paintpaint=newPaint();//创建画笔
paint.setColor(Color.BLUE);//设置画笔颜色canvas.drawRect(0,0,100,100,paint);//画个正方形,坐标0,0,100,100。
}
}
26android新建对话框
Dialogdialog=newDialog(this);
dialog.setTitle("test");//设置标题
dialog.addContentView(button,newLayoutParams(-1,-1));//添加控件,-1是设置高度和宽度充满布局,-2是按照需要设置宽度高度。
dialog.show();
27android取消对话框
dialog.cancel();
28对View类刷新显示
view.invalidate();//通过这个调用view的onDraw()函数
28android对View类刷新显示
view.invalidate();//通过这个调用view的onDraw()函数
29android使用SurfaceView画图
setContentView(newMySurfaceView(this));
classMySurfaceViewextendsSurfaceViewimplementsSurfaceHolder.Callback
{
SurfaceHolderholder;
publicMySurfaceView(Contextcontext)
{
super(context);
holder=getHolder();
holder.addCallback(this);
}
classMyThreadextendsThread
{
publicvoidrun()
{Canvascanvas=holder.lockCanvas();Paintpaint=newPaint();paint.setColor(Color.YELLOW);canvas.drawRect(100,100,200,200,paint);
holder.unlockCanvasAndPost(canvas);
}
}
publicvoidsurfaceChanged(SurfaceHolderholder,intformat,intwidth,intheight){
}
publicvoidsurfaceCreated(SurfaceHolderholder){
newMyThread().start();
}
publicvoidsurfaceDestroyed(SurfaceHolderholder){}
}
30android获得控件findViewById
TextView
textView=(TextView)findViewById(R.id.TextView01);
31android十六进制设置画笔颜色
Paintpaint=newPaint();
paint.setColor(0xffffffff);//第一个ff是透明度的设置。
32android获得String.xml中配置的字符串
//在activity中直接调用
getText(R.string.app_name);
33android去掉应用程序头部
requestWindowFeature(Window.FEATURE_NO_TITLE);
34android使用SharedPreferences写入数据代码
getSharedPreferences("data",0).edit().putString("aa","bb")mit();
35android使用SharedPreferences读取数据代码
Stringdata=getSharedPreferences("data",0).getString("item","");//后面的""是默认值,没有取到则赋值为"",如果不想有默认,可以设置null。
36android继承SQLiteOpenHelper
classMyHelperextendsSQLiteOpenHelper
{
publicMyHelper(Contextcontext,Stringname,CursorFactoryfactory,intversion){
super(context,name,factory,version);
}
publicvoidonCreate(SQLiteDatabasedb)
{
db.execSQL(
"CREATETABLEIFNOTEXISTStesttable("+
"cardnointegerprimarykey,"+
"usernamevarchar,"+
"moneyinteger"+
")");
}
publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion)
{
db.execSQL("DROPTABLEIFEXISTStesttable");
onCreate(db);
}
}
37android利用SQLiteOpenHelper打开数据库
MyHelperdbHelper=newMyHelper(this,"testtable.db",null,1);
SQLiteDatabasedb=dbHelper.getReadableDatabase();//打开只读
//或者
SQLiteDatabasedb=dbHelper.getWritableDatabase();//打开可写
38android查询数据表并显示结果
Cursorcursor=db.query("testtable",null,null,null,null,null,null);
//db的获得请参见“利用SQLiteOpenHelper打开数据库”
while(!cursor.isAfterLast()){
Log.i("test",cursor.getString(0));
cursor.moveToNext();
}
39androidLogcat输出打印测试信息
Log.i("TAG","TEST");
40android数据表插入数据
ContentValuesvalues=newContentValues();
values.put("username","admin");
values.put("money","10000");
db.insert("testtable",null,values);
41android使得应用全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
42android设置LinearLayout方向为竖
layoutParant.setOrientation(LinearLayout.VERTICAL);
43android设置LinearLayout方向为横
layoutParant.setOrientation(LinearLayout.HORIZONTAL);
44android数据库更新数据
ContentValuesvalues=newContentValues();
values.put("username","admin");
values.put("money","10000");
db.update("testtable",values,"userno=1",null);
45android数据库删除数据
db.delete("testtable","userno=1",null);
46android判断sd卡是否存在
if(android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
{
Log.i("test","SDCARDexists");
}
else{
Log.i("test","SDCARDdoesn'texist");
}
47android创建ImageView
ImageViewview=newImageView(this);
view.setImageResource(R.drawable.icon);
48androi
d提示信息
Toasttoast=Toast.makeText(this,"hello",Toast.LENGTH_LONG);
toast.show();
49android创建单选框以及单选组
RadioButtonradioButton=newRadioButton(this);
RadioButtonradioButton2=newRadioButton(this);
radioButton.setText("yes");
radioButton2.setText("no");
RadioGroupradioGroup=newRadioGroup(this);
radioGroup.addView(radioButton);
radioGroup.addView(radioButton2);
50android新建播放器
MediaPlayerMediaPlayer=newMediaPlayer();
51android媒体播放器使用
//创建MediaPlayer
MediaPlayerplayer=newMediaPlayer();
//重置MediaPlayer
player.reset();
try{
//设置要播放的文件的路径player.setDataSource("/sdcard/1.mp3");
//准备播放player.prepare();
}
catch(Exceptione){}
//开始播放
player.start();
//设置播放完毕事件
player.setOnCompletionListener(newOnCompletionListener(){
publicvoidonCompletion(MediaPlayerplayer){
//播完一首循环try{
//再次准备播放player.prepare();
}catch(Exceptione){}player.start();
}});
52android媒体播放器暂停
player.pause();
53android清空cookies
CookieManager.getInstance().removeAllCookie();
54android文本设置粗体
TextViewtextView=newTextView(this);
TextPainttextPaint=textView.getPaint();
textPaint.setFakeBoldText(true);
55android网络权限配置
56androidGL设定背景色
gl.glClearColor(0.5f,0.2f,0.2f,1.0f);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
57android创建GL画布
publicclassMy3DViewextendsGLSurfaceView{
privateGLSurfaceView.Rendererrenderer;
publicMy3DView(Contextcontext){
super(context);
renderer=newMy3DRender();
setRenderer(renderer);
}}
58android创建复选框
CheckBoxcheckBox=newCheckBox(this);
59android复选框监听选择/取消事件
checkBox.setOnCheckedChangeListener(newOnCheckedChangeListener(){
publicvoidonCheckedChanged(CompoundButtonbuttonView,booleanisChecked){
Log.i("QSR","TEST");
}
});
60android创建菜单
//重写下面这个函数
publicbooleanonCreateOptionsMenu(Menumenu){
super.onCreateOptionsMenu(menu);
menu.add(0,1,1,"test1");
menu.add(0,2,2,"test2");
menu.add(0,3,3,"test3");
menu.add(0,4,4,"test4");
returntrue;
61android处理菜单选择事件
publicbooleanonOptionsItemSelected(MenuItemitem)
{
intid=item.getItemId();
switch(id){
case1:
Log.i("QSR","1");
break;
case2:
Log.i("QSR","2");
break;
case3:
Log.i("QSR","3");
break;
case4:
Log.i("QSR","4");
break;
default:
break;
}
returnsuper.onOptionsItemSelected(item);
}
}
62android允许程序访问GPS(XML配置)
63android允许程序访问GSM网络信息(XML配置)
64android允许程序访问WIFI网络信息(XML配置)
<
uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/>
65android允许程序更新电池状态(XML配置)
66android允许程序写短信(XML配置)
67android允许程序设置壁纸(XML配置)
68android允许程序使用蓝牙(XML配置)
69android允许程序打电话(XML配置)
70android允许程序使用照相设备(XML配置)
71android允许程序改变网络状态(XML配置)
72android允许程序改变WIFI状态(XML配置)
73android允许程序删除缓存文件(XML配置)
74android允许程序删除包(XML配置)
75android允许程序禁用键盘锁(XML配置)
76android允许程序获取任务信息(XML配置)
77android允许程序截获鼠标或键盘等事件(XML配置)
78android允许程序使用socket(XML配置)
79android允许程序读取日历(XML配置)
80android允许程序读取系统日志(XML配置)
81android允许程序读取所有者数据(XML配置)
82android允许程序读取短信(XML配置)
83android允许程序重启设备(XML配置)
84android允许程序录制音频(XML配置)
85android允许程序发送短信(XML配置)
86android允许程序将自己置为最前(XML配置)
87android创建图像图片Bitmap
Resourcesres=getResources();
Bitmapbitmap=BitmapFactory.decodeResource(res,R.drawable.hh);
88android取得远程图片
HttpURLConnectionconn=(HttpURLConnection)imageUrl.openConnection();
conn.connect();
InputStreamis=conn.getInputStream();
bitmap=BitmapFact
ory.decodeStream(is);
is.close();
89android允许程序发送短信(XML配置)
90android启动和结束服务
startService(newIntent("qsr.test.MyService"));
stopService(newIntent("qsr.test.MyService"));
91android创建和配置Service
publicclassMyServiceextendsService{
publicIBinderonBind(Intentarg0){returnnull;}
publicvoidonStart(Intentintent,intstartId)
{
super.onStart(intent,startId);
//todosomethingwhenstart
}
publicvoidonDestroy()
{
super.onDestroy();
//todosomethingwhenstop
}
}
//xml配置
92android获得系统感应设备
SensorManagersensorManager=
(SensorManager)getSystemService(Context.SENSOR_SERVICE);
93android设置控件布局参数
textView01.setLayoutParams
(
newAbsoluteLayout.LayoutParams(100,60,0,0);//高100,宽60,x=0,y=0;
);
94android创建Drawable对象
Resourcesres=getResources();
Drawabledrawable=res.getDrawable(R.drawable.hh);
95android访问网页
Uriuri=Uri.parse("google");
Intentintent=newIntent(Intent.ACTION_VIEW,uri);
startActivity(intent);
96android打电话
Uriuri=Uri.parse("tel:00000000");
Intentintent=newIntent(Intent.ACTION_DIAL,uri);
startActivity(intent);
97android播放歌曲
Intentintent=newIntent(Intent.ACTION_VIEW);
Uriuri=Uri.parse("file:///sdcard/test.mp3");
intent.setDataAndType(uri,"audio/mp3");
startActivity(intent);
98android发送邮件
Intentintent=newIntent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT,"Theemailtext");
intent.setType("text/plain");
startActivity(Intent.createChooser(intent,"ChooseEmailClient"));
99android发短信
Uriuri=Uri.parse("smsto:123456789");
Intentintent=newIntent(Intent.ACTION_SENDTO,uri);
intent.putExtra("sms_body","TheSMStext");
startActivity(intent);
100android安装程序
UriinstallUri=Uri.fromParts("package","xxx",null);
Intentintent=newIntent(Intent.ACTION_PACKAGE_ADDED,installUri);
startActivity(intent);
101android卸载程序
UriuninstallUri=Uri.fromParts("package","xxx",null);
Intentintent=newIntent(Intent.ACTION_DELETE,uninstallUri);
startActivity(intent);
102android从xml配置获得控件对象
//TestActivity.java
textView=(TextView)findViewById(R.id.TextView01);
//main.xml
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="60px"
android:layout_y="60px"/>
103android获得触摸屏压力
publicbooleanonTouch(Viewv,MotionEventevent){
floatpressure=event.getPressure();
returnfalse;
}
104android给文本加
上滚动条
TextViewtextView=newTextView(this);
textView.setText(string);
ScrollViewscrollView=newScrollView(this);
scrollView.addView(textView);
setContentView(scrollView);
105android获得正在运行的所有服务
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
StringBufferserviceInfo=newStringBuffer();
ActivityManageractivityManager=(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
Listservices=activityManager.getRunningServices(256);
Iteratoriterator=services.iterator();
while(iterator.hasNext()){
RunningServiceInfosi=(RunningServiceInfo)iterator.next();
serviceInfo.append("pid:").append(si.pid);
serviceInfo.append("process:").append(si.process);
}
TextViewtextView=newTextView(this);
textView.setText(serviceInfo.toString());
ScrollViewscrollView=newScrollView(this);
scrollView.addView(textView);
setContentView(scrollView);
}
106android使用ContentResolver获得联系人和号码
ContentResolvercr=getContentResolver();
Cursorcur=cr.query(People.CONTENT_URI,null,null,null,null);
cur.moveToFirst();
do{
intnameColumn=cur.getColumnIndex(People.NAME);
intphoneColumn=cur.getColumnIndex(People.NUMBER);
Stringname=cur.getString(nameColumn);
StringphoneNumber=cur.getString(phoneColumn);
Toast.makeText(this,name,Toast.LENGTH_LONG).show();
Toast.makeText(this,phoneNumber,Toast.LENGTH_LONG).show();
}while(cur.moveToNext());
107android创建WebView
WebViewwebView=newWebView(this);
webView.loadData(""+"test"+"test"+"","text/html","utf-8");
108android设置地图是否显示卫星和街道
mapView.setSatellite(false);
mapView.setStreetView(true);
109android单选框清除
radioGroup.clearCheck();
110android给文本增加链接
Linkify.addLinks(mTextView01,Linkify.WEB_URLS);
Linkify.addLinks(mTextView02,Linkify.EMAIL_ADDRESSES);
Linkify.addLinks(mTextView03,Linkify.PHONE_NUMBERS);
111android设置手机震动
Vibratorvibrator=(Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE);
vibrator.vibrate(newlong[]{1000,1000,1000,1000},-1);//震动一秒,停一秒,再震一秒
112android创建下拉框
Spinnerspinner=newSpinner(this);
113android给spinner添加事件
spinner.setOnItemSelectedListener(
newSpinner.OnItemSelectedListener()
{
publicvoidonItemSelected(AdapterView>parent,Viewview,intposition,longid)
{
}
publicvoidonNothingSelected(AdapterView>parent)
{
}
});
114android图片的显示方式
ImageViewimageView=newImageView(this);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);//适应大小
imageView.setScaleType(ImageView.ScaleType.CENTER);//原始大小,居中显示
115android取得缓存目录
FilecacheDir=this.getCacheDir();
116android取得当前文件目录
FilefileDir=this.getFilesDir();
117android判断当前wifi是否可用
WifiManageraWiFiManager=(WifiManager)
this.getSystemService(Context.WIFI_SERVICE);
booleanisEnabled=aWiFiManager.isWifiEnabled);
118android判断当前wifi是否已经打开
WifiManageraWiFiManager=(WifiManager)
this.getSystemService(Context.WIFI_SERVICE);
if(aWiFiManager.getWifiState()==WifiManager.WIFI_STATE_ENABLED)
Log.i("TEST","itisopen");
119android判断SIM卡状态
TelephonyManagertelephonyManager=(TelephonyManager)getSystemService(TELEPHONY_SERVICE);
if(telephonyManager.getSimState()==telephonyManager.SIM_STATE_READY)
{
Log.i("TEST","正常");
}
elseif(telephonyManager.getSimState()==telephonyManager.SIM_STATE_ABSENT)
{
Log.i("TEST","无SIM卡");
}
120android取得SIM卡商名称
TelephonyManagertelephonyManager=(TelephonyManager)getSystemService(TELEPHONY_SERVICE);
Stringname=telephonyManager.getSimOperatorName();
121android为activity增加键盘事件
publicbooleanonKeyDown(intkeyCode,KeyEventevent)
{
switch(keyCode)
{
caseKeyEvent.KEYCODE_DPAD_UP:
Log.i("上",String.valueOf(keyCode));
break;
caseKeyEvent.KEYCODE_DPAD_DOWN:
Log.i("下",String.valueOf(keyCode));
break;
caseKeyEvent.KEYCODE_DPAD_LEFT:
Log.i("左",String.valueOf(keyCode));
break;
caseKeyEvent.KEYCODE_DPAD_RIGHT:
Log.i("右",String.valueOf(keyCode));
break;
caseKeyEvent.KEYCODE_DPAD_CENTER:
Log.i("中",String.valueOf(keyCode));
break;
}
returnsuper.onKeyDown(keyCode,event);
}
122android显示正在运行的程序
ActivityManagermActivityManager=(ActivityManager)
getSystemService(ACTIVITY_SERVICE);
ListmRunningTasks=
mActivityManager.getRunningTasks(100);
for(ActivityManager.RunningTaskInfotask:mRunningTasks)
{
StringtaskInfo=task.baseActivity.getClassName()
+"(ID="+amTask.id+")");
}
123android切换横竖屏
if(getRequestedOrientation()==
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
{
setRequestedOrientation
(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
elseif(getRequestedOrientation()==
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
{
setRequestedOrientation
(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
//PORTRAIT竖;LANDSCAPE横
124android判断网络类型是否为GPRS
TelephonyManagertelephonyManager=(TelephonyManager)getSystemService(TELEPHONY_SERVICE);
if(telephonyManager.getNetworkType()==telephonyManager.NETWORK_TYPE_GPRS)
125android发送http请求给网页
StringuriAPI="127.0.0.1:8080/test/index.jsp";
HttpPosthttpRequest=newHttpPost(uriAPI);
Listparams=newArrayList();
params.add(newBasicNameValuePair("username","test"));
try
{
httpRequest.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponsehttpResponse=newDefaultHttpClient().execute(httpRequest);
if(httpResponse.getStatusLine().getStatu
sCode()==200)
{
StringstrResult=EntityUtils.toString(httpResponse.getEntity());
}
}
catch(IOExceptione)
{
e.printStackTrace();
}
126android创建带图片的按钮
ImageButtonimageButton=newImageButton(this);
imageButton.setImageResource(R.drawable.test);
127android创建WebView
LinearLayoutlayout=newLinearLayout(this);
Buttonbutton=newButton(this);
layout.addView(button);
layout.removeView(button);
128androidlayout设置背景图片
LinearLayoutlayout=newLinearLayout(this);
layout.setBackgroundResource(R.drawable.hh);//图片放在drawable下了,名字是hh.jpg
129android设置铃声
Intentintent=newIntent(RingtoneManager.
ACTION_RINGTONE_PICKER);
130android设置网络请求方式/缓存/格式/编码
HttpURLConnectioncon=(HttpURLConnection)url.openConnection();
con.setUseCaches(false);//不使用缓存
con.setRequestMethod("POST");//请求方式是post
con.setRequestProperty("Content-Type","text/xml");//格式
con.setRequestProperty("Charset","UTF-8");//编码
131android判断是否为有效的网络url
URLUtil.isNetworkUrl(strPath)
132android创建垂直滚动条
ScrollViewscrollView=newScrollView(this);
133android创建水平滚动条
HorizontalScrollViewhorizontalScrollView=newHorizontalScrollView(this);
134android创建自动完成文本框
AutoCompleteTextViewautoCompleteTextView=newAutoCompleteTextView(this);
135android创建地图控件MapView
MapViewmapView=newMapView(this);
136android设置地图放大系数
mapController=mapView.getController();
mapController.setZoom(12);
137androidlayout增加和删除控件
LinearLayoutlayout=newLinearLayout(this);
Buttonbutton=newButton(this);
layout.addView(button);
layout.removeView(button);
138android刷新地图显示函数
//继承MapActivity并重写以下方法
publicvoidrefreshMapView()
{}
139android创建LocationManager
LocationManagerlocationManager=
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
140android设置webView的javascript有效
WebViewwebView=newWebView(this);
webView.setJavaScriptEnabled(true);
141android设置webView的保存密码有效
WebViewwebView=newWebView(this);
webSettings.setSavePassword(true);
142android获得PowerManager
PowerManagerpowerManager=(PowerManager)getSystemService(Context.POWER_SERVICE);
143android相机的预览
parameters.setPreviewSize(640,480);
//参数的其他设定参考“设置相机图片大小和像素等”
camera.setPreviewDisplay(surfaceHolder);
//这里是个SurfaceHolder对象
camera.startPreview();
camera.stopPreview();
144androidGoogleMap的移动
GeoPointpoint=newGeoPoint(xxx,yyy);
MapControllercontroller=mapView.getController();
controller.animateTo(point);
145android设置画笔粗细
Paintpaint=newPaint();
paint.setStrokeWidth(1);
146android打开相机
Camera.open();
147android设置相机图片大小和
像素等
Camera.Parametersparameters=camera.getParameters();
//设置相片格式为JPEG
parameters.setPictureFormat(PixelFormat.JPEG);
//设置图片分辨率大小
parameters.setPictureSize(640,480);
camera.setParameters(parameters);
148android将屏幕亮着
PowerManager.WakeLockwakeLock=mPowerManager.newWakeLock
(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,"BackLight");
149android暂停和恢复activity
protectedvoidonPause()
{
super.onPause();
}
protectedvoidonResume()
{
super.onResume();
}
150android保存和恢复canvas设置
canvas.save();//保存设置
//之间做一些变换,转移,拉伸等操作
canvas.restore();//恢复设置
151android地图搜索
Intentsearch=newIntent(Intent.ACTION_WEB_SEARCH);
search.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
search.putExtra(SearchManager.QUERY,"newyork");
startActivity(search);
152android设置播放器音量
mediaPlayer.setVolume(10,10);
153android播放器跳转到具体位置
mediaPlayer.seekTo(0);//0的单位是毫秒
154android获得手机号码和手机串号(IMEI)
TelephonyManagertelephonyManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
Stringimei=telephonyManager.getDeviceId();
Stringtel=telephonyManager.getLine1Number();
155android闹钟设置代码
//接受闹铃并显示提示
classAlarmReceiverextendsBroadcastReceiver{
publicvoidonReceive(Contextcontext,Intentintent){
Toast.makeText(context,"时间到",Toast.LENGTH_LONG).show();
}
}
//实例化自定义的BroadcastReceiver
AlarmReceiverreceiver=newAlarmReceiver();
IntentFilterfilter=newIntentFilter();
filter.addAction("android.intent.action.BOOT_COMPLETED");
//以编程方式注册BroadcastReceiver。xml配置方式见下
//一般在OnStart时注册,在OnStop时取消注册
registerReceiver(receiver,filter);
Intentintent=newIntent(this,AlarmReceiver.class);
PendingIntentpendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
AlarmManageralarmManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
//一次闹铃
alarmManager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+1000,pendingIntent);
//周期闹铃
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+1000,10000,pendingIntent);
//xml配置
156android接收系统启动完毕的broadcast的权限
157android多媒体录制
MediaRecorderrecorder=newMediaRecorder();
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//视频
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//音频
recor
der.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setOutputFile("/sdcard/media/1.3gp");
try{
recorder.prepare();
}catch(IllegalStateExceptione){e.printStackTrace();}
catch(IOExceptione){e.printStackTrace();}
recorder.start();
158android视频播放
VideoViewvideoView=newVideoView(this);
setContentView(videoView);
videoView.setVideoURI(Uri.parse("/sdcard/1.3gp"));
videoView.requestFocus();
videoView.start();
159android绘制文字
canvas.drawText(str,30,30,paint);
160android判断QWERTY键盘硬件是否滑出
Configurationconfig=getResources().getConfiguration();
if(config.hardKeyboardHidden==Configuration.KEYBOARDHIDDEN_NO)
{}
elseif(config.hardKeyboardHidden==Configuration.KEYBOARDHIDDEN_YES)
{}
161android清除手机cookie
CookieSyncManager.createInstance(getApplicationContext());
CookieManager.getInstance().removeAllCookie();
162android读写文件
读:
publicStringReadSettings(Contextcontext){
FileInputStreamfIn=null;
InputStreamReaderisr=null;
char[]inputBuffer=newchar[255];
Stringdata=null;
try{
fIn=openFileInput("settings.dat");
isr=newInputStreamReader(fIn);
isr.read(inputBuffer);
data=newString(inputBuffer);
Toast.makeText(context,"Settingsread",Toast.LENGTH_SHORT).show();
}
catch(Exceptione){
e.printStackTrace();
Toast.makeText(context,"Settingsnotread",Toast.LENGTH_SHORT).show();
}
finally{
try{
isr.close();
fIn.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
returndata;
}
&n, bsp; 写:
publicvoidWriteSettings(Contextcontext,Stringdata){
FileOutputStreamfOut=null;
OutputStreamWriterosw=null;
try{
fOut=openFileOutput("settings.dat",MODE_PRIVATE);
osw=newOutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context,"Settingssaved",Toast.LENGTH_SHORT).show();
}
catch(Exceptione){
e.printStackTrace();
Toast.makeText(context,"Settingsnotsaved",Toast.LENGTH_SHORT).show();
}
finally{
try{
osw.close();
fOut.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
163android判断不可卸载的程序
PackageManagermPm=getPackageManager();
ListinstalledAppList=
mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
********************************
for(ApplicationInfoappInfo:installedAppList){
booleanflag=false;
if((appInfo.flags&;ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)!=0){
//Updatedsystemapp
flag=true;
}elseif((appInfo.flags&;ApplicationInfo.FLAG_SYSTEM)==0){
//Non-systemapp
flag=true;
}
if(flag){
appList.add(appInfo);
}
}
164android判断是否飞行模式
booleanisEnabled=Settings.System.getInt(
context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON,0)==1;