Android工具代码块儿

来源:互联网 发布:敏捷软件开发 源代码 编辑:程序博客网 时间:2024/05/29 19:31

1. 让某个Activity透明

OnCreate中不设置Layout

this.setTheme(R.style.Theme_Transparent);

以下是Theme_Transparent的定义(注意transparent_bg是一副头透明的图片)


 

 设置ActivityDialog的形式

在AndroidManifest.xml中配置Activity节点中配置theme如下:

android:theme = @android:style/Theme.Dialog


1. 发送短息

注册权限

<uses-permission android:name="android.permission.SEND_SMS"/>

一:

Intent it = newIntent(Intent.ACTION_VIEW);  

it.putExtra("sms_body", "TheSMS 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", "TheSMS text");  

startActivity(it);

 

String body="this is sms demo";

Intent mmsintent = newIntent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", number, null));

mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY,body);

mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE,true);

mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT,true);

startActivity(mmsintent);

 

三:后台发送短信

        注册权限

<uses-permissionandroid:name="android.permission.SEND_SMS" />

代码实现 :

// 获取信息内容

String message ;

// 移动运营商允许每次发送的字节数据有限,我们可以使用Android给我们提供 的短信工具。

if (message != null) {

SmsManager sms = SmsManager.getDefault();

// 如果短信没有超过限制长度,则返回一个长度的List。

List<String> texts =sms.divideMessage(message);

for (String text : texts) {

sms.sendTextMessage(“这里是接收者电话号码”, “这里是发送者电话号码”, “这里是短信内容”,  null, null);

}

}

//说明

sms.sendTextMessage(destinationAddress,scAddress, text, sentIntent, deliveryIntent):

destinationAddress:接收方的手机号码

scAddress:发送方的手机号码

text:信息内容

sentIntent:发送是否成功的回执,

DeliveryIntent:接收是否成功的回执



1. 发送彩信

StringBuilder sb = new StringBuilder();

Sb.append(“file://”);

Sb.append(fd.getAbsoluteFile());

Intent intent = newIntent(Intent.ACTION_SENDTO,Uri.fromParts(“mmsto”,number,nul));

//Below exra datas are all optional

intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);

intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY,body);

intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI,sb.toString());

intent.putExtra()

   

    或者

    Uri uri =Uri.parse("content://media/external/images/media/23");  

Intent it = newIntent(Intent.ACTION_SEND);  

it.putExtra("sms_body", "sometext");  

it.putExtra(Intent.EXTRA_STREAM, uri);  

it.setType("image/png");  

startActivity(it);

StringBuilder sb = new StringBuilder();

sb.append("file://");

sb.append(fd.getAbsoluteFile());

Intent intent = newIntent(Intent.ACTION_SENDTO, Uri.fromParts("mmsto", number, null));

// Below extra datas are all optional.

intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT,subject);

intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY,body);

intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI,sb.toString());

intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE,composeMode);

intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT,exitOnSent);

startActivity(intent);


1. 发送Mail

/*mime = “img/jpg”;

shareIntent.setDataAndType(Uri.fromFile(fd) ,mime);

shareIntent.putExtra(Intent.EXTRA_STREAM ,Uri.fromFile(fd));

shareIntent.putExtra(Intent.EXTRA_SUBJECT ,subject);

shareIntent.putExtra(Intent.EXTRA_TEXT , body);*/

 

Intent i = new Intent(Intent.ACTION_SEND);

//i.setType(“text/plain”);//模拟器请使用这行

i.setType(“message/rfc822”);//真机上使用这行

i.putExtra(Intent.EXTRA_STREAM , new String[]{“test@gmail.com”,”test@163.com”});

i.putExtra(Intent.EXTRA_SUBJECT , “subject goeshere”);

i.putExtra(Intent.EXTRA_TEXT , “body goeshere”);

startActivity(Intent.createChooser(i,”Select emailapplication”));

或者:

Uri uri =Uri.parse("mailto:xxx@abc.com");

Intent it = new Intent(Intent.ACTION_SENDTO,uri);

startActivity(it);

 

或者:

Intent intent = new Intent(Intent.ACTION_SEND);  

intent.putExtra(Intent.EXTRA_EMAIL, address);  

intent.putExtra(Intent.EXTRA_SUBJECT, filename);  

intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + filename)); ;

intent.setType("text/csv");  

startActivity(Intent.createChooser(intent, "EMail File"));  

 

或者:

Intent it = newIntent(Intent.ACTION_SEND);  

it.putExtra(Intent.EXTRA_EMAIL,"me@abc.com");  

it.putExtra(Intent.EXTRA_TEXT, "Theemail body text");  

it.setType("text/plain");  

startActivity(Intent.createChooser(it,"Choose Email Client"));

 

或者:

Intent it=newIntent(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, "Theemail body text");    

it.putExtra(Intent.EXTRA_SUBJECT, "Theemail subject text");    

it.setType("message/rfc822");    

startActivity(Intent.createChooser(it,"Choose Email Client"));  

 

或者:

Intent it = newIntent(Intent.ACTION_SEND);  

it.putExtra(Intent.EXTRA_SUBJECT, "Theemail subject text");  

it.putExtra(Intent.EXTRA_STREAM,"file:///sdcard/mysong.mp3");  

sendIntent.setType("audio/mp3");  

startActivity(Intent.createChooser(it,"Choose Email Client")); 


3. Android拨打电话

 拨打电话

Uri uri = Uri.parse("tel:xxxxxx");

Intent it = new Intent(Intent.ACTION_CALL,uri);  

//Intent call = newIntent(Intent.ACTION_DIAL, uri); //只是拨号, 并未呼叫

startActivity(it);

 注册权限

<uses-permissionandroid:name="android.permission.CALL_PHONE"/>

 

3.2 电话窃听器

要实现电话窃听,需要监听电话的状态,方法如下:

/* 取得电话服务 */

TelephonyManager telManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

PhoneStateListener listener = new PhoneStateListener(){   

       @Override  public void onCallStateChanged(int state,String incomingNumber) {

             switch (state){

               case TelephonyManager.CALL_STATE_IDLE:/* 无任何状态时 */

                      break;

               case TelephonyManager.CALL_STATE_OFFHOOK:/* 接起电话时 */

                      break;    

               caseTelephonyManager.CALL_STATE_RINGING: /* 电话进来时 */

                      break;

               default:

              break;

             }

       super.onCallStateChanged(state,incomingNumber);

       }            

};

//监听电话的状态

telManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

在清单文件AndroidManifest.xml中添加权限:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

 



4.  系统操作

获得手机的UA

public String getUserAgent()

{

String user_agent =ProductProperties.get(ProductProperties.USER_AGENT_KEY , null);

Return user_agent;

}


判断SIM卡属于哪个移动运营商

在文件AndroidManifest.xml中添加权限

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

 

第一种方法:

获取手机的IMSI,并判断是中国移动、中国联通、中国电信

TelephonyManager  telManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

  /** 获取SIM卡的IMSI码

              *SIM卡唯一标识:IMSI 国际移动用户识别码(IMSI:International Mobile SubscriberIdentification Number)是区别移动用户的标志,

        * 储存在SIM卡中,可用于区别移动用户的有效信息。IMSI由MCC、MNC、MSIN组成,其中MCC为移动国家号码,由3位数字组成,

        * 唯一地识别移动客户所属的国家,我国为460;MNC为网络id,由2位数字组成,

        * 用于识别移动客户所归属的移动网络,中国移动为00,中国联通为01,中国电信为03;MSIN为移动客户识别码,采用等长11位数字构成。

        * 唯一地识别国内GSM移动通信网中移动客户。所以要区分是移动还是联通,只需取得SIM卡中的MNC字段即可

        */

       String imsi = telManager.getSubscriberId();

 if(imsi!=null){

       if(imsi.startsWith("46000") ||imsi.startsWith("46002")){//因为移动网络编号46000下的IMSI已经用完,所以虚拟了一个46002编号,134/159号段使用了此编号

        //中国移动

       }else if(imsi.startsWith("46001")){

        //中国联通

       }else if(imsi.startsWith("46003")){

        //中国电信

       }

}

 

第二种方法

TelephonyManager telManager =(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

       String operator = telManager.getSimOperator();

 if(operator!=null){

       if(operator.equals("46000") ||operator.equals("46002")){

        //中国移动

       }else if(operator.equals("46001")){

        //中国联通

       }else if(operator.equals("46003")){

        //中国电信

       }

}



清空手机上的cookie

CookieSyncManager.createInstance(getApplicationContext());

CookieManager.getInstance().removeAllCookie();


 获取手机号码

//创建电话管理  //与手机建立连接

TelephonyManager tm = activity.getSystemService(Context.TELEPHONY_SERVICE);

 //获取手机号码

String phoneid = tm.getLine1Number();

//记得在manifest file中添加

 //程序在模拟器上无法实现,必须连接手机


检查当前网络是否连上

ConnectivityManager conn = (ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);

Boolean wifi =con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();

Boolean internet =con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnetedOrConnecting();

在AndroidManifest.xml中添加权限

<uses-permission Android:name = “android.permission.ACCESS_NETWORK_STATE”/>

 

 Android 获取设备唯一id

String android_id =Secure.getString(getContext().getContentResolver() , Secure.ANDROID_ID);

 

 Android中获取IP地址

Public String getLocalIpAddress(){

Try{

for(Enumeration(NetworkInterface)en = NetworkInterface.getNetworkInterface();en.hasMoreElements();){

NetworkInterface intf =en.nextElement();

for(Enumeration<InetAddress>enumIpAddr = intf.getInetAddress();anumIpAddr.hasMoreElements();){

InetAddress inetAddress =enumIpAddr.nextElement();

If(!inetAddress.isLoopbackAddress()){

RetruninetAddress.getHostAddress().toString();

}

}

}

}catch(SocketExceptionex){

Log.e(LOG_TAG ,ex.toString());

}

return null;

}

 Android获取存储卡路径以及使用情况:

/*获取存储卡路径*/

File sdcardDir =Envoiroment.getExternalStorageDirectory();

/*StatFs看文件系统空间使用情况*/

StatFs statFs = new StatFs(sdcardDir.getPath());

/*Block的size*/

Long blockSize = statFs.getBlockSize();

/**总Block数量/

Long totalBlocks = statFs.getBlockCount();

/*已使用的Block数量*/

Long availableBlocks = statFs.getAvailableBlocks();


察看电池使用情况:

Intent intentBatteryUsage = newIntent(Intent.ACTION_POWER_USAGE_SUMMARY);

startActivity(intentBatteryUsage);


 关闭软键盘

private void hideSoftInput(){

InputMethodManager imm =(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);

}

 回退按钮

public boolean onKeyDown(int keyCode, KeyEventevent){

If(keyCode ==KeyEvent.KEYCODE_BACK && event.getRepeatCount() ==0){

newAlertDialog.Builder(xxxActivity.this)

.setTitle(“退出系统”)

.setMessage(“确定要退出系统吗”)

.setPositiveButton(“退出”,newDialogInterface.OnClickListener(){

public voidonCLick(DialogInterface dialog,int which){

finish();

}})

.setNegativeButton(“取消”,

newDialogInterface.OnClickListener(){

public voidonClick(DialogInterface dialog , int which){

dialog.cancel();

}

}

).show();

}

return false;

}


34. Mac地址和开机时间

Public String[] getOtherInfo(){

String[] other = [“null”,”null”];

WifiManager wifimanager =(WiFiManager)mContext.getSystemService(Context.WiFI_SERVICE);

WifiInfo wifiInfo =wifimanager.getConnetionInfo();

if(wifiInfo.getMacAddress()!=null){

other[0] =wifiInfo.getMacAddress();

}else{

other[0] = “Fail”;

}

other[1] = getTimes();

return other;

}

private String getTimes(){

Long ut =SystemClock.elapsedRealtime()/1000;

If(ut == 0){

ut = 1;

}

int m = (int)((ut/60)%60);

int h = (int)((ut/3600));

Return h + “ “ +mContext.getString(R.String.info_times_hour) + m + “”+mContext.getString(R.string.info_times_minute);

}

 

35. 系统版本信息

public String[] getVersion(){

String[] version = {“null”,“null”,“null”,“null”};

String str1 = “/proc/version”;

String str2;

String[] arrayOfString;

try{

FileReader  localFileReader = new FileReader();

BufferedReaderlocalBufferedReader = new BufferedReader(localFIleReader , 8192);

str2 =localBufferedReader.readLine();

arrayOfString =str2.split(“\s+”);

version[0] =arrayOfString[2];//KernelVersion

localBufferedReader.close();

}catch(IOException e){

}

version[1] =Build.VERSION_RELEASE;//firmware version

version[2] =Build.MODEL;//model

Version[3] =Build.DISPLAY;//system version

return version;

}

 

36. CPU频率,CPU信息:/proc/cpuinfo和/poroc/stat

通过读取文件/proc/cpuinfo系统CPU的类型等多种信息。

读取/proc/stat 所有CPU活动的信息来计算CPU使用率

 

下面我们就来讲讲如何通过代码来获取CPU频率

importjava.io.BufferedReader;

importjava.io.FileNotFoundException;

importjava.io.FileReader;

importjava.io.IOException;

importjava.io.InputStream;

 

public class CpuManager{

//获取CPU最大频率(单位KHZ)

//“/system/bin/cat”命令行

//“/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq”存储最大频率文件的路径

public static StringgetMaxCpuFreq(){

String result = “”;

ProcessBilder cmd;

try{

String[]args={“/system/bin/cat”,”/sys/devices/system/cpu/cpu0/cpufreaq/cpuinfo_max_freq”};

cmd = newProcessBuilder(args);

Process process =cmd.start();

InputStream in =process.getInputStream();

byte[] re = new byte[24];

while(in.read(re) != -1){

result = result + newString(re);

}

in.close();

}catch(IOException ex){

ex.printStackTrace();

result = “N/A”;

}

Return result.trim();

}

//获取CPU最小的频率(KHZ)

public static StringgetMinCpuFreq()

{

String result = “”;

ProcessBilder cmd;

try{

String[] args = {“/system/bin/cat”,”/sys/devices/system/cpu/cpu0/cpufreaq/cpuinfo_min_freq”};

cmd = newProcessBuilder(args);

Process process =cmd.start();

InputStream in =process.getInputStream();

byte[] re = new byte[24];

while(in.read(re) != -1){

result = result + newString(re);

}

in.close();

}catch(IOException ex){

x.printStackTrace();

result = “N/A”;

}

return result.trim();

}

//实时获取CPU当前频率(单位KHZ)

public static StringgetCurCpuFreq(){

String result = “N/A”;

try{

FileReader fr = newFileReader(“/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq”);

BufferedReader br = newBufferedReader(fr);

String text =br.readLine();

Result = text.trim();

}catch(FileNotFoundExceptione){

e.printStackTrace();

}catch(IOException e){

e.printStackTrace();

}

return result;

}

//获取CPU名字

public static StringgetCpuName(){

try{

FileReader fr = newFileReader(“/proc/cpuinfo”);

BufferedReader br = newBuuferedReader(fr);

String text =br.readLine();

String[] array =text.split(“:\s+”, 2);

for(){

}

return array[1];

}catch(FileNotFoundExceptione){

e.printStackTrace();

}catch(IOException e){

e.printStackTrace();

}

return null;

}

}

 

37. 内存:/proc/meminfo

public voidgetTotalMemory(){

String str1 = “/proc/meminfo”;

String str2 = “”;

try{

FileReader fr = newFileReader(str1);

BufferedReader localBufferedReader= new BufferedReader(fr,8192);

while((str2 =localBufferedReader.readLine()) != null){

Log.i(TAG , “---” + str2);

}

}catch(IOException e){

 

}

}



5. 设置全屏

Android 设置全屏的方法:

A   在java中设置全屏设置

/**全屏设置,隐藏窗口所有装饰*/

requestWindowFeature(Window.FEATURE_NO_TITLE);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

package eoe.demo;

   

   

    import android.app.Activity;

    import android.os.Bundle;

    import android.view.Window;

    import android.view.WindowManager;

    public class OpenGl_Lesson1 extends Activity {

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    //无title

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    //全屏

    getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN,

    WindowManager.LayoutParams. FLAG_FULLSCREEN);

   

    setContentView(R.layout.main);

    }

}

    在这里要强调一点,设置全屏的俩段代码必须在setContentView(R.layout.main)之前,不然会报错。

 

 

B  在AndroidManifest.xml中配置

<activity

android:name=”xxxxActivity”

Android:theme=”@android:style/Theme.Black.NoTitleBar.Fullscreen”>

 <activity>

 

Android中全屏或者取消标题栏 先介绍去掉标题栏的方法:

第一种:也一般入门的时候经常使用的一种方法

requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏注意这句一定要写在setContentView()方法的前面,不然会报错的

第二种:在AndroidManifest.xml文件中定义

<application android:icon="@drawable/icon"        android:label="@string/app_name"        android:theme="@android:style/Theme.NoTitleBar">可以看出,这样写的话,整个应用都会去掉标题栏,如果只想去掉某一个Activity的标题栏的话,可以把这个属性加到activity标签里面

 

第三种:这种在一般的应用中不常用,就是在res/values目录下面新建一个style.xml的文件

例如:

 

 

<?xml version="1.0" encoding="UTF-8"?><resources>    <stylename="notitle">       <item name="android:windowNoTitle">true</item>    </style> </resources>

这样,我们就自定义了一个style,就相当于一个主题,然后在AndroidManifest.xml文件中定义

 

 

<application android:icon="@drawable/icon"        android:label="@string/app_name"        android:theme="@style/notitle">

这样也可以达到去掉标题栏的效果

 

三种去掉标题栏方法的总结

第一种,有的时候我们会看到,会先出现标题栏,然后再消失,因为我们只是在activity的oncreate方法中定义的,第二种相对第一种比较好一些,不会出现这种情况,第三种我个人感觉最好,这样把功能分开,便于维护和扩展

 

再介绍全屏的方法:

第一种

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

第二种

android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

第三种

application android:icon="@drawable/icon"        android:label="@string/app_name"       android:theme="@style/fullscreem"

 android 获取屏幕高度和宽度的方法 

我们需要获取Android手机或Pad的屏幕的物理尺寸,以便于界面的设计或是其他功能的实现。下面就介绍讲一讲如何获取屏幕的物理尺寸

    下面的代码即可获取屏幕的尺寸。
    在一个Activity的onCreate方法中,写入如下代码:
        DisplayMetrics metric = newDisplayMetrics();
       getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;    // 屏幕宽度(像素)
        int height = metric.heightPixels;  // 屏幕高度(像素)
        float density = metric.density;     // 屏幕密度(0.75 / 1.0 / 1.5)
        int densityDpi =metric.densityDpi;  // 屏幕密度DPI(120 / 160 / 240)

    但是,需要注意的是,在一个低密度的小屏手机上,仅靠上面的代码是不能获取正确的尺寸的。比如说,一部240x320像素的低密度手机,如果运行上述代 码,获取到的屏幕尺寸是320x427。因此,研究之后发现,若没有设定多分辨率支持的话,Android系统会将240x320的低密度(120)尺寸 转换为中等密度(160)对应的尺寸,这样的话就大大影响了程序的编码。所以,需要在工程的AndroidManifest.xml文件中,加入 supports-screens节点,具体的内容如下:
        <supports-screens
            android:smallScreens="true"
           android:normalScreens="true"
           android:largeScreens="true"
           android:resizeable="true"
           android:anyDensity="true" />
    这样的话,当前的Android程序就支持了多种分辨率,那么就可以得到正确的物理尺寸了。


------------------------------
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;
public class TextCanvasActivity extends Activity{
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(new MyView(this));
         
    //定义DisplayMetrics 对象  
      setContentView(R.layout.main);  
      DisplayMetrics  dm = newDisplayMetrics();  
      //取得窗口属性  
      getWindowManager().getDefaultDisplay().getMetrics(dm);  
      
      //窗口的宽度  
      int screenWidth = dm.widthPixels;  
      
      //窗口高度  
      int screenHeight = dm.heightPixels;        
     TextView textView =(TextView)findViewById(R.id.tv1);         
      textView.setText("屏幕宽度:" + screenWidth + "\n屏幕高度:" + screenHeight);
    }
}


6. 打开文件

27. 从res/raw打开文件

Public static String openFileFromRaw(Contextcontext) throws IOExcetion{

String content = “”;

InputStream inputStream =context.getResources().openRawResource(R.raw.provinces);

If(inputStream != null){

BufferedReader buffreader= new BufferedReader(new InputStreamReader(inputStream()));

String line;

//分行读取

try{

while((line =buffreader.readLine()) != null){

Content += line + “n”;

}

}catch(IOException e){

e.printStackTrace();

}

inputStream.close();

}

return content ;

}


38. 如何获取assets文件夹里的文件:

 

public StringgetFromAssets(String fileName){

try{

InputStreamReaderinputReader = new InputStreamReader(getResource().getAssets().open(fileName));

BufferedReader bufReader= new BufferedReader(inputReader);

String line = “”;

String Result = “”;

StringBuilder sb =StringBuffer();

While((line =bufReader.readLine()) != null)

sb.append(line);

               Return sb.toString();

}catch(Exception e){

e.printStackTrace();

}

return “”;

}

final String html =getFromAssets(“html/” + “xxx.html”);

 

另外教大家一个技巧:

可以把这个方法getFronAssets放在Activity里,然后所有Activity继承该Activity,是个不错的选择哦,

   public class BaseActivity extends Activity{

 

public StringgetFromAssets(String fileName){

try{

InputStreamReaderinputReader = new InputStreamReader(getResource().getAssets().open(fileName));

BufferedReader bufReader= new BufferedReader(inputReader);

String line = “”;

String Result = “”;

StringBuilder sb =StringBuffer();

While((line =bufReader.readLine()) != null)

sb.append(line);

                Return sb.toString();

}catch(Exception e){

e.printStackTrace();

}

return “”;

}

}

 

然后,想用就继承BaseActivity

public class Activtiy1extends BaseActivtiy{

  @Override

protected voidonCreate(Bundle savaedInstanceState){

final String html =getFromAssets(“html/” + “xxx.html”);

}

}


7.   Menu实现的两种方法

A.  第一种方法,通过Layout来添加静态菜单元素

<?xmlversion="1.0"encoding="utf-8"?> 
    <menu
xmlns:android="http://schemas.android.com/apk/res/android"
         <item
  
                android:id="@+id/previous"  
                android:title="@string/previous"  
                android:enabled="false" 
                  android:icon="@android:drawable/ic_media_previous"/> 
                <   !--these may not be available in next api(level > 3), so be carefull--> 
            <item  
                  android:id="@+id/play_pause"  
                  android:title="@string/play"  
             android:icon="@android:drawable/ic_media_play"/> 
            <item
  
                     android:id="@+id/next"  
                 android:title="@string/next"  
                 android:icon="@android:drawable/ic_menu_next"/> 
    </menu>

 

在Activity类中调用刚刚创建的Menu,首先将当前的Activity与指定的Menu XML相关联:
    @Override

    public booleanonCreateOptionsMenu(Menu menu) {

        super.onCreateOptionsMenu(menu);

        getMenuInflater().inflate(R.layout.menu_mainactivity, menu);

        return true;

    }

实现onOptionsItemSelected方法:(其目的是捕捉到菜单触发事件后,对具体触发的选项做出响   应,实际调用的函数包含在各自的case中)

@Override

public boolean onOptionsItemSelected(MenuItem item){

Switch(item.getItemId()){

case R.id.previous:

previous();//go to previous song in the playlist

return true;

case R.id.play_pause:

isPlaying()?pause():play();//toggle play /pause

return true;

case R.id.next:

next();//go to next song in the playlist

return true

 

}

return false ;//should never happen

}

 

最后可以通过onPrepareOptionMenu方法初始化Menu Items的属性:

@Override

Publicboolean onPrepareOptionsMenu(Menu menu){

//setplay_pause menu item look

if(isPlaying()){

menu.findItem(R.id.play_pause)

.setTitle(R.string.pause)

.setIcon(android.R.drawable.ic_media_pause);

}else {

menu.finaItem(R.id.play_pause)

.setTitle(R.string.pause)

.setIcon(android.R.drawable.ic_media_play);

 

}

return true;

}

 

 

B.   第二种方法,在Activity类中动态创建Menu。

首先需要定义Menu Item识别序号:
    public static finalMENU_PREVIOUS = 0; //no more R.ids
    public static finalMENU_PLAY_PAUSE = 1;
    public static finalMENU_NEXT = 2;

@Override

public booleanonCreateOptionsMenu(Menu menu) {

    menu.add(0, MENU_PREVIOUS, 0,R.string.previous)

      .setIcon(android.R.drawable.ic_media_previous);

    menu.add(0, MENU_PLAY_PAUSE, 0,R.string.play)

        .setIcon(android.R.drawable.ic_media_play);

   menu.add(0, MENU_NEXT, 0, R.string.next)

      .setIcon(android.R.drawable.ic_media_next);

    return true;

}

 

引用与第一种方法相同的方式来捕捉菜单的行为:

@Override

public booleanonOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

    case MENU_PREVIOUS:

        previous(); //go to previous song inthe playlist

        return true;

    case MENU_PLAY_PAUSE:

        isPlaying() ? pause() : play();//toggle play/pause

        return true;

    case MENU_NEXT:

        next(); //go to next song in theplaylist

        return true;

    }

    return false; //should never happen

}

 

对以上两种方法的补充

根据需要设置不同的Menu Item的属性:

menu.findItem(R.id.next).setEnable(false);

 

设置Menu Item从属关系(添加子父级别):

直接写在方法中:

menu.addSubMenu(R.id.repeat)

.add(R.id.one)

.add(R.id.all)

.add(R.id.none);

直接定义在XML Layout中:

<itemandroid:id="@+id/repeat"android:title="@string/repeat"
    <menu> 
           <item
android:id="@+id/one"android:title="@string/repeat_one"></item> 
           <item
android:id="@+id/all"android:title="@string/repeat_all"></item> 
            <item
android:id="@+id/none"android:title="@string/repeat_none"></item> 
    </menu>

————
这两种不同的方法实现的目的是一样的,而且不存在本质上的却别,具体根据实际情况(根据项目的结构需要或者团队开发标准)选择合适的方法来创建Menu。



0 0