常用代码合集一

推荐安卓开发神器(里面有各种UI特效和android代码库实例)

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

2 警报管理器 权限
代码 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

3 音频管理器 权限
代码 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
4 剪贴板管理器 权限
代码 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

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

6 输入法管理器 权限
代码 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_S)
7 键盘管理器 权限
代码 KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);

8 布局解压器管理器 权限
代码 LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

9 位置管理器 权限
代码 LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

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

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

12 搜索管理器 权限
代码 SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

13 传感器管理器 权限
代码 SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

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

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

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

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

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

19获取用户android手机 机器码和手机号
TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
       String imei = tm.getDeviceId();//获取机器码
         String tel = 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 获取屏幕宽高
DisplayMetrics dm = new DisplayMetrics();  
//获取窗口属性  
getWindowManager().getDefaultDisplay().getMetrics(dm);  
int screenWidth = dm.widthPixels;//320  
int screenHeight = dm.heightPixels;//480


23使用样式表
在 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>

24使用布局文件,切换 布局
建立两个布局文件
在事件里面写代码
@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);
     }
     });


=========================================================================
1.Intent用法
2010-04-27 12:09

// 短信列表界面
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setData(Uri.parse("content://mms-sms/"));
startActivity(intent);



// 通话记录界面
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android.cursor.dir/calls");
startActivity(intent);



Intent it = new Intent(Activity.Main.this, Activity2.class);
startActivity(it);
2. 向下一个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");
3. 向上一个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);
4. 回调上一个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);
}
}
}
显示网页
1. Uri uri = Uri.parse("http://google.com");
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);
显示地图
1. Uri uri = Uri.parse("geo:38.899533,-77.036476");
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);
4. //其他 geo URI 範例
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. Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);
4. //where startLat, startLng, endLat, endLng are a long with 6 decimals like: 50.123456
打 电话
1. //叫出拨号程序
2. Uri uri = Uri.parse("tel:0800000123");
3. Intent it = new Intent(Intent.ACTION_DIAL, uri);
4. startActivity(it);
1. //直接打电话出去
2. Uri uri = Uri.parse("tel:0800000123");
3. Intent it = new Intent(Intent.ACTION_CALL, uri);
4. startActivity(it);
5. //用這個,要在 AndroidManifest.xml 中,加上
6. //<uses-permission id="android.permission.CALL_PHONE" />
传 送SMS/MMS
1. //调用短信程序
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. it.putExtra("sms_body", "The SMS text");
4. it.setType("vnd.android-dir/mms-sms");
5. startActivity(it);
1. //传送消息
2. Uri uri = Uri.parse("smsto://0800000123");
3. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
4. it.putExtra("sms_body", "The SMS text");
5. startActivity(it);
1. //传送 MMS
2. Uri uri = Uri.parse("content://media/external/images/media/23");
3. Intent it = new Intent(Intent.ACTION_SEND);
4. it.putExtra("sms_body", "some text");
5. it.putExtra(Intent.EXTRA_STREAM, uri);
6. it.setType("image/png");
7. startActivity(it);
传 送 Email
1. Uri uri = Uri.parse("mailto:xxx@abc.com");
2. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
3. startActivity(it);
1. Intent it = new Intent(Intent.ACTION_SEND);
2. it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");
3. it.putExtra(Intent.EXTRA_TEXT, "The email body text");
4. it.setType("text/plain");
5. startActivity(Intent.createChooser(it, "Choose Email Client"));
1. Intent it=new Intent(Intent.ACTION_SEND);
2. String[] tos={"me@abc.com"};
3. String[] ccs={"you@abc.com"};
4. it.putExtra(Intent.EXTRA_EMAIL, tos);
5. it.putExtra(Intent.EXTRA_CC, ccs);
6. it.putExtra(Intent.EXTRA_TEXT, "The email body text");
7. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
8. it.setType("message/rfc822");
9. startActivity(Intent.createChooser(it, "Choose Email Client"));
1. //传送附件
2. Intent it = new Intent(Intent.ACTION_SEND);
3. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
4. it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");
5. sendIntent.setType("audio/mp3");
6. 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 相关
1. //寻找某个应用
2. Uri uri = Uri.parse("market://search?q=pname:pkg_name");
3. Intent it = new Intent(Intent.ACTION_VIEW, uri);
4. startActivity(it);
5. //where pkg_name is the full package path for an application
1. //显示某个应用的相关信息
2. Uri uri = Uri.parse("market://details?id=app_id");
3. Intent it = new Intent(Intent.ACTION_VIEW, uri);
4. startActivity(it);
5. //where app_id is the application ID, find the ID
6. //by clicking on your application on Market home
7. //page, and notice the ID from the address bar
Uninstall 应用程序
1. Uri uri = Uri.fromParts("package", strPackageName, null);
2. Intent it = new Intent(Intent.ACTION_DELETE, uri);
3. startActivity(it);
===============================================================================
1 调用浏览器 载入某网址
view plaincopy to clipboardprint?
Uri uri = Uri.parse("http://www.baidu.com");         
Intent it = new Intent(Intent.ACTION_VIEW, uri);         
startActivity(it); 
2 Broadcast接收系统广播的intent 监控应用程序包的安装 删除
view plaincopy to clipboardprint?
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
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/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>  
3 使用Toast输出一个字符串
view plaincopy to clipboardprint?
public void DisplayToast(String str) 
        { 
      Toast.makeText(this,str,Toast.LENGTH_SHORT).show(); 
        }  
4 把一个字符串写进文件
view plaincopy to clipboardprint?
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()); 
             } 
        } 
5 把文件内容读出到一个字符串
view plaincopy to clipboardprint?
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; 
        } 
6 调用Android installer 安装和卸载程序
view plaincopy to clipboardprint?
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);//正常卸载程序 
7 结束某个进程
view plaincopy to clipboardprint?
activityManager.restartPackage(packageName); 
8 设置默认来电铃声
view plaincopy to clipboardprint?
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); 
    ;} 
需要的权限
view plaincopy to clipboardprint?
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值