Android 常用代碼集合

來源:互聯網
上載者:User
這篇文章主要記錄一些我常用的一些程式碼片段,方便以後查閱,不斷更新中

 

1 呼叫瀏覽器 載入某網址

Uri uri = Uri.parse("http://www.baidu.com");<br />Intent it = new Intent(Intent.ACTION_VIEW, uri);<br />startActivity(it); 

 

2 Broadcast接收系統廣播的intent 監控應用程式套件組合的安裝 刪除

public class getBroadcast extends BroadcastReceiver {<br /> @Override<br /> public void onReceive(Context context, Intent intent) {</p><p> if(Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())){<br /> Toast.makeText(context, "有應用被添加", Toast.LENGTH_LONG).show();<br /> }<br /> else if(Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())){<br /> Toast.makeText(context, "有應用被刪除", Toast.LENGTH_LONG).show();<br /> }</p><p> else if(Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())){<br /> Toast.makeText(context, "有應用被替換", Toast.LENGTH_LONG).show();<br /> }</p><p> else if(Intent.ACTION_CAMERA_BUTTON.equals(intent.getAction())){<br /> Toast.makeText(context, "按鍵", Toast.LENGTH_LONG).show();<br /> }</p><p> }</p><p>} 

需要聲明的許可權如下AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><br /><manifest xmlns:android="http://schemas.android.com/apk/res/android"<br /> package="zy.Broadcast"<br /> android:versionCode="1"<br /> android:versionName="1.0"><br /> <application android:icon="@drawable/icon" android:label="@string/app_name"><br /> <activity android:name=".Broadcast"<br /> android:label="@string/app_name"><br /> <intent-filter><br /> <action android:name="android.intent.action.MAIN" /><br /> <category android:name="android.intent.category.LAUNCHER" /><br /> </intent-filter><br /> </activity><br /> <receiver android:name="getBroadcast" android:enabled="true" ><br /> <intent-filter><br /> <action android:name="android.intent.action.PACKAGE_ADDED"></action><br /> <!-- <action android:name="android.intent.action.PACKAGE_CHANGED"></action>--><br /> <action android:name="android.intent.action.PACKAGE_REMOVED"></action><br /> <action android:name="android.intent.action.PACKAGE_REPLACED"></action><br /> <!-- <action android:name="android.intent.action.PACKAGE_RESTARTED"></action>--><br /> <!-- <action android:name="android.intent.action.PACKAGE_INSTALL"></action>--><br /> <action android:name="android.intent.action.CAMERA_BUTTON"></action><br /> <data android:scheme="package"></data><br /> </intent-filter><br /></receiver><br /> </application><br /> <uses-sdk android:minSdkVersion="3" /></p><p></manifest>  

 

3 使用Toast輸出一個字串

public void DisplayToast(String str)<br /> {<br /> Toast.makeText(this,str,Toast.LENGTH_SHORT).show();<br /> }  

 

4 把一個字串寫進檔案

public void writefile(String str,String path )<br /> {<br /> File file;<br /> FileOutputStream out;<br /> try {<br /> //建立檔案<br /> file = new File(path);<br /> file.createNewFile();</p><p> //開啟檔案file的OutputStream<br /> out = new FileOutputStream(file);<br /> String infoToWrite = str;<br /> //將字串轉換成byte數組寫入檔案<br /> out.write(infoToWrite.getBytes());<br /> //關閉檔案file的OutputStream<br /> out.close();</p><p> } catch (IOException e) {<br /> //將出錯資訊列印到Logcat<br /> DisplayToast(e.toString());</p><p> }<br /> } 

 

5 把檔案內容讀出到一個字串

public String getinfo(String path)<br /> {<br /> File file;<br /> String str="";<br /> FileInputStream in;<br /> try{<br /> //開啟檔案file的InputStream<br /> file = new File(path);<br /> in = new FileInputStream(file);<br /> //將檔案內容全部讀入到byte數組<br /> int length = (int)file.length();<br /> byte[] temp = new byte[length];<br /> in.read(temp, 0, length);<br /> //將byte數組用UTF-8編碼並存入display字串中<br /> str = EncodingUtils.getString(temp,TEXT_ENCODING);<br /> //關閉檔案file的InputStream</p><p> in.close();<br /> }<br /> catch (IOException e) {</p><p> DisplayToast(e.toString());</p><p> }<br /> return str;<br /> } 

 

6 調用Android installer 安裝和卸載程式

Intent intent = new Intent(Intent.ACTION_VIEW);<br /> intent.setDataAndType(Uri.fromFile(new File("/sdcard/WorldCupTimer.apk")), "application/vnd.android.package-archive");<br /> startActivity(intent); //安裝 程式</p><p> Uri packageURI = Uri.parse("package:zy.dnh");<br /> Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);<br /> startActivity(uninstallIntent);//正常卸載程式 

7 結束某個進程

activityManager.restartPackage(packageName); 

 

8 設定預設來電鈴聲

 

 

public void setMyRingtone()<br /> {<br /> File k = new File("/sdcard/Shall We Talk.mp3"); // 設定歌曲路徑<br /> ContentValues values = new ContentValues();<br /> values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());<br /> values.put(MediaStore.MediaColumns.TITLE, "Shall We Talk");<br /> values.put(MediaStore.MediaColumns.SIZE, 8474325);<br /> values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");<br /> values.put(MediaStore.Audio.Media.ARTIST, "Madonna");<br /> values.put(MediaStore.Audio.Media.DURATION, 230);<br /> values.put(MediaStore.Audio.Media.IS_RINGTONE, true);<br /> values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);<br /> values.put(MediaStore.Audio.Media.IS_ALARM, false);<br /> values.put(MediaStore.Audio.Media.IS_MUSIC, false);<br /> // Insert it into the database<br /> Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());<br /> Uri newUri = this.getContentResolver().insert(uri, values);<br /> RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);<br /> ;} 

 

需要的許可權

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

 

類比HOME按鍵

Intent i=new Intent(Intent.ACTION_MAIN);<br />i.addCategory(Intent.CATEGORY_HOME);<br />i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<br />context.startActivity(i); 

 

9 開啟某一個連絡人

Intent intent=new Intent();<br />String data = "content://contacts/people/1";<br />Uri uri = Uri.parse(data); intent.setAction(Intent.ACTION_VIEW);<br />intent.setData(uri);<br />startActivity(intent); 

10 傳送檔案

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,                         "選擇藍芽用戶端"));}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.