android 开发中中,经常用到的代码(转载)

android开发中中,经常用到的代码(转载)

2012-04-1912:13by宁录,56阅读,0评论,收藏,编辑

1活动管理器

权限<uses-permissionandroid:name="android.permission.GET_TASKS"/>

代码ActivityManageractivityManager=(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);

2警报管理器权限

代码AlarmManageralarmManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);

3音频管理器权限

代码AudioManageraudioManager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);

4剪贴板管理器权限

代码ClipboardManagerclipboardManager=(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);

5连接管理器权限<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>

代码ConnectivityManagerconnectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVIT

6输入法管理器权限

代码InputMethodManagerinputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_S)

7键盘管理器权限

代码KeyguardManagerkeyguardManager=(KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);

8布局解压器管理器权限

代码LayoutInflaterlayoutInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

9位置管理器权限

代码LocationManagerlocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);

10通知管理器权限

代码NotificationManagernotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATIO)

11电源管理器权限<uses-permissionandroid:name="android.permission.DEVICE_POWER"/>

代码PowerManagerpowerManager=(PowerManager)getSystemService(Context.POWER_SERVICE);

12搜索管理器权限

代码SearchManagersearchManager=(SearchManager)getSystemService(Context.SEARCH_SERVICE);

13传感器管理器权限

代码SensorManagersensorManager=(SensorManager)getSystemService(Context.SENSOR_SERVICE);

14电话管理器权限<uses-permissionandroid:name="android.permission.READ_PHONE_STATE"/>

代码TelephonyManagertelephonyManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

15振动器权限<uses-permissionandroid:name="android.permission.VIBRATE"/>

代码Vibratorvibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

16墙纸权限<uses-permissionandroid:name="android.permission.SET_WALLPAPER"/>

代码WallpaperServicewallpaperService=(WallpaperService)getSystemService(Context.WALLPAPER_SERVICE);

17Wi-Fi管理器权限<uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/>

代码WifiManagerwifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);

18窗口管理器权限

代码WindowManagerwindowManager=(WindowManager)getSystemService(Context.WINDOW_SERVICE);

19获取用户android手机机器码和手机号

TelephonyManagertm=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

Stringimei=tm.getDeviceId();//获取机器码

Stringtel=tm.getLine1Number();//获取手机号

20设置为横屏

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

21无标题栏、全屏

//无标题栏

requestWindowFeature(Window.FEATURE_NO_TITLE);//要在setcontentView之前哦

//全屏模式

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

WindowManager.LayoutParams.FLAG_FULLSCREEN);

22获取屏幕宽高

DisplayMetricsdm=newDisplayMetrics();

//获取窗口属性

getWindowManager().getDefaultDisplay().getMetrics(dm);

intscreenWidth=dm.widthPixels;//320

intscreenHeight=dm.heightPixels;//480

23使用样式表

在res/values下面新建一个XML文件style.xml,然后写下如下代码

<?xmlversion="1.0"encoding="utf-8"?>

<resources>

<stylename="style1">

<itemname="android:textSize">18sp</item>

<itemname="android:textColor">#EC9237</item>

</style>

<stylename="style2"><itemname="android:textSize">10sp</item>

<itemname="android:textColor">#FF9237</item>

</style>

</resources>

使用:

<TextView

style="@style/style1"//调用style

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="样式1"

android:id="@+id/Tv1">

</TextView>

24使用布局文件,切换布局

建立两个布局文件

在事件里面写代码

@Override

publicvoidonClick(Viewv){

helllo.this.setContentView(R.layout.layout2);

ButtontempBtn=(Button)findViewById(R.id.btn_click1);

tempBtn.setOnClickListener(newButton.OnClickListener(){

@Override

publicvoidonClick(Viewv){

helllo.this.setContentView(R.layout.xxx);

}

});

=========================================================================

1.Intent用法

2010-04-2712:09

Intentit=newIntent(Activity.Main.this,Activity2.class);

startActivity(it);

2.向下一个Activity传递数据(使用Bundle和Intent.putExtras)

Intentit=newIntent(Activity.Main.this,Activity2.class);

Bundlebundle=newBundle();

bundle.putString("name","ThisisfromMainActivity!");

it.putExtras(bundle);//it.putExtra(“test”,"shuju”);

startActivity(it);//startActivityForResult(it,REQUEST_CODE);

对于数据的获取可以采用:

Bundlebundle=getIntent().getExtras();

Stringname=bundle.getString("name");

3.向上一个Activity返回结果(使用setResult,针对startActivityForResult(it,REQUEST_CODE)启动的Activity)

Intentintent=getIntent();

Bundlebundle2=newBundle();

bundle2.putString("name","ThisisfromShowMsg!");

intent.putExtras(bundle2);

setResult(RESULT_OK,intent);

4.回调上一个Activity的结果处理函数(onActivityResult)

@Override

protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){

//TODOAuto-generatedmethodstub

super.onActivityResult(requestCode,resultCode,data);

if(requestCode==REQUEST_CODE){

if(resultCode==RESULT_CANCELED)

setTitle("cancle");

elseif(resultCode==RESULT_OK){

Stringtemp=null;

Bundlebundle=data.getExtras();

if(bundle!=null)temp=bundle.getString("name");

setTitle(temp);

}

}

}

显示网页

1.Uriuri=Uri.parse("http://google.com");

2.Intentit=newIntent(Intent.ACTION_VIEW,uri);

3.startActivity(it);

显示地图

1.Uriuri=Uri.parse("geo:38.899533,-77.036476");

2.Intentit=newIntent(Intent.ACTION_VIEW,uri);

3.startActivity(it);

4.//其他geoURI範例

5.//geo:latitude,longitude

6.//geo:latitude,longitude?z=zoom

7.//geo:0,0?q=my+street+address

8.//geo:0,0?q=business+near+city

9.//google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom

路径规划

1.Uriuri=Uri.parse("http://maps.google.com/maps?f=d&saddr=startLatstartLng&daddr=endLatendLng&hl=en");

2.Intentit=newIntent(Intent.ACTION_VIEW,uri);

3.startActivity(it);

4.//wherestartLat,startLng,endLat,endLngarealongwith6decimalslike:50.123456

打电话

1.//叫出拨号程序

2.Uriuri=Uri.parse("tel:0800000123");

3.Intentit=newIntent(Intent.ACTION_DIAL,uri);

4.startActivity(it);

1.//直接打电话出去

2.Uriuri=Uri.parse("tel:0800000123");

3.Intentit=newIntent(Intent.ACTION_CALL,uri);

4.startActivity(it);

5.//用這個,要在AndroidManifest.xml中,加上

6.//<uses-permissionid="android.permission.CALL_PHONE"/>

传送SMS/MMS

1.//调用短信程序

2.Intentit=newIntent(Intent.ACTION_VIEW,uri);

3.it.putExtra("sms_body","TheSMStext");

4.it.setType("vnd.android-dir/mms-sms");

5.startActivity(it);

1.//传送消息

2.Uriuri=Uri.parse("smsto://0800000123");

3.Intentit=newIntent(Intent.ACTION_SENDTO,uri);

4.it.putExtra("sms_body","TheSMStext");

5.startActivity(it);

1.//传送MMS

2.Uriuri=Uri.parse("content://media/external/images/media/23");

3.Intentit=newIntent(Intent.ACTION_SEND);

4.it.putExtra("sms_body","sometext");

5.it.putExtra(Intent.EXTRA_STREAM,uri);

6.it.setType("image/png");

7.startActivity(it);

传送Email

1.Uriuri=Uri.parse("mailto:[email protected]");

2.Intentit=newIntent(Intent.ACTION_SENDTO,uri);

3.startActivity(it);

1.Intentit=newIntent(Intent.ACTION_SEND);

2.it.putExtra(Intent.EXTRA_EMAIL,"[email protected]");

3.it.putExtra(Intent.EXTRA_TEXT,"Theemailbodytext");

4.it.setType("text/plain");

5.startActivity(Intent.createChooser(it,"ChooseEmailClient"));

1.Intentit=newIntent(Intent.ACTION_SEND);

2.String[]tos={"[email protected]"};

3.String[]ccs={"[email protected]"};

4.it.putExtra(Intent.EXTRA_EMAIL,tos);

5.it.putExtra(Intent.EXTRA_CC,ccs);

6.it.putExtra(Intent.EXTRA_TEXT,"Theemailbodytext");

7.it.putExtra(Intent.EXTRA_SUBJECT,"Theemailsubjecttext");

8.it.setType("message/rfc822");

9.startActivity(Intent.createChooser(it,"ChooseEmailClient"));

1.//传送附件

2.Intentit=newIntent(Intent.ACTION_SEND);

3.it.putExtra(Intent.EXTRA_SUBJECT,"Theemailsubjecttext");

4.it.putExtra(Intent.EXTRA_STREAM,"file:///sdcard/mysong.mp3");

5.sendIntent.setType("audio/mp3");

6.startActivity(Intent.createChooser(it,"ChooseEmailClient"));

播放多媒体

Uriuri=Uri.parse("file:///sdcard/song.mp3");

Intentit=newIntent(Intent.ACTION_VIEW,uri);

it.setType("audio/mp3");

startActivity(it);

Uriuri=Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"1");

Intentit=newIntent(Intent.ACTION_VIEW,uri);

startActivity(it);

Market相关

1.//寻找某个应用

2.Uriuri=Uri.parse("market://search?q=pname:pkg_name");

3.Intentit=newIntent(Intent.ACTION_VIEW,uri);

4.startActivity(it);

5.//wherepkg_nameisthefullpackagepathforanapplication

1.//显示某个应用的相关信息

2.Uriuri=Uri.parse("market://details?id=app_id");

3.Intentit=newIntent(Intent.ACTION_VIEW,uri);

4.startActivity(it);

5.//whereapp_idistheapplicationID,findtheID

6.//byclickingonyourapplicationonMarkethome

7.//page,andnoticetheIDfromtheaddressbar

Uninstall应用程序

1.Uriuri=Uri.fromParts("package",strPackageName,null);

2.Intentit=newIntent(Intent.ACTION_DELETE,uri);

3.startActivity(it);

===============================================================================

1调用浏览器载入某网址

viewplaincopytoclipboardprint?

Uriuri=Uri.parse("http://www.baidu.com");

Intentit=newIntent(Intent.ACTION_VIEW,uri);

startActivity(it);

2Broadcast接收系统广播的intent监控应用程序包的安装删除

viewplaincopytoclipboardprint?

publicclassgetBroadcastextendsBroadcastReceiver{

@Override

publicvoidonReceive(Contextcontext,Intentintent){

if(Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())){

Toast.makeText(context,"有应用被添加",Toast.LENGTH_LONG).show();

}

elseif(Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())){

Toast.makeText(context,"有应用被删除",Toast.LENGTH_LONG).show();

}

elseif(Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())){

Toast.makeText(context,"有应用被替换",Toast.LENGTH_LONG).show();

}

elseif(Intent.ACTION_CAMERA_BUTTON.equals(intent.getAction())){

Toast.makeText(context,"按键",Toast.LENGTH_LONG).show();

}

}

}

需要声明的权限如下AndroidManifest.xml

viewplaincopytoclipboardprint?

<?xmlversion="1.0"encoding="utf-8"?>

<manifestxmlns:android="http://schemas.android.com/apk/res/android"

package="zy.Broadcast"

android:versionCode="1"

android:versionname="1.0">

<applicationandroid:icon="@drawable/icon"android:label="@string/app_name">

<activityandroid:name=".Broadcast"

android:label="@string/app_name">

<intent-filter>

<actionandroid:name="android.intent.action.MAIN"/>

<categoryandroid:name="android.intent.category.LAUNCHER"/>

</intent-filter>

</activity>

<receiverandroid:name="getBroadcast"android:enabled="true">

<intent-filter>

<actionandroid:name="android.intent.action.PACKAGE_ADDED"></action>

<!--<actionandroid:name="android.intent.action.PACKAGE_CHANGED"></action>-->

<actionandroid:name="android.intent.action.PACKAGE_REMOVED"></action>

<actionandroid:name="android.intent.action.PACKAGE_REPLACED"></action>

<!--<actionandroid:name="android.intent.action.PACKAGE_RESTARTED"></action>-->

<!--<actionandroid:name="android.intent.action.PACKAGE_INSTALL"></action>-->

<actionandroid:name="android.intent.action.CAMERA_BUTTON"></action>

<dataandroid:scheme="package"></data>

</intent-filter>

</receiver>

</application>

<uses-sdkandroid:minSdkVersion="3"/>

</manifest>

3使用Toast输出一个字符串

viewplaincopytoclipboardprint?

publicvoidDisplayToast(Stringstr)

{

Toast.makeText(this,str,Toast.LENGTH_SHORT).show();

}

4把一个字符串写进文件

viewplaincopytoclipboardprint?

publicvoidwritefile(Stringstr,Stringpath)

{

Filefile;

FileOutputStreamout;

try{

//创建文件

file=newFile(path);

file.createNewFile();

//打开文件file的OutputStream

out=newFileOutputStream(file);

StringinfoToWrite=str;

//将字符串转换成byte数组写入文件

out.write(infoToWrite.getBytes());

//关闭文件file的OutputStream

out.close();

}catch(IOExceptione){

//将出错信息打印到Logcat

DisplayToast(e.toString());

}

}

5把文件内容读出到一个字符串

viewplaincopytoclipboardprint?

publicStringgetinfo(Stringpath)

{

Filefile;

Stringstr="";

FileInputStreamin;

try{

//打开文件file的InputStream

file=newFile(path);

in=newFileInputStream(file);

//将文件内容全部读入到byte数组

intlength=(int)file.length();

byte[]temp=newbyte[length];

in.read(temp,0,length);

//将byte数组用UTF-8编码并存入display字符串中

str=EncodingUtils.getString(temp,TEXT_ENCODING);

//关闭文件file的InputStream

in.close();

}

catch(IOExceptione){

DisplayToast(e.toString());

}

returnstr;

}

6调用Androidinstaller安装和卸载程序

viewplaincopytoclipboardprint?

Intentintent=newIntent(Intent.ACTION_VIEW);

intent.setDataAndType(Uri.fromFile(newFile("/sdcard/WorldCupTimer.apk")),"application/vnd.android.package-archive");

startActivity(intent);//安装程序

UripackageURI=Uri.parse("package:zy.dnh");

IntentuninstallIntent=newIntent(Intent.ACTION_DELETE,packageURI);

startActivity(uninstallIntent);//正常卸载程序

7结束某个进程

viewplaincopytoclipboardprint?

activityManager.restartPackage(packageName);

8设置默认来电铃声

viewplaincopytoclipboardprint?

publicvoidsetMyRingtone()

{

Filek=newFile("/sdcard/ShallWeTalk.mp3");//设置歌曲路径

ContentValuesvalues=newContentValues();

values.put(MediaStore.MediaColumns.DATA,k.getAbsolutePath());

values.put(MediaStore.MediaColumns.TITLE,"ShallWeTalk");

values.put(MediaStore.MediaColumns.SIZE,8474325);

values.put(MediaStore.MediaColumns.MIME_TYPE,"audio/mp3");

values.put(MediaStore.Audio.Media.ARTIST,"Madonna");

values.put(MediaStore.Audio.Media.DURATION,230);

values.put(MediaStore.Audio.Media.IS_RINGTONE,true);

values.put(MediaStore.Audio.Media.IS_NOTIFICATION,false);

values.put(MediaStore.Audio.Media.IS_ALARM,false);

values.put(MediaStore.Audio.Media.IS_MUSIC,false);

//Insertitintothedatabase

Uriuri=MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());

UrinewUri=this.getContentResolver().insert(uri,values);

RingtoneManager.setActualDefaultRingtoneUri(this,RingtoneManager.TYPE_RINGTONE,newUri);

;}

需要的权限

viewplaincopytoclipboardprint?

<uses-permissionandroid:name="android.permission.WRITE_SETTINGS"></uses-permission>

相关推荐