android 常用api示例


获取当前日期时间,并格式化:
调用long System.currentTimeMillis()方法,可以取得从1970年1月1日开始经过的毫秒数

SimpleDateFormat dateFormat = new SimpleDateFormat("EE yyyy年MM月dd日  HH:mm:ss");
String strDate = dateFormat.format(new Date());
textvDate.setText(strDate);
打印行号与文件名
阅JDK,我们找到StackTraceElement这个类。这个类可以从Throwable取得,另外也可以从Thread类取得,通过这些我写如下的一个打印行号的测试程序:
查看源代码
打印帮助
01      public class LineNo {
02        public static int getLineNumber() {
03        return Thread.currentThread().getStackTrace()[2].getLineNumber();
04        }
05       
06        public static String getFileName() {
07        return Thread.currentThread().getStackTrace()[2].getFileName();
08        }
09        public static void main(String args[]) {
10        System.out.println("["+getFileName()+":"+ getLineNumber()+"]"+"Hello World!");
11        }
12      }

留下一个问题,上面程序中的magic数字 2 代表什么含义呢?

0是thread.getCurrentThread()
1是getLineNumber()
2才是调用getLineNumber的类


android系统管理联系人的URI如下
ContactsContract.Contacts.CONTENT_URI 管理联系人的Uri
ContactsContract.CommonDataKinds.Phone.CONTENT_URI 管理联系人的电话的Uri
ContactsContract.CommonDataKinds.Email.CONTENT_URI 管理联系人的Email的Uri
(注:Contacts有两个表,分别是rawContact和Data,rawContact记录了用户的id和name,其中id栏名称为:ContactsContract.Contacts._ID, name名称栏为ContactContract.Contracts.DISPLAY_NAME,电话信息表的外键id为ContactsContract.CommonDataKinds.Phone.CONTACT_ID,电话号码栏名称为:
ContactsContract.CommonDataKinds.Phone.NUMBER.

data表中Email地址栏名称为:
ContactsContract.CommonDataKinds.Email.DATA
其外键栏为:ContactsContract.CommonDataKinds.Email.CONTACT_ID)

android为多媒体提供的ContentProvider的Uri如下:
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI  存储在sd卡上的音频文件
MediaStore.Audio.Media.INTERNAL_CONTENT_URI  存储在手机内部存储器上的音频文件

MediaStore.Audio.Images.EXTERNAL_CONTENT_URI SD卡上的图片文件内容
MediaStore.Audio.Images.INTERNAL_CONTENT_URI 手机内部存储器上的图片
MediaStore.Audio.Video.EXTERNAL_CONTENT_URI SD卡上的视频
MediaStore.Audio.Video.INTERNAL_CONTENT_URI  手机内部存储器上的视频
(注:图片的显示名栏:Media.DISPLAY_NAME,图片的详细描述栏为:Media.DESCRIPTION  图片的保存位置:Media.DATA
短信URI: Content://sms
发送箱中的短信URI: Content://sms/outbox
(相应栏名称address, subject(标题), time)


InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                              //隐藏软键盘
//                              imm.hideSoftInputFromWindow(tv.getWindowToken(), 0);
                              //显示软键盘
//                              imm.showSoftInputFromInputMe thod(tv.getWindowToken(), 0);
tv是你控件editText

android 获取当前程序路径(当前目录,当前文件路径)
      分类: android
//  获取当前程序路径
      getApplicationContext().getFilesDir().getAbsolutePath();

//  获取该程序的安装包路径
      String path=getApplicationContext().getPackageResourcePath();

//  获取程序默认数据库路径
      getApplicationContext().getDatabasePath(s).getAbsolutePath();
     
外部存储文件创建:
File extDir = Environment.getExternalStorageDirect ory();
String filename = "downloadedMusic.mp3";
File fullFilename = new File(extDir, filename);
fullFilename.createNewFile();
fullFilename.setWritable(Boolean.TRUE);
songtaste.stDownloadFromUrl(strSongUrl, fullFilename);

字节流与字符串转换:
Byte[] 字节流转换为String对象:
  fin=mContext.openFileInput("helloworld.txt");
int size=fin.available();
byte[]buffer=new byte[size];
while(fin.read(buffer)>0)
{
    mResult+=new String(buffer,"utf-8");
}
字符串转换为字符流:
String content="dfsfs";
fout.write(content.getBytes("utf-8"));

SQLiteDatabase.rawQuery 用string替换占位符?时,直接作为字符串导入,因此在like ‘pattern’ 这样的语句中,可以写成 "... like ?",new String[]{"pattern"}
String queryString = cities[position].code + "__";//(正确语句, 不需在字符串中包含"'")//String queryString = "'"+cities[position].code + "__"+"'";(错误语句)
cursor = mydb.rawQuery("select code, name, fullcode from city_code where code like ?", new String[]{queryString});//


Handler 使用 //常用于子线程与主线程通信,如:子线程要求刷新Ui组件,可以此通知主线程

Handler handler = null;

主线程(ui线程)代码:
handler = new Handler()
            {
                  @Override
                  public void handleMessage(Message msg) {
                        // TODO Auto-generated method stub
                        System.out.println("what--->"+ msg.what);
                        switch(msg.what)
                        {
                        case 0x1010:
                              byte[] imageData = msg.getData().getByteArray("buffer");
                              System.out.println("imageData.length-------->"+imageData.length);
                              Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                              image[0].setImageBitmap(bitmap);
                              image[0].setVisibility(View.VISIBLE);
                              break;
                        case 0x1111:
                              String fullName1 = msg.getData().getString("fullname");
                              System.out.println("fullName1"+fullName1);
                              Bitmap bitmapFile1 = BitmapFactory.decodeFile(fullName1);
                              image[1].setImageBitmap(bitmapFile1);
                              image[1].setVisibility(View.VISIBLE);
                              break;
                        case 0x1000:
                              System.out.println("time update");
                              SimpleDateFormat dateFormat = new SimpleDateFormat("EE yyyy年MM月dd日  HH:mm:ss");
                              String strDate = dateFormat.format(new Date());
                              textvDate.setText(strDate);
                              break;
                        default:
                              super.handleMessage(msg);
                        }
                  }
            };
           

      Message msg = new Message();
      msg.what = 0x1110 + i;
      Bundle bundle1 = new Bundle();
      String fullName = String fullFileName = String fullFileName = getApplication().getFilesDir().getPath()+"/icon/"+ "filename";//getApplication().getFilesDir().getPath()+"/icon/"+getFileName(path);;
      bundle1.putString("fullname", fullName);
      msg.setData(bundle1);
      handler.sendMessage(msg);
     
子线程代码2:
定时器使用:
Timer timer= new Timer();
TimerTask timerTask = new TimerTask() {
     
      @Override
      public void run() {
            // TODO Auto-generated method stub
            System.out.println("time update message");
            Message msg = new Message();
            msg.what = 0x1000;
            handler.sendMessage(msg);
      }
};
timer.schedule(timerTask, 0, 1000);//延迟0毫秒后每隔1000毫秒启动timetask任务
timerTask.cancel() 可停止任务
timerTask.run()可开始任务
timerTask.scheduledExecutionTime()//任务运行时间
     
     
数据库操作:
//打开数据库或者创建再打开数据库
String databasePath = getApplication().getFilesDir().getPath()+ "/" + DATABASE_NAME;
SQLiteDatabase      mydb = SQLiteDatabase.openOrCreateDatabase(databasePath, null);
           
      //数据表是否存在
      try
      {
            cursor = mydb.rawQuery("select * from city_code", null);
      }
      catch (Exception e)
      {
            //数据表不存在,创建数据表
           
            mydb.execSQL("create table city_code(_id integer primary key autoincrement, code varchar(6), name varchar(14), fullcode varchar(9))");
           
      }
           
           
      System.out.println("time for parse xml--->"+(System.currentTimeMillis() - startTime));
      String sql = "insert into city_code(code,name,fullcode) values(?,?,?)";
      SQLiteStatement stat = mydb.compileStatement(sql);
      mydb.beginTransaction();
      for(int i = 0; i < provices.length; i++)
      {
              stat.bindString(1, provices[i].code);
              stat.bindString(2, provices[i].name);
              stat.bindString(3, "0");
              stat.executeInsert();
      }
     
      mydb.setTransactionSuccessful ();
      mydb.endTransaction();
     
      //查询数据库,并读取查询结果
      //查询省级行政单位列表
            cursor = mydb.rawQuery("select code, name from city_code where code like '__'", null);
//            System.out.println("row counts--->"+cursor.getCount());
            provices = new Province[cursor.getCount()];
            int iPos = 0;
            while(cursor.moveToNext())
            {
                  provices[iPos] = new Province();
                  provices[iPos].code = cursor.getString(0);//第一个字段(index==0) code ,根据查询语句确定索引号
                  provices[iPos].name = cursor.getString(1);//第二个字段(index==1) name
                  iPos++;
            }
           
      //关闭数据库
      mydb.close();
           
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值