(一) Android 开发基础

1 Android平台的特性

1)  应用程序框架支持组建的重用和替换,包括打电话应用程序、文件管理器等。

2)  Dalvik虚拟机专门为移动设备做了优化,Dalvik虚拟机是基于寄存器的,相对于Java虚拟机速度要快很多

3)  内部集成浏览器基于开源的WebKit引擎

4)  优化的图形库包括2D和3D图形库

5) SQLite用作结构化的数据存储 等

2 Android的体系结构

分为4层,由上而下依次是应用程序、应用程序框架、核心类库和Linux内核。

3 Android组件类

1)  Activity:一个Activity通常就是一个单独的屏幕,通过调用startActivity()方法可以从一个屏幕导航到另一个屏幕,打开Activity的条件被封装在Intent中。当一个新的屏幕打开后,前一个屏幕将会暂停,并保存在历史堆栈中。默认情况下,Android将会保留从主屏幕到每一个应用的运行屏幕。

2)  Service:一种长生命周期的、没有用户界面的程序,通过嗲用Context.startService()来启动一个Service,还可以通过使用Context.bindService()方法连接到一个Service上,连接之后,我们还可以通过Service提供的接口与它进行通信。

3)  Broadcast Receiver:为了实现系统广播而提供的一种组件。

4)  ContentProvider:用来实现不同组件之间数据的共享

5)  View:是Android中图形用户界面的基类。Android的图形界面展示可以分为三层:底层是Activity,上面是Window,再上面是Views.View又可以分为View(按钮、单选框、多选课等)和ViewGroup(布局控件)。

6)  Intent:不同组件之间相互导航的纽带,封装了不同组件之间导航查找的条件

4 Android开发

1)安装环境的配置:下载Android SDK、下载安装JDK、下载Eclipse、下载安装ADT

2)Android SDK下载包说明

add-ons   空目录保存Google插件工具

platforms  空目录保存不同版本SDK

tools  SDK工具

SDK Setup.exe    在线安装SDK的可执行文件

SDK Readme.txt   说明文件

3) adb常用命令

adb push  本地路径  远程路径   , 例 D:\>adb push d:\test.apk   /sdcard/     将D盘根目录下的text.txt文件复制到设备的sdcard里面远程路径本地路径

adb pull     远程路径  本地路径 , 例 D:\>adb pull  /sdcard/test.apk  d:\    将sdcard里的text.txt复制到D盘根目录下

adb install  test.apk  安装程序

adb shell  允许使用系统中的各种命令,进入shell命令行之后,这里我们可以使用ls 来显示当前目录下的文件内容,可以使用cd来改变当前路径,也可以使用exit退出shell

4) 其他工具简介

Dalvik Debug Monitor Service(DDMS),即Dalvik调试监控服务,是一个可视化的调试监控工具。在DOS命令窗口中输入ddms就会弹出界面。主要是对系统运行后台日志的监控,还有系统线程、虚拟机状态的监控,另外还可以模拟发送短信、拨打电话和发送GDP位置信息

5 Android 应用程序结构

src    源文件文件夹(主要是完成java代码的编写)

gen  保存自动生成的R资源类文件夹;系统自动生成的源代码目录

R.java  工程自动生成的资源索引类,这个是系统自动生成的文件,非常的重要。这个R.java类默认有attr、drawable、layout、string 4个静态内部类,每个类对应一种资源。例如我们在工程中增加一幅图片,那么工程就会在此类的drawable内部类中增加一条数据,如果删除此图片,工程会自动删除此条数据。

assets   资源文件夹

res   资源文件夹(存图片、布局文件盒字符串、菜单等文件)

drawable  保存图片等资源文件夹,默认PNG格式

layout   存放界面布局文件,以.xml结束

layout->main.xml   界面布局文件

values  简单配置文件夹,存放很重要的strings.xml,除此之外还可以定义arrays.xml(用来定义数值)、color.xml(用来定义颜色和颜色字符串数值)、dimens.xml(用来定义尺寸数值)、styles.xml(用来定义样式)

values->strings.xml   字符串配置文件,存放的自定义的字符串和数值

AndroidManifest.xml  Android配置清单文件

是每个android程序必须的文件,它位于整个项目的根目录,描述了package中暴露的组件(activities,services等等),他们各自的实现类,各种能被处理的数据和启动位置,除了能声明程序中的Activities,ContentProviders,Services和Intent Receivers,还能指定permissions和instrumentation(安全控制和测试)

default.xml  属性文件

project.properties  工程属性文件配置

bin  输出文件夹,如生成的APK文件

-----------------------------------------------------------------------------------------------------------------------------------

文 件             取值方式

string.xml          getResource().getString(resourceId) 或者 getResource().getText(resourceId)

arrays.xml         getResource().getStringArray(resourceId)

color.xml           getResource().getDarwable(resourceId) 或者 getResource().getColor(resourceId)

dimens.xml        getResource().getDimension(resourceId)

styles.xml          不需要取值

------------------------------------------------------------------------------------------------------------------------------------

Activity生命周期的7个方法和3个阶段
7个方法如下:
void onCreate(Bundle savedInstanceState) 
void onStart() 
void onRestart() 
void onResume() 
void onPause() 
void onStop() 
void onDestroy()

Activity经历如下3个阶段:

开始Activity: 在这个阶段依次执行3个生命周期的方法,分别是onCreate、onStart和onResume方法。

Activity重新获得焦点:如果Activity重新获得焦点,会依次执行3个生命周期,分别是 onRestart、onStart和onResume

关闭Activity:当Activity被关闭时系统会依次执行3个生命周期方法,分别是:onPause、onStop和onDestory。

从以上的Activity的生命周期不难看出,该图包含了两层循环,第一层循环是onPauseonResumeonPause ;第二层循环是onStartonRestartonResumeonPauseonStop 。我们可以将这两层的循环看成整个Activity的生命周期的子生命周期 ,第一层循环称为是焦点生命周期,第二层循环可以视为生命周期。
也就是说,第一层循环在Activity焦点获得与失去的过程中循环,在这个过程中,Activity始终是可见的,第二层循环是Activity可见和不可见的过程中循环。
这个过程中伴随着Activity焦点的获得与失去,也就是说,Activity首先会被显示,然后会获得焦点,接着失去焦点,最后弹出其他的Activity
Activity具体的生命周期如下:
整体的生命周期:onCreate…..onDestory
可视生命周期:onStart…..onStop
焦点生命周期:onResumeonPause

------------------------------------------------------------------------------------------------------------------------------------

android中的数据传递

在Activity之间数据传递,还有一种比较实用的方式,就是全局对象;

在JAVA WEB的四个作用域中,这四个作用域从小到大分别是Page,Request,Session,Application,其中Application域在应用程序的任何地方都可以使用和访问,除非是WEB服务器停止,Android中的全局对象非常类似于JAVA WEB中的Application域,除非是Android应用程序清除内存,否则全局对象将一直可以访问。

------------------------------------------------------------------------------------------------------------------------------------

问题概述:

在run project 后提示如下错误:

“Error generating final archive: Debug Certificate expired ....”

原因分析:

android要求所有的程序必须有签名,否则就不会安装该程序。在我们开发过程中,adt使用debug keystore,在 preference->android->buid中设置。debug的keystore默认有效期为一年,如果你是从一年前开始完android程序,那么在一年后导入这个app的时候很可能出现debug keystore过期,导致你无法生成 apk文件。

此时你只要删除debug keystore就行,系统又会为你生成有效期为一年的私钥。

解决方法:

可在eclipse中查找此路径:Window->Preferences->Android->Build下 Default debug keystore

将该路径下的 debug.keystore和 ddms.cfg 删除,然后重新run即可。

--------------------------------------------------------------------------------------------------------------------------------------

常用方法

1.手机屏幕分辨率 

DisplayMetrics dm = new DisplayMetrics();

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

String strOpt = "手机屏幕分辨率为:" + dm.widthPixels + " × " + dm.heightPixel;

2.调用一个新的Activity,传递Bundle

/* new一个Intent对象,并指定要启动的class */ 
 Intent intent = new Intent(); 
 intent.setClass(EX03_09_1.this, EX03_09.class);

/*new一个Bundle对象,并将要传递的数据传入*/
 Bundle bundle = new Bundle();
  bundle.putDouble("height",height);
  bundle.putString("sex",sex); 
 /*将Bundle对象assign给Intent*/ 
  intent.putExtras(bundle); 
 /* 调用一个新的Activity */ startActivity(intent); 
 /* 关闭原本的Activity */ 
EX03_09_1.this.finish();

3. 取得Intent中的Bundle对象

/* 取得Intent中的Bundle对象 */
 Bundle bunde = this.getIntent().getExtras();
    
  /* 取得Bundle对象中的数据 */
  String sex = bunde.getString("sex");
  double height = bunde.getDouble("height");

4.选择窗口

new AlertDialog.Builder(EX03_20.this).setTitle(R.string.str_alert_title)
          .setItems(R.array.items_irdc_dialog,
              new DialogInterface.OnClickListener()
              {
                public void onClick(DialogInterface dialog, int whichcountry)
                {
                  CharSequence strDialogBody = getString(R.string.str_alert_body);
                  String[] aryShop = getResources().getStringArray(
                      R.array.items_irdc_dialog);
                  new AlertDialog.Builder(EX03_20.this).setMessage(
                      strDialogBody + aryShop[whichcountry]).setNeutralButton(
                      R.string.str_ok, new DialogInterface.OnClickListener()
                      {
                        public void onClick(DialogInterface dialog,
                            int whichButton)
                        { /* 在这里处理要作的事 */
                        }
                      }).show();
                }
              }).setNegativeButton("取消", new DialogInterface.OnClickListener()
          {
            @Override
            public void onClick(DialogInterface d, int which)
            {
              d.dismiss();
            }
          }).show();

5.显示Progress对话框

// 显示Progress对话框
      myDialog = ProgressDialog.show(EX03_19.this, strDialogTitle,
          strDialogBody, true);

6.调试信息的输出

Log.v(TAG, "This is a VERBOSE message");//输出冗余消息
        Log.d(TAG, "This is a DEBUG message");//输出调试消息
        Log.i(TAG, "This is an INFO message");//输出普通消息
        Log.w(TAG, "This is a WARNING message");//输出警告消息
        Log.e(TAG, "This is a ERROR message");//输出错误消息

-------------------------------------------------------------------------------------------------------------------------------------------

菜单使用例子

//初始化菜单,这个函数只会被被调用一次,在菜单第一次显示时调用,要想每次显示时都更新请参见 onPrepareOptionsMenu(Menu).
  public boolean onCreateOptionsMenu(Menu menu)
  {
    menu.add(0, 0, 0, R.string.app_about);
    menu.add(0, 1, 1, R.string.str_exit);
    return super.onCreateOptionsMenu(menu);
  }
  //描述当菜单选项被选择时,如何作响应
  public boolean onOptionsItemSelected(MenuItem item)
  {
    super.onOptionsItemSelected(item);
    switch(item.getItemId())
    {
      case 0:
        openOptionsDialog();
        break;
      case 1:
        finish();
        break;
    }
    return true;
  }
    //响应函数
  private void openOptionsDialog()
  {
    new AlertDialog.Builder(this)
    .setTitle(R.string.app_about)
    .setMessage(R.string.app_about_msg)
    .setPositiveButton(R.string.str_ok,
        new DialogInterface.OnClickListener()
        {
         public void onClick(DialogInterface dialoginterface, int i)
         {
         }
         }
        )
    .show();
  }

-----------------------------------------------------------------------------------------------------------------------------

常用例子代码

1.使用Toast  

/*使用系统标准的 makeText()方式来产生Toast讯息*/

Toast.makeText( EX04_03.this, "你的愿望 "+Str.toString()+"已送达耶诞老人信箱", Toast.LENGTH_LONG).show();

/*使用带图片的Toast*/

LinearLayout lay = new LinearLayout(EX05_07.this);
        /*设定mTextView去抓取string值*/ 
        mTextView.setText(R.string.app_url);  
        /*用Toast方式显示*/ 
        Toast toast = Toast.makeText(EX05_07.this, mTextView .getText(), Toast.LENGTH_LONG); 
        View textView = toast.getView(); 
        lay.setOrientation(LinearLayout.HORIZONTAL);
        /*在Toast里加上图片*/
        mView01.setImageResource(R.drawable.icon); 
        /*在Toast里显示图片*/ lay.addView(mView01); 
        /*在Toast里显示文字*/ lay.addView(textView); 
        toast.setView(lay);
        toast.show();

2.拨打电话

/*建构一个新的Intent并执行action.CALL的常数与透过Uri将字符串带入*/
Intent myIntentDial = new Intent("android.intent.action.CALL",Uri.parse("tel:"+strInput)); 
/*在startActivity()方法中带入自定义的Intent对象以执行拨打电话的工作*/ 
startActivity(myIntentDial);

  3.发短信

/*建构一取得default instance的 SmsManager对象 */ 
     SmsManager smsManager = SmsManager.getDefault(); 
    
 /* 先建构一PendingIntent对象并使用getBroadcast()方法进行Broadcast * 
 / * 将PendingIntent,电话,简讯文字等参数传入sendTextMessage()方法发送简讯*/ 
     PendingIntent mPI = PendingIntent.getBroadcast(EX05_03.this, 0, new Intent(), 0); 
     smsManager.sendTextMessage(strDestAddress, null, strMessage, mPI, null);

4.发邮件

/*透过Intent来发送邮件*/
     Intent mEmailIntent = 
    new Intent(android.content.Intent.ACTION_SEND); 
 /*设定邮件格式为plain/text*/
      mEmailIntent.setType("plain/text");
 /*取得EditText01,02,03,04的值作为收件人地址,附件,主题,内容*/
      strEmailReciver = new String[]{mEditText01.getText().toString()};
      strEmailCc = new String[]{mEditText02.getText().toString()};
      strEmailSubject = mEditText03.getText().toString();
      strEmailBody = mEditText04.getText().toString(); 
   /*将取得的字符串放入mEmailIntent中*/
      mEmailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, strEmailReciver); 
      mEmailIntent.putExtra(android.content.Intent.EXTRA_CC, strEmailCc);
      mEmailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, strEmailSubject);
      mEmailIntent.putExtra(android.content.Intent.EXTRA_TEXT, strEmailBody); 
      /*开启Gmail 并将相关参数传入*/ 
      startActivity(Intent.createChooser(mEmailIntent, getResources().getString(R.string.str_message)));

5.使用Notication

/* 建立新的Intent,作为点选Notification留言条时,
     * 会执行的Activity */ 
    Intent notifyIntent=new Intent(this,EX05_08_1.class);  
    notifyIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
    /* 建立PendingIntent作为设定递延执行的Activity */ 
    PendingIntent appIntent=PendingIntent.getActivity(EX05_08.this,0,
                                                      notifyIntent,0);
       
    /* 建立Notication,并设定相关参数 */ 
    Notification myNoti=new Notification();
    /* 设定statusbar显示的icon */
    myNoti.icon=iconId;
    /* 设定statusbar显示的文字讯息 */
    myNoti.tickerText=text;
    /* 设定notification发生时同时发出预设声音 */
    myNoti.defaults=Notification.DEFAULT_SOUND;
    /* 设定Notification留言条的参数 */
    myNoti.setLatestEventInfo(EX05_08.this,"MSN登入状态",text,appIntent);
    /* 送出Notification */
    myNotiManager.notify(0,myNoti);

6.横式直式切换

if(getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
          {
            /* 若当前为横式,则变更为直式显示 */
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
          }
          else if(getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
          {
            /* 若当前为直式,则变更为横式显示 */
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
          }

---------------------------------------------------------------------------------------------------------------------------------------------------

SQLite的简单实例

//实例类

public class ToDoDB extends SQLiteOpenHelper

{
  private final static String DATABASE_NAME = "todo_db";
  private final static int DATABASE_VERSION = 1;
  private final static String TABLE_NAME = "todo_table"; 
  public final static String FIELD_id = "_id";
  public final static String FIELD_TEXT = "todo_text"; 
  public ToDoDB(Context context) 
  { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); }
  @Override 
  public void onCreate(SQLiteDatabase db)
  {
    /* 建立table */ 
    String sql = "CREATE TABLE " 
      + TABLE_NAME + " (" + FIELD_id +
      " INTEGER primary key autoincrement, "
      + " " + FIELD_TEXT + " text)"; 
    db.execSQL(sql); 
    } 
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
  { 
    String sql = "DROP TABLE IF EXISTS " 
      + TABLE_NAME; db.execSQL(sql);
      onCreate(db); 
      }
  public Cursor select() 
  { 
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
    return cursor;
    }
  public long insert(String text)
  { 
    SQLiteDatabase db = this.getWritableDatabase();
    /* 将新增的值放入ContentValues */
    ContentValues cv = new ContentValues();
    cv.put(FIELD_TEXT, text);
    long row = db.insert(TABLE_NAME, null, cv); 
    return row; 
    } 
  public void delete(int id) 
  { 
    SQLiteDatabase db = this.getWritableDatabase();
    String where = FIELD_id + " = ?"; 
    String[] whereValue = { Integer.toString(id) };
    db.delete(TABLE_NAME, where, whereValue); 
    } 
  public void update(int id, String text) 
  { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    String where = FIELD_id + " = ?";
    String[] whereValue = { Integer.toString(id) }; 
    /* 将修改的值放入ContentValues */ 
    ContentValues cv = new ContentValues(); 
    cv.put(FIELD_TEXT, text); 
    db.update(TABLE_NAME, cv, where, whereValue); 
    }

}

----------------------------------------------------------------------------------------------------------------------------------------

监听短信接收实例

/* 自定义继承自BroadcastReceiver类,监听系统服务广播的信息 */
public class EX06_01_SMSreceiver extends BroadcastReceiver 

   /*声明静态字符串,并使用android.provider.Telephony.SMS_RECEIVED作为Action为短信的依据*/
  private static final String mACTION = "android.provider.Telephony.SMS_RECEIVED"; 
  
  @Override 
  public void onReceive(Context context, Intent intent) 
  { 
    // TODO Auto-generated method stub 
    /* 判断传来Intent是否为短信*/
    if (intent.getAction().equals(mACTION)) 
    { 
      /*建构一字符串集集合变量sb*/
      StringBuilder sb = new StringBuilder(); 
      /*接收由Intent传来的数据*/
      Bundle bundle = intent.getExtras(); 
      /*判断Intent是有资料*/
      if (bundle != null) 
      { 
        /* pdus为 android内建短信参数 identifier
         * 透过bundle.get("")并传一个包含pdus的对象*/
        Object[] myOBJpdus = (Object[]) bundle.get("pdus"); 
        /*建构短信对象array,并依据收到的对象长度来建立array的大小*/
        SmsMessage[] messages = new SmsMessage[myOBJpdus.length];  
        for (int i = 0; i<myOBJpdus.length; i++) 
        {  
          messages[i] = SmsMessage.createFromPdu ((byte[]) myOBJpdus[i]);  
        } 
          
        /* 将送来的短信合并自定义信息于StringBuilder当中 */  
        for (SmsMessage currentMessage : messages) 
        {  
          sb.append("接收到来告:\n");  
          /* 来讯者的电话号码 */ 
          sb.append(currentMessage.getDisplayOriginatingAddress());  
          sb.append("\n------传来的短信------\n");  
          /* 取得传来讯息的BODY */  
          sb.append(currentMessage.getDisplayMessageBody());  
        }  
      }    
      /* 北Notification(Toase)显示短信信息  */
      Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show(); 
       
      /* 返并加Activity */ 
      Intent i = new Intent(context, EX06_01.class); 
      /*设定让加Activity以一个新的task来执行*/
      i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
      context.startActivity(i); 
    } 
  } 
--------------------------------------------------------------------------------------------------------------------------------------------
Service的简单使用例子
/* 建构Intent对象,指定开启对象为mService1服务 */
        Intent i = new Intent( EX06_04.this, mService1.class );
        
        /* 设定新TASK的方式 */
        i.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
        
        /* 以startService方法启动Intent */

startService(i);

/* 构造Intent对象,指定欲关闭的对象为mService1服务 */
        Intent i = new Intent( EX06_04.this, mService1.class );
        
        /* 以stopService方法关闭Intent */
        stopService(i);

---------------------------------------------------------------------------------------------------------------------------------------------

监听电话的例子

/* 内部class继承PhoneStateListener */
  public class exPhoneCallListener extends PhoneStateListener
  {
    /* 重写onCallStateChanged当状态改变时改变myTextView1的文字及颜色 */
    public void onCallStateChanged(int state, String incomingNumber)
    {
      switch (state)
      {
        /* 无任务状态时 */
        case TelephonyManager.CALL_STATE_IDLE:
          myTextView1.setTextColor(getResources().getColor(R.drawable.red));
          myTextView1.setText("CALL_STATE_IDLE");
          break;
        /* 接起电话时 */
        case TelephonyManager.CALL_STATE_OFFHOOK:
          myTextView1.setTextColor(getResources().getColor(R.drawable.green));
          myTextView1.setText("CALL_STATE_OFFHOOK");
          break;
        /* 电话进来时 */
        case TelephonyManager.CALL_STATE_RINGING:
          getContactPeople(incomingNumber);
          break;
        default:
          break;
      }
      super.onCallStateChanged(state, incomingNumber);
    }

}

///

/* 新增的PhoneStateListener */
    exPhoneCallListener myPhoneCallListener = new exPhoneCallListener();
    /* 取得电话服务 */
    TelephonyManager tm = (TelephonyManager) this
        .getSystemService(Context.TELEPHONY_SERVICE);
    /* 注册Listener */
    tm.listen(myPhoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);

-------------------------------------------------------------------------------------------------------------------------------------------------------

查看SD card使用情况的例子

/* 判断记忆卡是否插入 */
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
    { 
      /* 取得SD CARD档案路径一般是/sdcard */
      File path = Environment.getExternalStorageDirectory(); 
      /* StatFs看文件系统空间使用状况 */
      StatFs statFs = new StatFs(path.getPath());
      /* Block的size */
      long blockSize = statFs.getBlockSize(); 
      /* 总Block数量 */ 
      long totalBlocks = statFs.getBlockCount(); 
      /* 已使用的Block数量 */
      long availableBlocks = statFs.getAvailableBlocks(); 
      String[] total = fileSize(totalBlocks * blockSize); 
      String[] available = fileSize(availableBlocks * blockSize);
      /* getMax取得在main.xml里ProgressBar设定的最大值 */
      int ss = Integer.parseInt(available[0]) * myProgressBar.getMax() / Integer.parseInt(total[0]); 
      myProgressBar.setProgress(ss); 
      String text = "总共" + total[0] + total[1] + "\n"; text += "可用" + available[0] + available[1]; 
      myTextView.setText(text); } 
    else if (Environment.getExternalStorageState().equals( Environment.MEDIA_REMOVED))
    { 
      String text = "SD CARD已移除"; myTextView.setText(text); 
      }
    } 
------------------------------------------------------------------------------------------------------------------------------
文件存取简单例子

/* 将值写入文件mc.ini*/

boolean isExit = true;

FileOutputStream fos = null;
    try
    {
      openFileInput(fileName);
    } catch (FileNotFoundException e)
    {
      isExit = false;
    }
    if (!isExit)
    {
      try
      {
        fos = openFileOutput(fileName, MODE_WORLD_WRITEABLE);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

/* 系统日期为上次MC第一天的日期 */
        mcdate_value = DateUtil.getDateTime("yyyyMMdd", System
            .currentTimeMillis());
        String txt = mcdate_key + "=" + mcdate_value;
        bos.write(txt.getBytes());
        /* 周期为28天 */
        bos.write(new String("\n").getBytes());
        txt = period_key + "=" + period_value;
        bos.write(txt.getBytes());
        /* 提醒时间为中午12点 */
        bos.write(new String("\n").getBytes());
        txt = remind_key + "=" + remind_value;
        bos.write(txt.getBytes());

bos.close();
        fos.close();

} catch (FileNotFoundException e)
      {
        e.printStackTrace();
      } catch (IOException e)
      {
        e.printStackTrace();
      }
    }
    /* 将文件mc.ini里的值取出 */
    Properties p = new Properties();
    try
    {
      p.load(openFileInput(fileName));
      mcdate_value = p.getProperty(mcdate_key);
      period_value = p.getProperty(period_key);
      remind_value = p.getProperty(remind_key);
    } catch (FileNotFoundException e)
    {
      e.printStackTrace();
    } catch (IOException e)
    {
      e.printStackTrace();

}

///

try {
// 创建文件
file = new File(FILE_PATH, FILE_NAME);
file.createNewFile();

// 打开文件file的OutputStream
out = new FileOutputStream(file);
String infoToWrite = "我是即将要写入文件的内容";

// 将字符串转换成byte数组写入文件
out.write(infoToWrite.getBytes());
// 关闭文件file的OutputStream
out.close();

// 打开文件file的InputStream
in = new FileInputStream(file);
// 将文件内容全部读入到byte数组
int length = (int) file.length();
byte[] temp = new byte[length];
in.read(temp, 0, length);

// 将byte数组用UTF-8编码并存入display字符串中
display = EncodingUtils.getString(temp, TEXT_ENCODING);
// 关闭文件file的InputStream
in.close();
} catch (IOException e) {
// 将出错信息打印到Logcat
Log.e(TAG, e.toString());
this.finish();
}

-------------------------------------------------------------------------------------------------------------------------------------------------

QR Code条形码的产生

/* 自定义生成QR Code的函数 */
  public void AndroidQREncode(String strEncoding, int qrcodeVersion)
  {
    try
    {
      /* 建构QRCode编码对象 */
      com.swetake.util.Qrcode testQrcode = new com.swetake.util.Qrcode();
      /* L','M','Q','H' */
      testQrcode.setQrcodeErrorCorrect('M');
      /* "N","A" or other */
      testQrcode.setQrcodeEncodeMode('B');
      /* 0-20 */
      testQrcode.setQrcodeVersion(qrcodeVersion);
      
      // getBytes
      byte[] bytesEncoding = strEncoding.getBytes("utf-8");
      
      if (bytesEncoding.length>0 && bytesEncoding.length <120)
      {
        /* 将字符串透过calQrcode函数转换成boolean数组 */
        boolean[][] bEncoding = testQrcode.calQrcode(bytesEncoding);
        /* 依据编码后的boolean数组,绘图 */
        drawQRCode(bEncoding, getResources().getColor(R.drawable.black));
      }
    }
    catch (Exception e)
    {
      Log.i("HIPPO", Integer.toString(mEditText01.getText().length()) );
      e.printStackTrace();
    }
  }
  
  /* 在SurfaceView上绘制QRCode图片 */
  private void drawQRCode(boolean[][] bRect, int colorFill)
  {
    /* test Canvas*/
    int intPadding = 20;
    
    /* 欲在SurfaceView上绘图,需先lock锁定SurfaceHolder */
    Canvas mCanvas01 = mSurfaceHolder01.lockCanvas();
    
    /* 设定画布绘制颜色 */
    mCanvas01.drawColor(getResources().getColor(R.drawable.white));
    
    /* 建立画笔 */
    Paint mPaint01 = new Paint();
    
    /* 设定画笔颜色及样式 */
    mPaint01.setStyle(Paint.Style.FILL);
    mPaint01.setColor(colorFill);
    mPaint01.setStrokeWidth(1.0F);
    
    /* 逐一加载2维boolean数组 */
    for (int i=0;i<bRect.length;i++)
    {
      for (int j=0;j<bRect.length;j++)
      {
        if (bRect[j][i])
        {
          /* 依据数组值,绘出条形码方块 */
          mCanvas01.drawRect(new Rect(intPadding+j*3+2, intPadding+i*3+2, intPadding+j*3+2+3, intPadding+i*3+2+3), mPaint01);
        }
      }
    }
    mSurfaceHolder01.unlockCanvasAndPost(mCanvas01);
  }
  
-----------------------------------------------------------------------------------------------------------------------------------------------------
Http Get使用简单例子
public String get(String url) throws Exception {

HttpClient client = new DefaultHttpClient();

HttpGet get = new HttpGet(url);

HttpResponse response = client.execute(get);

HttpEntity entity = response.getEntity();

// 尝试读取entity的长度,返回-1表示长度未知

long length = entity.getContentLength();

InputStream is = entity.getContent();

String s = null;
if (is != null) {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buf = new byte[512];

int ch = -1;
int count = 0;

while ((ch = is.read(buf)) != -1) {

baos.write(buf, 0, ch);

count += ch;

}

Log.e("HttpTask", "length=" + baos.toByteArray().length);
// 返回内容
s = new String(baos.toByteArray());
}
return s; 
}

-------------------------------------------------------------------------------------------------------------------------------------------------

转载于:https://www.cnblogs.com/lteal/p/3545941.html

【Android学习日记】相关推荐

  1. android学习日记 RecyclerView的简单使用

    android学习日记 RecyclerView的简单使用 文章目录 android学习日记 RecyclerView的简单使用 一.如何使用RecyclerView? 二.使用步骤 1.首先在bui ...

  2. Android学习日记 Notification 通知

    Android学习日记 Notification 通知 文章目录 Android学习日记 Notification 通知 前言 使用步骤 总结 前言 下拉状态栏显示的通知功能 使用步骤 代码如下: p ...

  3. android学习日记一

    这几天在公司实习,公司主要是做android项目,以前在学校也学习过android,但是就学了点皮毛,在这里我准备把自己当做android一无所知的人,但是java会点的人,来系统的学习一下andro ...

  4. 日记背景 android,android学习日记:4.0源生背景修改

    经过整整一周的学习,总算实现了android中源生背景的修改.效果如下: 分别是修改前的原始界面.选择背景设置界面以及最后的效果图. 之前一直想用ScrollView来实现这个效果,后来发现用Gall ...

  5. Android学习日记(1)

    直接上代码: IBinder类: /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apac ...

  6. android学习日记24--Android 菜单开发

    菜单是任何应用程序必不可少的一项.按下Menu键或者长按某个View就会弹出相应菜单,当然前提是应用程序有实现菜单功能. Android平台下的菜单有:Options Menu(选项菜单).Subme ...

  7. 【转】android学习日记01--综述

    转自:http://www.cnblogs.com/aiguozhe/p/3541941.html 一.总体框架 先上一张google提供官方的Android框架图: Android系统架构由5部分组 ...

  8. android学习日记16--GridView(网格视图)

    一.GridView 1.简述 GridView按照行列来显示图片或文本的一种视图,排列其实有点类似TableLayout布局, 不过和TableLayout还是差别很大的,倒比较像二维的ListVi ...

  9. android学习日记13--数据存储之ContentProvide

    3.ContentProvider 数据在Android当中是私有的,当然这些数据包括文件数据和数据库数据以及一些其他类型的数据.ContentProvider实现多应用程序间的数据共享类 一般利用C ...

  10. android学习日记12--布局管理器

    1.概述 布局管理器的用途: a.可以更好的管理组件; b.通过使用布局管理器,Android应用程序可以做到平台无关性 布局管理器都是ViewGroup的子类,所有可充当容器的父类都是ViewGro ...

最新文章

  1. 人人出售部分Social Finance 股票 获益9190万美
  2. 数据驱动的未来城市八大趋势
  3. SAP Kyma的Lambda Function describe命令输出
  4. ListView展示SIM信息
  5. pycharm不同py文件共享参数_PyCharm安装笔记
  6. C# WebBrowser实现网页自动填表
  7. 选择操作、投影操作、交操作
  8. 拓端tecdat|R语言曲线回归:多项式回归、多项式样条回归、非线性回归数据分析
  9. 基因表达式编程的任务指派问题求解算法设计与实现
  10. 【分享】外卖优惠券怎么弄微信返利公众号系统的流程和方法
  11. 手把手DES加密解密详解-Java,Python
  12. keep-alive 组件缓存的用法
  13. Java 获取主机ip地址(ipv4)
  14. 一大堆模块的结晶……
  15. 第一个java程序(输出个人信息)
  16. 计算机怎样禁用中等加密算法,限制加密算法和协议 - Windows Server | Microsoft Docs...
  17. 通过 ffmpeg 无损剪切与拼接视频方法
  18. 【算法】只有五行的Floyd最短路算法
  19. VR实时语音,带着最好的武器去战斗
  20. Dogs vs. Cats

热门文章

  1. flume+kafka整合采集数据案例
  2. 软件测试性能工程师工资,软件测试工程师工资一般多少 前景怎么样
  3. 常用颜色的RGB分布
  4. 自旋锁以及Java中的自旋锁的实现
  5. OpenCV中使用Eigenfaces人脸识别器识别人脸实战(附Python源码)
  6. 为金融而生的区块链Injective(INJ)
  7. oppoa9处理器怎么样_OPPOA9处理器是骁龙几?
  8. 自上而下的语法分析-递归下降分析和LL(1)文法
  9. 计算机怎样禁用中等加密算法,限制加密算法和协议 - Windows Server | Microsoft Docs...
  10. 服务器内存占用太高如何解决及知识点介绍