分享

Android常用代码合集

 edwinningb 2012-09-18

活动管理器 
权限 <uses-permission android:name="android.permission.GET_TASKS"/> 
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); 

警报管理器 
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 

音频管理器 
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 

剪贴板管理器
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 

连接管理器
权限 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVIT 

输入法管理器
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_S) 

键盘管理器
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); 

布局解压器管理器
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

位置管理器
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

通知管理器
代码 NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATIO) 

电源管理器
权限 <uses-permission android:name="android.permission.DEVICE_POWER"/> 
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); 

搜索管理器
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 

传感器管理器
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 

电话管理器
权限 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> 
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 

振动器
权限 <uses-permission android:name="android.permission.VIBRATE"/> 
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 

墙纸
权限 <uses-permission android:name="android.permission.SET_WALLPAPER"/> 
WallpaperService wallpaperService = (WallpaperService) getSystemService(Context.WALLPAPER_SERVICE); 

Wi-Fi管理器
权限 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 
代码 WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 

窗口管理器 
代码 WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); 

获取用户android手机 机器码和手机号 
TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); 
       String imei = tm.getDeviceId();//获取机器码 
         String tel = tm.getLine1Number();//获取手机号 

设置为横屏 
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 

无标题栏、全屏   
    //无标题栏   
    requestWindowFeature(Window.FEATURE_NO_TITLE);  //要在setcontentView之前哦 
    //全屏模式   
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
    WindowManager.LayoutParams.FLAG_FULLSCREEN); 

获取屏幕宽高 
DisplayMetrics dm = new DisplayMetrics();   
//获取窗口属性   
getWindowManager().getDefaultDisplay().getMetrics(dm);   
int screenWidth = dm.widthPixels;//320   
int screenHeight = dm.heightPixels;//480 

使用样式表 
在 res/values下面新建一个XML文件style.xml ,然后写下如下代码 
<?xml version="1.0" encoding="utf-8"?> 
<resources> 
<style name="style1"> 
<item name="android:textSize">18sp</item> 
<item name="android:textColor">#EC9237</item> 
</style> 
<style name="style2"><item name="android:textSize">10sp</item> 
<item name="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> 

使用布局文件,切换 布局 
建立两个布局文件 
在事件里面写代码 
@Override 
public void onClick(View v) { 
    helllo.this.setContentView(R.layout.layout2); 
    Button tempBtn=(Button)findViewById(R.id.btn_click1); 
    tempBtn.setOnClickListener(new Button.OnClickListener(){ 
    @Override 
    public void onClick(View v) { 
         helllo.this.setContentView(R.layout.xxx); 
    } 
}); 

=========================================================================
//Intent用法 
Intent it = new Intent(Activity.Main.this, Activity2.class); 
startActivity(it); 

//向下一个Activity传递数据(使用Bundle和Intent.putExtras) 
Intent it = new Intent(Activity.Main.this, Activity2.class); 
Bundle bundle=new Bundle(); 
bundle.putString("name", "This is from MainActivity!"); 
it.putExtras(bundle); // it.putExtra(“test”, "shuju”); 
startActivity(it); // startActivityForResult(it,REQUEST_CODE); 
对于数据 的获取可以采用: 
Bundle bundle=getIntent().getExtras(); 
String name=bundle.getString("name"); 

//向上一个Activity返回结果(使用setResult,针对startActivityForResult(it,REQUEST_CODE)启动 的Activity) 
Intent intent=getIntent(); 
Bundle bundle2=new Bundle(); 
bundle2.putString("name", "This is from ShowMsg!"); 
intent.putExtras(bundle2); 
setResult(RESULT_OK, intent); 

//回调上一个Activity的结果处理函数(onActivityResult) 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
// TODO Auto-generated method stub 
super.onActivityResult(requestCode, resultCode, data); 
if (requestCode==REQUEST_CODE){ 
if(resultCode==RESULT_CANCELED) 
setTitle("cancle"); 
else if (resultCode==RESULT_OK) { 
String temp=null; 
Bundle bundle=data.getExtras(); 
if(bundle!=null) temp=bundle.getString("name"); 
setTitle(temp); 


//显示网页 
Uri uri = Uri.parse("http://google.com"); 
Intent it = new Intent(Intent.ACTION_VIEW, uri); 
startActivity(it); 

//显示地图 
Uri uri = Uri.parse("geo:38.899533,-77.036476"); 
Intent it = new Intent(Intent.ACTION_VIEW, uri); 
startActivity(it); 
//其他 geo URI 範例 
//geo:latitude,longitude 
//geo:latitude,longitude?z=zoom 
//geo:0,0?q=my+street+address 
//geo:0,0?q=business+near+city 
//google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom 

//路径规划 
Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en"); 
Intent it = new Intent(Intent.ACTION_VIEW, uri); 
startActivity(it); 
//where startLat, startLng, endLat, endLng are a long with 6 decimals like: 50.123456 

//打 电话 
//叫出拨号程序 
Uri uri = Uri.parse("tel:0800000123"); 
Intent it = new Intent(Intent.ACTION_DIAL, uri); 
startActivity(it); 
//直接打电话出去 
Uri uri = Uri.parse("tel:0800000123"); 
Intent it = new Intent(Intent.ACTION_CALL, uri); 
startActivity(it); 
//用這個,要在 AndroidManifest.xml 中,加上//<uses-permission id="android.permission.CALL_PHONE" /> 

//传送SMS/MMS 
//调用短信程序 
Intent it = new Intent(Intent.ACTION_VIEW, uri); 
it.putExtra("sms_body", "The SMS text"); 
it.setType("vnd.android-dir/mms-sms"); 
startActivity(it); 

//传送消息 
Uri uri = Uri.parse("smsto://0800000123"); 
Intent it = new Intent(Intent.ACTION_SENDTO, uri); 
it.putExtra("sms_body", "The SMS text"); 
startActivity(it); 

//传送 MMS 
Uri uri = Uri.parse("content://media/external/images/media/23"); 
Intent it = new Intent(Intent.ACTION_SEND); 
it.putExtra("sms_body", "some text"); 
it.putExtra(Intent.EXTRA_STREAM, uri); 
it.setType("image/png"); 
startActivity(it); 

//传送Email 
Uri uri = Uri.parse("mailto:xxx@abc.com"); 
Intent it = new Intent(Intent.ACTION_SENDTO, uri); 
startActivity(it); 
Intent it = new Intent(Intent.ACTION_SEND); 
it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com"); 
it.putExtra(Intent.EXTRA_TEXT, "The email body text"); 
it.setType("text/plain"); 
startActivity(Intent.createChooser(it, "Choose Email Client")); 

Intent it=new Intent(Intent.ACTION_SEND); 
String[] tos={"me@abc.com"}; 
String[] ccs={"you@abc.com"}; 
it.putExtra(Intent.EXTRA_EMAIL, tos); 
it.putExtra(Intent.EXTRA_CC, ccs); 
it.putExtra(Intent.EXTRA_TEXT, "The email body text"); 
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text"); 
it.setType("message/rfc822"); 
startActivity(Intent.createChooser(it, "Choose Email Client")); 

//传送附件 
Intent it = new Intent(Intent.ACTION_SEND); 
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text"); 
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3"); 
sendIntent.setType("audio/mp3"); 
startActivity(Intent.createChooser(it, "Choose Email Client")); 

//播放多媒体
Uri uri = Uri.parse("file:///sdcard/song.mp3"); 
Intent it = new Intent(Intent.ACTION_VIEW, uri); 
it.setType("audio/mp3"); 
startActivity(it); 
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1"); 
Intent it = new Intent(Intent.ACTION_VIEW, uri); 
startActivity(it); 

//Market 相关 
//寻找某个应用 
Uri uri = Uri.parse("market://search?q=pname:pkg_name"); 
Intent it = new Intent(Intent.ACTION_VIEW, uri); 
startActivity(it); 
//where pkg_name is the full package path for an application 

//显示某个应用的相关信息 
Uri uri = Uri.parse("market://details?id=app_id"); 
Intent it = new Intent(Intent.ACTION_VIEW, uri); 
startActivity(it); 
//where app_id is the application ID, find the ID 
//by clicking on your application on Market home 
//page, and notice the ID from the address bar 

//Uninstall 应用程序 
Uri uri = Uri.fromParts("package", strPackageName, null); 
Intent it = new Intent(Intent.ACTION_DELETE, uri); 
startActivity(it); 
==============================================================================

//调用浏览器载入某网址
 Uri uri = Uri.parse("http://www.baidu.com");          
Intent it = new Intent(Intent.ACTION_VIEW, uri);          
startActivity(it);  

//Broadcast接收系统广播的intent 监控应用程序包的安装 删除
 public class getBroadcast extends BroadcastReceiver {  
        @Override  
        public void onReceive(Context context, Intent intent) {  
                  if(Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())){  
                    Toast.makeText(context, "有应用被添加", Toast.LENGTH_LONG).show();  
            }  
                else  if(Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())){  
                    Toast.makeText(context, "有应用被删除", Toast.LENGTH_LONG).show();  
            }  
                else  if(Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())){  
                    Toast.makeText(context, "有应用被替换", Toast.LENGTH_LONG).show();  
            }  
                else  if(Intent.ACTION_CAMERA_BUTTON.equals(intent.getAction())){  
                    Toast.makeText(context, "按键", Toast.LENGTH_LONG).show();  
            }  
        }  
}  
//需要声明的权限如下AndroidManifest.xml
 <?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas./apk/res/android"  
      package="zy.Broadcast"  
      android:versionCode="1"  
      android:versionName="1.0">  
    <application android:icon="@drawable/icon" android:label="@string/app_name">  
        <activity android:name=".Broadcast"  
                  android:label="@string/app_name">  
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" />  
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity>  
      <receiver android:name="getBroadcast" android:enabled="true" >  
         <intent-filter>  
             <action android:name="android.intent.action.PACKAGE_ADDED"></action>  
             <!-- <action android:name="android.intent.action.PACKAGE_CHANGED"></action>-->  
             <action android:name="android.intent.action.PACKAGE_REMOVED"></action>  
             <action android:name="android.intent.action.PACKAGE_REPLACED"></action>  
             <!-- <action android:name="android.intent.action.PACKAGE_RESTARTED"></action>-->  
           <!--    <action android:name="android.intent.action.PACKAGE_INSTALL"></action>-->  
               <action android:name="android.intent.action.CAMERA_BUTTON"></action>  
               <data android:scheme="package"></data>  
              </intent-filter>  
</receiver>  
    </application>  
    <uses-sdk android:minSdkVersion="3" />  
</manifest>   

//使用Toast输出一个字符串
 public void DisplayToast(String str)  
        {  
      Toast.makeText(this,str,Toast.LENGTH_SHORT).show();  
        }  

//把一个字符串写进文件
 public void writefile(String str,String path )  
        {  
            File file;  
            FileOutputStream out;  
             try {  
                 //创建文件  
                 file = new File(path);  
                 file.createNewFile();  
                 //打开文件file的OutputStream  
                 out = new FileOutputStream(file);  
                 String infoToWrite = str;  
                 //将字符串转换成byte数组写入文件  
                 out.write(infoToWrite.getBytes());  
                 //关闭文件file的OutputStream  
                 out.close();  
             } catch (IOException e) {  
                 //将出错信息打印到Logcat  
              DisplayToast(e.toString());  
             }  
        }  

//把文件内容读出到一个字符串
 public String getinfo(String path)  
        {  
            File file;  
            String str="";   
            FileInputStream in;  
         try{  
            //打开文件file的InputStream  
             file = new File(path);  
             in = new FileInputStream(file);  
             //将文件内容全部读入到byte数组  
             int length = (int)file.length();  
             byte[] temp = new byte[length];  
             in.read(temp, 0, length);  
             //将byte数组用UTF-8编码并存入display字符串中  
             str =  EncodingUtils.getString(temp,TEXT_ENCODING);  
             //关闭文件file的InputStream  
             in.close();  
         }  
         catch (IOException e) {  
          DisplayToast(e.toString());  
         }  
         return str;  
        }  

//调用Android installer 安装和卸载程序
Intent intent = new Intent(Intent.ACTION_VIEW);   
       intent.setDataAndType(Uri.fromFile(new File("/sdcard/WorldCupTimer.apk")), "application/vnd.android.package-archive");   
       startActivity(intent); //安装 程序  
       Uri packageURI = Uri.parse("package:zy.dnh");       
       Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);       
       startActivity(uninstallIntent);//正常卸载程序  

//结束某个进程
activityManager.restartPackage(packageName);  

//设置默认来电铃声
public void setMyRingtone()  
    {  
   File k = new File("/sdcard/Shall We Talk.mp3"); // 设置歌曲路径  
    ContentValues values = new ContentValues();  
    values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());  
    values.put(MediaStore.MediaColumns.TITLE, "Shall We Talk");  
    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);  
    // Insert it into the database  
    Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());  
    Uri newUri = this.getContentResolver().insert(uri, values);  
    RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);  
    ;}  
需要的权限
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多