Android 常用代碼集合 – Android移動開發技術文章_手機開發 Android移動開發教學課程

[java] <span style="font-family: Arial, Verdana, sans-serif; white-space: normal; background-color: rgb(255, 255, 255); ">這篇文章主要記錄一些我常用的一些代碼段,方便以後查閱,不斷更新中</span> 
<span style="font-family: Arial, Verdana, sans-serif; white-space: normal; background-color: rgb(255, 255, 255); ">這篇文章主要記錄一些我常用的一些代碼段,方便以後查閱,不斷更新中</span>

 

1 調用瀏覽器 載入某網址
[java] Uri uri = Uri.parse("http://www.baidu.com");         
Intent it = new Intent(Intent.ACTION_VIEW, uri);         
startActivity(it); 
Uri uri = Uri.parse("http://www.baidu.com");       
Intent it = new Intent(Intent.ACTION_VIEW, uri);       
startActivity(it);

 

2 Broadcast接收系統廣播的intent 監控應用程序包的安裝 刪除
[java] 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(); 
            } 
             
        } 
        

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

[c-sharp] <?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>  
<?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輸出一個字符串
[java] public void DisplayToast(String str) 
        { 
      Toast.makeText(this,str,Toast.LENGTH_SHORT).show(); 
        }  
public void DisplayToast(String str)
     {
   Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
     } 

 

4 把一個字符串寫進文件
[c-sharp] 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()); 
                  
             } 
        } 
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 把文件內容讀出到一個字符串
[java] 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; 
        } 
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 安裝和卸載程序
[java] 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);//正常卸載程序 
 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 結束某個進程
[c-sharp] activityManager.restartPackage(packageName); 
activityManager.restartPackage(packageName);

 

8 設置默認來電鈴聲
 

 

[c-sharp] 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); 
    ;} 
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);
    ;}

 

需要的權限

[c-sharp] <uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission> 
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

 

模擬HOME按鍵

[c-sharp] Intent i=new Intent(Intent.ACTION_MAIN); 
i.addCategory(Intent.CATEGORY_HOME); 
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
context.startActivity(i); 
Intent i=new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

 

9 打開某一個聯系人
[c-sharp] Intent intent=new Intent(); 
String data = "content://contacts/people/1"; 
Uri  uri = Uri.parse(data);          intent.setAction(Intent.ACTION_VIEW); 
intent.setData(uri); 
startActivity(intent); 
Intent intent=new Intent();
String data = "content://contacts/people/1";
Uri  uri = Uri.parse(data);    intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);

10 發送文件

[java] void sendFile(String path) 

    File mZipFile=new File(path); 
       Intent intent = new Intent(  
               Intent.ACTION_SEND);  
     //  intent.setClassName("com.android.bluetooth", "com.broadcom.bt.app.opp.OppLauncherActivity");  
     // intent.setClassName("com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity");  
       intent.putExtra("subject", mZipFile  
               .getName()); //   
        
       intent.putExtra("body", "content by chopsticks"); // 正文   
       intent.putExtra(Intent.EXTRA_STREAM,  
               Uri.fromFile(mZipFile)); // 添加附件,附件為file對象   
       if (mZipFile.getName().endsWith(".gz")) {  
           intent  
                   .setType("application/x-gzip"); // 如果是gz使用gzip的mime   
       } else if (mZipFile.getName().endsWith(  
               ".txt")) {  
           intent.setType("text/plain"); // 純文本則用text/plain的mime   
       } else if (mZipFile.getName().endsWith(  
               ".zip")) {  
           intent.setType("application/zip"); // 純文本則用text/plain的mime   
       } else {  
           intent  
                   .setType("application/octet-stream"); // 其他的均使用流當做二進制數據來發送   
       }  
      // startActivity(intent);  
       startActivity(  
               Intent.createChooser(intent,  
                       "選擇藍牙客戶端")); 

 void sendFile(String path)
 {
  File mZipFile=new File(path);
        Intent intent = new Intent(
                Intent.ACTION_SEND);
      //  intent.setClassName("com.android.bluetooth", "com.broadcom.bt.app.opp.OppLauncherActivity");
      // intent.setClassName("com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
        intent.putExtra("subject", mZipFile
                .getName()); //
       
        intent.putExtra("body", "content by chopsticks"); // 正文
        intent.putExtra(Intent.EXTRA_STREAM,
                Uri.fromFile(mZipFile)); // 添加附件,附件為file對象
        if (mZipFile.getName().endsWith(".gz")) {
            intent
                    .setType("application/x-gzip"); // 如果是gz使用gzip的mime
        } else if (mZipFile.getName().endsWith(
                ".txt")) {
            intent.setType("text/plain"); // 純文本則用text/plain的mime
        } else if (mZipFile.getName().endsWith(
                ".zip")) {
            intent.setType("application/zip"); // 純文本則用text/plain的mime
        } else {
            intent
                    .setType("application/octet-stream"); // 其他的均使用流當做二進制數據來發送
        }
       // startActivity(intent);
        startActivity(
                Intent.createChooser(intent,
                        "選擇藍牙客戶端"));
 }

 摘自 Zy的技術心得
 

發佈留言