`
407827531
  • 浏览: 1060951 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

常用代码合集一

阅读更多

推荐安卓开发神器(里面有各种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>

 

分享到:
评论

相关推荐

    PyTorch常用代码段合集1

    PyTorch常用代码段合集1

    网页制作常用代码

    网页制作常用代码包括 一:文字加粗 倾斜的代码 二:文字链接代码 三:在网站上放图片的代码 四:图片链接代码 五:换行代码 六:文字移动的代码 七:移动图片的代码 八:背景音乐的代码 九:在网站中插入一个...

    JAVA常用代码块

    JAVA常用代码块 JAVA常用代码块 JAVA常用代码块 JAVA常用代码块 JAVA常用代码块

    EXCEL VBA 常用代码实战大全

    书中所涉及的所有范例都以Excel 2007制作成示例文件,包含在《EXCEL VBA 常用代码实战大全》 示例文件文件夹中,每一章都有自己的文件夹。例如,要查看第3章的示例文件,可以查看《EXCEL VBA 常用代码实战大全》示例...

    Unity3D常用代码集合1

    Unity3D常用代码集合1

    100种网页常用广告代码集

    100种网页常用广告代码集 绝对经典 1:对联广告代码演示下载 2:对联广告带关闭代码演示下载 3:大幅广告自动翻滚代码演示下载 4:大幅图片广告代码演示下载 5:横向滚动图片代码演示下载 6:幻灯图片代码演示下载 7...

    PHP常用经典代码大全

    echo "共".($pages+1)."页: "; if($page&gt;0)echo "$PHP_SELF?page=0$queryString&gt;首页&lt;/a&gt;"; if($startpage&gt;0) echo " ... &lt;b&gt;&lt;a href=$PHP_SELF?page=".($page-$shownum*2)."$queryString&gt;?&lt;/a&gt;&lt;/b&gt;"; for($i=...

    matlab常用代码大全_常用代码

    这份代码写的非常好,欢迎大家一起来学习。

    模型算法大全(20+种常用算法模型+代码实现)

    模型算法大全(20+种常用算法模型+代码实现)模型算法大全(20+种常用算法模型+代码实现)模型算法大全(20+种常用算法模型+代码实现)模型算法大全(20+种常用算法模型+代码实现)模型算法大全(20+种常用算法模型+...

    dreamweaver 命令中文解释 and 常用代码

    dreamweaver命令的中文解释 和 常用的一些代码 一看就明白

    vb常用代码大全

    这些代码都是本人经过多年在网上收集的,每一条都是通过重复实验成功过后才收集,90%的代码都有注释,方便新手,在此感谢网上的各位无名网友的代码分享.谢谢

    stata代码命令全集:跟检验do文件、stata常用命令、代码大合集、面板熵值法

    一、常用模型代码整理 1、数据来源: 2、时间跨度:无 3、区域范围:无 4、指标说明: 包含如下模型代码: l OLS模型 l Heckman两阶段模型 l PSM+DID模型 l 固定效应模型(xtreg命令的使用) l 中介效应模型...

    Web开发中的30种常用代码

    Web开发中的30种常用代码 1. 打开新的窗口并传送参数:  传送参数: response.write("<script>window.open(’*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"’)</script>")  接收参数: string a...

    各类常用代码

    C# 常用代码积累,是一个十分好用的文档,请下载查看

    C# 常用类代码(封装)

    7.js.cs 常用js代码 8.文件操作类 9.数据检查类 10.util.cs常用字符串操作 11.CacheManager.cs 操作缓存的类 12.CookieManager.cs Cookie管理类 13.DataToExcel.cs 导出excel 14.EnumConvert 枚举转换为详细说明的类...

    NC开发常用代码.txt

    NC开发常用代码,调用接口,弹出询问窗口,判断模板状态,打开另一个节点,可以自行选择弹窗的样式,当前选中树的数据,前界面显示的子表名称.......

    这是一个方舟常用的代码.txt

    这是一个方舟常用的代码

    Asp.net常用代码

    Asp.net常用代码(一) Asp.net常用代码(二) Asp.net常用代码(三) Asp.net常用代码(四) Asp.net常用代码(五) Asp.net常用代码(六)

    代码合集.rar

    2012-06-11 14:34 173,925,575 代码合集.rar 2012-06-11 12:54 3,755,221 图像处理基础及其实现.rar 2012-06-11 12:56 46,896,300 开源搜索引擎(SourceCode).rar 2012-06-11 12:50 1,627,503 数据采集器.rar 2012-06...

    c#常用代码(每日更新)

    欢迎使用该软件 目的: 1.提高代码效率 2.格式化,方便阅读 3.偷懒专用

Global site tag (gtag.js) - Google Analytics