Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 開發常用程式碼片段整理

編輯:初階開發

日常開發中,有些功能幾乎每個專案都會用到。以下把常見的 Android 程式碼片段整理成一份速查表,需要的時候直接複製改一改就能用。

1. 用系統檢視器開啟 URI

Uri uri = Uri.parse("https://www.example.com");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);

2. 監聽應用程式的安裝、移除與替換

透過 BroadcastReceiver 攔截系統廣播,就能得知是否有 App 被安裝、刪除或更新。

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 需要在 receiver 中註冊 action,並加上 package scheme 的 data:

<receiver android:name="getBroadcast" android:enabled="true">
  <intent-filter>
    <action android:name="android.intent.action.PACKAGE_ADDED" />
    <action android:name="android.intent.action.PACKAGE_REMOVED" />
    <action android:name="android.intent.action.PACKAGE_REPLACED" />
    <action android:name="android.intent.action.CAMERA_BUTTON" />
    <data android:scheme="package" />
  </intent-filter>
</receiver>

3. 用 Toast 輸出字串

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

4. 把字串寫入檔案

public void writefile(String str, String path) {
    File file;
    FileOutputStream out;
    try {
        file = new File(path);
        file.createNewFile();          // 建立檔案
        out = new FileOutputStream(file);
        out.write(str.getBytes());     // 轉為 byte 陣列後寫入
        out.close();
    } catch (IOException e) {
        DisplayToast(e.toString());
    }
}

5. 把檔案內容讀成字串

public String getinfo(String path) {
    File file;
    String str = "";
    FileInputStream in;
    try {
        file = new File(path);
        in = new FileInputStream(file);
        int length = (int) file.length();
        byte[] temp = new byte[length];
        in.read(temp, 0, length);
        str = EncodingUtils.getString(temp, TEXT_ENCODING);
        in.close();
    } catch (IOException e) {
        DisplayToast(e.toString());
    }
    return str;
}

6. 呼叫系統安裝器安裝與解除安裝

// 安裝
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. 結束指定程式

activityManager.restartPackage(packageName);

8. 設定預設來電鈴聲

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);

    Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
    Uri newUri = this.getContentResolver().insert(uri, values);
    RingtoneManager.setActualDefaultRingtoneUri(this,
            RingtoneManager.TYPE_RINGTONE, newUri);
}

此功能需要以下權限:

<uses-permission android:name="android.permission.WRITE_SETTINGS" />
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved