Android Java 桌面功能示例
Android Java 桌面风格功能示例,包括文件对话框、消息框和系统集成
💻 消息框 java
🟢 simple
⭐⭐
使用AlertDialog显示警报对话框、确认对话框和输入对话框
⏱️ 20 min
🏷️ java, android, message box, ui
Prerequisites:
Basic Java knowledge, Android UI, AlertDialog
// Android Java Message Box Examples
// Using AlertDialog for various dialog types
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
// 1. Alert Dialog Builder
public class MessageBoxHelper {
private Activity activity;
public MessageBoxHelper(Activity activity) {
this.activity = activity;
}
// Simple alert dialog
public void showAlert(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.out.println("OK clicked");
}
});
builder.setCancelable(false);
builder.show();
}
// Alert with callback
public void showAlertWithCallback(String title, String message, final OnDialogClickListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onPositiveClick();
}
}
});
builder.show();
}
// Confirmation dialog
public void showConfirmation(String title, String message, final OnConfirmListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onConfirm(true);
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onConfirm(false);
}
}
});
builder.setCancelable(false);
builder.show();
}
// Three-button dialog
public void showThreeButtonDialog(String title, String message,
String positiveText, String negativeText, String neutralText,
final OnThreeButtonListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(positiveText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onPositiveClick();
}
}
});
builder.setNegativeButton(negativeText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onNegativeClick();
}
}
});
builder.setNeutralButton(neutralText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onNeutralClick();
}
}
});
builder.show();
}
// Input dialog
public void showInputDialog(String title, String hint, final OnInputListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
final EditText input = new EditText(activity);
input.setHint(hint);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onInput(input.getText().toString());
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
// Number input dialog
public void showNumberInputDialog(String title, String hint, final OnInputListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
final EditText input = new EditText(activity);
input.setHint(hint);
input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onInput(input.getText().toString());
}
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
// Multi-choice dialog
public void showMultiChoiceDialog(String title, final String[] items,
final boolean[] checkedItems,
final OnMultiChoiceListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
builder.setMultiChoiceItems(items, checkedItems,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkedItems[which] = isChecked;
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onItemsSelected(checkedItems);
}
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
// Single-choice dialog
public void showSingleChoiceDialog(String title, final String[] items, int checkedItem,
final OnSingleChoiceListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
builder.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onItemSelected(which);
}
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
// List dialog
public void showListDialog(String title, final String[] items, final OnItemClickListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onItemClick(which);
}
}
});
builder.show();
}
// Progress dialog
public void showProgressDialog(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
LayoutInflater inflater = activity.getLayoutInflater();
View dialogView = inflater.inflate(android.R.layout.simple_list_item_1, null);
builder.setView(dialogView);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.show();
}
// Custom dialog with layout
public void showCustomDialog(String title, int layoutRes, final OnCustomDialogListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
LayoutInflater inflater = activity.getLayoutInflater();
View dialogView = inflater.inflate(layoutRes, null);
builder.setTitle(title);
builder.setView(dialogView);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onCustomView(dialogView);
}
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
}
// 2. Dialog Callback Interfaces
interface OnDialogClickListener {
void onPositiveClick();
void onNegativeClick();
}
interface OnConfirmListener {
void onConfirm(boolean confirmed);
}
interface OnThreeButtonListener {
void onPositiveClick();
void onNegativeClick();
void onNeutralClick();
}
interface OnInputListener {
void onInput(String input);
}
interface OnMultiChoiceListener {
void onItemsSelected(boolean[] checkedItems);
}
interface OnSingleChoiceListener {
void onItemSelected(int which);
}
interface OnItemClickListener {
void onItemClick(int which);
}
interface OnCustomDialogListener {
void onCustomView(View customView);
}
// 3. Predefined Dialogs
public class CommonDialogs {
private Activity activity;
private MessageBoxHelper messageBox;
public CommonDialogs(Activity activity) {
this.activity = activity;
this.messageBox = new MessageBoxHelper(activity);
}
// Error dialog
public void showError(String message) {
messageBox.showAlert("Error", message);
}
// Warning dialog
public void showWarning(String message) {
messageBox.showAlert("Warning", message);
}
// Info dialog
public void showInfo(String message) {
messageBox.showAlert("Information", message);
}
// Success dialog
public void showSuccess(String message) {
messageBox.showAlert("Success", message);
}
// Confirm delete
public void confirmDelete(final OnConfirmListener listener) {
messageBox.showConfirmation("Confirm Delete",
"Are you sure you want to delete this item?",
listener);
}
// Confirm save
public void confirmSave(final OnConfirmListener listener) {
messageBox.showConfirmation("Confirm Save",
"Do you want to save changes?",
listener);
}
// Confirm exit
public void confirmExit(final OnConfirmListener listener) {
messageBox.showConfirmation("Confirm Exit",
"Are you sure you want to exit?",
listener);
}
// Input name
public void inputName(final OnInputListener listener) {
messageBox.showInputDialog("Enter Name", "Name", listener);
}
// Input email
public void inputEmail(final OnInputListener listener) {
messageBox.showInputDialog("Enter Email", "[email protected]", listener);
}
// Input password
public void inputPassword(final OnInputListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Enter Password");
final EditText input = new EditText(activity);
input.setHint("Password");
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onInput(input.getText().toString());
}
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
}
// 4. Toast Messages
public class ToastHelper {
private Activity activity;
public ToastHelper(Activity activity) {
this.activity = activity;
}
// Short toast
public void showShort(String message) {
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_SHORT).show();
}
// Long toast
public void showLong(String message) {
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show();
}
// Custom position toast
public void showAtPosition(String message, int gravity, int xOffset, int yOffset) {
android.widget.Toast toast = android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_SHORT);
toast.setGravity(gravity, xOffset, yOffset);
toast.show();
}
}
// 5. Snackbar Messages (requires design library)
public class SnackbarHelper {
private Activity activity;
public SnackbarHelper(Activity activity) {
this.activity = activity;
}
// Note: This requires com.google.android.material.snackbar.Snackbar
// For simplicity, we'll use Toast as fallback
public void show(String message) {
// In real implementation, use Snackbar
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show();
}
public void showWithAction(String message, String actionText) {
// In real implementation:
// Snackbar.make(view, message, Snackbar.LENGTH_LONG)
// .setAction(actionText, clickListener).show();
android.widget.Toast.makeText(activity, message + " (" + actionText + ")", android.widget.Toast.LENGTH_LONG).show();
}
}
// 6. Dialog with Custom View
public class CustomDialogHelper {
private Activity activity;
public CustomDialogHelper(Activity activity) {
this.activity = activity;
}
// Create dialog with username and password fields
public void showLoginDialog(final OnLoginListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Login");
LinearLayout layout = new LinearLayout(activity);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(50, 40, 50, 10);
final EditText usernameInput = new EditText(activity);
usernameInput.setHint("Username");
layout.addView(usernameInput);
final EditText passwordInput = new EditText(activity);
passwordInput.setHint("Password");
passwordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
layout.addView(passwordInput);
builder.setView(layout);
builder.setPositiveButton("Login", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String username = usernameInput.getText().toString();
String password = passwordInput.getText().toString();
if (listener != null) {
listener.onLogin(username, password);
}
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
}
interface OnLoginListener {
void onLogin(String username, String password);
}
// 7. Dialog Manager
public class DialogManager {
private Activity activity;
private MessageBoxHelper messageBox;
private CommonDialogs commonDialogs;
private ToastHelper toastHelper;
public DialogManager(Activity activity) {
this.activity = activity;
this.messageBox = new MessageBoxHelper(activity);
this.commonDialogs = new CommonDialogs(activity);
this.toastHelper = new ToastHelper(activity);
}
// Show error with toast
public void notifyError(String message) {
commonDialogs.showError(message);
toastHelper.showShort("Error occurred");
}
// Show success with toast
public void notifySuccess(String message) {
commonDialogs.showSuccess(message);
toastHelper.showShort("Operation successful");
}
// Show loading
public AlertDialog showLoadingDialog(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Please Wait");
builder.setMessage(message);
builder.setCancelable(false);
AlertDialog dialog = builder.show();
return dialog;
}
}
// Main demonstration
public class MessageBoxDemo {
public static void demonstrateMessageBoxes(Activity activity) {
System.out.println("=== Android Java Message Box Examples ===\n");
MessageBoxHelper messageBox = new MessageBoxHelper(activity);
CommonDialogs commonDialogs = new CommonDialogs(activity);
ToastHelper toastHelper = new ToastHelper(activity);
// 1. Simple alert
System.out.println("--- 1. Simple Alert Dialog ---");
messageBox.showAlert("Alert", "This is a simple alert message");
// 2. Confirmation dialog
System.out.println("\n--- 2. Confirmation Dialog ---");
commonDialogs.confirmDelete(new OnConfirmListener() {
@Override
public void onConfirm(boolean confirmed) {
if (confirmed) {
System.out.println("User confirmed deletion");
} else {
System.out.println("User cancelled deletion");
}
}
});
// 3. Input dialog
System.out.println("\n--- 3. Input Dialog ---");
messageBox.showInputDialog("Enter Text", "Type something here", new OnInputListener() {
@Override
public void onInput(String input) {
System.out.println("User entered: " + input);
}
});
// 4. List dialog
System.out.println("\n--- 4. List Dialog ---");
final String[] colors = {"Red", "Green", "Blue", "Yellow", "Black"};
messageBox.showListDialog("Choose a Color", colors, new OnItemClickListener() {
@Override
public void onItemClick(int which) {
System.out.println("Selected color: " + colors[which]);
}
});
// 5. Multi-choice dialog
System.out.println("\n--- 5. Multi-Choice Dialog ---");
final String[] toppings = {"Cheese", "Pepperoni", "Mushrooms", "Olives", "Onions"};
final boolean[] checkedItems = {false, false, false, false, false};
messageBox.showMultiChoiceDialog("Select Toppings", toppings, checkedItems,
new OnMultiChoiceListener() {
@Override
public void onItemsSelected(boolean[] checkedItems) {
System.out.print("Selected toppings: ");
for (int i = 0; i < checkedItems.length; i++) {
if (checkedItems[i]) {
System.out.print(toppings[i] + " ");
}
}
System.out.println();
}
});
// 6. Toast messages
System.out.println("\n--- 6. Toast Messages ---");
toastHelper.showShort("This is a short toast");
toastHelper.showLong("This is a long toast message");
// 7. Common dialogs
System.out.println("\n--- 7. Common Dialogs ---");
commonDialogs.showError("This is an error message");
commonDialogs.showWarning("This is a warning message");
commonDialogs.showInfo("This is an info message");
commonDialogs.showSuccess("Operation completed successfully!");
// 8. Custom dialog
System.out.println("\n--- 8. Custom Dialog ---");
CustomDialogHelper customDialog = new CustomDialogHelper(activity);
customDialog.showLoginDialog(new OnLoginListener() {
@Override
public void onLogin(String username, String password) {
System.out.println("Login attempt: " + username);
}
});
System.out.println("\n=== All Message Box Examples Completed ===");
}
}
💻 文件对话框 java
🟡 intermediate
⭐⭐⭐
使用Android Intent和存储访问框架打开/保存文件对话框
⏱️ 30 min
🏷️ java, android, file dialog, ui
Prerequisites:
Intermediate Java, Android Storage Access Framework, Intents
// Android Java File Dialog Examples
// Using Android Intent and Storage Access Framework for file selection
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.OpenableColumns;
import android.database.Cursor;
import android.webkit.MimeTypeMap;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
// 1. File Picker Helper
public class FilePickerHelper {
public static final int PICK_FILE_REQUEST = 1001;
public static final int PICK_DIRECTORY_REQUEST = 1002;
public static final int SAVE_FILE_REQUEST = 1003;
private Activity activity;
private OnFileSelectedListener fileSelectedListener;
public interface OnFileSelectedListener {
void onFileSelected(Uri fileUri);
void onFilesSelected(List<Uri> fileUris);
void onDirectorySelected(Uri directoryUri);
void onCancelled();
}
public FilePickerHelper(Activity activity) {
this.activity = activity;
}
public void setOnFileSelectedListener(OnFileSelectedListener listener) {
this.fileSelectedListener = listener;
}
// Open single file picker
public void openFilePicker(String mimeType) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(mimeType != null ? mimeType : "*/*");
activity.startActivityForResult(intent, PICK_FILE_REQUEST);
}
// Open multiple files picker
public void openMultipleFilesPicker(String mimeType) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(mimeType != null ? mimeType : "*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
activity.startActivityForResult(Intent.createChooser(intent, "Select files"), PICK_FILE_REQUEST);
}
// Open directory picker (API 21+)
public void openDirectoryPicker() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
activity.startActivityForResult(intent, PICK_DIRECTORY_REQUEST);
}
// Create file for saving
public void createFile(String mimeType, String fileName) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(mimeType != null ? mimeType : "text/plain");
intent.putExtra(Intent.EXTRA_TITLE, fileName);
activity.startActivityForResult(intent, SAVE_FILE_REQUEST);
}
// Handle activity result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
if (fileSelectedListener != null) {
fileSelectedListener.onCancelled();
}
return;
}
switch (requestCode) {
case PICK_FILE_REQUEST:
handleFilePickerResult(data);
break;
case PICK_DIRECTORY_REQUEST:
handleDirectoryPickerResult(data);
break;
case SAVE_FILE_REQUEST:
handleSaveFileResult(data);
break;
}
}
private void handleFilePickerResult(Intent data) {
if (data != null) {
// Check for multiple files
if (data.getClipData() != null) {
List<Uri> uris = new ArrayList<>();
int count = data.getClipData().getItemCount();
for (int i = 0; i < count; i++) {
uris.add(data.getClipData().getItemAt(i).getUri());
}
if (fileSelectedListener != null) {
fileSelectedListener.onFilesSelected(uris);
}
} else if (data.getData() != null) {
if (fileSelectedListener != null) {
fileSelectedListener.onFileSelected(data.getData());
}
}
}
}
private void handleDirectoryPickerResult(Intent data) {
if (data != null && data.getData() != null) {
Uri treeUri = data.getData();
// Persist permission
final int takeFlags = data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION;
activity.getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
if (fileSelectedListener != null) {
fileSelectedListener.onDirectorySelected(treeUri);
}
}
}
private void handleSaveFileResult(Intent data) {
if (data != null && data.getData() != null) {
if (fileSelectedListener != null) {
fileSelectedListener.onFileSelected(data.getData());
}
}
}
}
// 2. File Information
public class FileInfoExtractor {
private Activity activity;
public FileInfoExtractor(Activity activity) {
this.activity = activity;
}
public static class FileInfo {
public String name;
public long size;
public String mimeType;
public Uri uri;
public FileInfo(String name, long size, String mimeType, Uri uri) {
this.name = name;
this.size = size;
this.mimeType = mimeType;
this.uri = uri;
}
public void print() {
System.out.println("File: " + name);
System.out.println("Size: " + size + " bytes");
System.out.println("Type: " + mimeType);
}
}
// Get file info from URI
public FileInfo getFileInfo(Uri uri) {
String fileName = null;
long fileSize = 0;
String mimeType = activity.getContentResolver().getType(uri);
Cursor cursor = activity.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
if (nameIndex != -1) {
fileName = cursor.getString(nameIndex);
}
if (sizeIndex != -1) {
fileSize = cursor.getLong(sizeIndex);
}
cursor.close();
}
return new FileInfo(fileName, fileSize, mimeType, uri);
}
// Get file name
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = activity.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (index != -1) {
result = cursor.getString(index);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
if (result == null) {
result = uri.getLastPathSegment();
}
return result;
}
// Get file size
public long getFileSize(Uri uri) {
long size = 0;
Cursor cursor = activity.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndex(OpenableColumns.SIZE);
if (index != -1) {
size = cursor.getLong(index);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return size;
}
// Get MIME type
public String getMimeType(Uri uri) {
String mimeType = activity.getContentResolver().getType(uri);
if (mimeType == null) {
String extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
}
return mimeType;
}
}
// 3. File Reader and Writer
public class FileIO {
private Activity activity;
public FileIO(Activity activity) {
this.activity = activity;
}
// Read content from URI
public String readTextFromUri(Uri uri) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream = activity.getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
}
return stringBuilder.toString();
}
// Read bytes from URI
public byte[] readBytesFromUri(Uri uri) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
try (InputStream inputStream = activity.getContentResolver().openInputStream(uri)) {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
}
return byteBuffer.toByteArray();
}
// Write text to URI
public void writeTextToUri(Uri uri, String text) throws IOException {
try (OutputStream outputStream = activity.getContentResolver().openOutputStream(uri)) {
outputStream.write(text.getBytes());
}
}
// Write bytes to URI
public void writeBytesToUri(Uri uri, byte[] bytes) throws IOException {
try (OutputStream outputStream = activity.getContentResolver().openOutputStream(uri)) {
outputStream.write(bytes);
}
}
// Copy file from URI to app storage
public boolean copyToAppStorage(Uri sourceUri, String destinationFileName) {
try {
byte[] data = readBytesFromUri(sourceUri);
FileOutputStream outputStream = activity.openFileOutput(destinationFileName, Activity.MODE_PRIVATE);
outputStream.write(data);
outputStream.close();
System.out.println("File copied to: " + destinationFileName);
return true;
} catch (IOException e) {
System.out.println("Error copying file: " + e.getMessage());
return false;
}
}
}
// 4. File Type Filter
public class FileTypeFilter {
public static class MimeTypeFilter {
private String mimeType;
private String[] extensions;
public MimeTypeFilter(String mimeType, String[] extensions) {
this.mimeType = mimeType;
this.extensions = extensions;
}
public String getMimeType() {
return mimeType;
}
public String[] getExtensions() {
return extensions;
}
}
// Common file type filters
public static MimeTypeFilter imageFilter() {
return new MimeTypeFilter("image/*", new String[]{"jpg", "jpeg", "png", "gif", "bmp", "webp"});
}
public static MimeTypeFilter videoFilter() {
return new MimeTypeFilter("video/*", new String[]{"mp4", "avi", "mkv", "mov", "wmv"});
}
public static MimeTypeFilter audioFilter() {
return new MimeTypeFilter("audio/*", new String[]{"mp3", "wav", "ogg", "flac", "aac"});
}
public static MimeTypeFilter textFilter() {
return new MimeTypeFilter("text/*", new String[]{"txt", "csv", "json", "xml", "html", "md"});
}
public static MimeTypeFilter pdfFilter() {
return new MimeTypeFilter("application/pdf", new String[]{"pdf"});
}
public static MimeTypeFilter documentFilter() {
return new MimeTypeFilter("*/*", new String[]{"doc", "docx", "xls", "xlsx", "ppt", "pptx"});
}
// Create custom filter
public static MimeTypeFilter customFilter(String mimeType, String[] extensions) {
return new MimeTypeFilter(mimeType, extensions);
}
}
// 5. Advanced File Operations
public class AdvancedFileOperations {
private Activity activity;
public AdvancedFileOperations(Activity activity) {
this.activity = activity;
}
// List files in directory (from tree URI)
public List<Uri> listDirectoryFiles(Uri directoryUri) {
List<Uri> files = new ArrayList<>();
Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(directoryUri,
DocumentsContract.getTreeDocumentId(directoryUri));
Cursor cursor = activity.getContentResolver().query(
childrenUri,
new String[]{DocumentsContract.Document.COLUMN_DOCUMENT_ID},
null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String documentId = cursor.getString(0);
Uri fileUri = DocumentsContract.buildDocumentUriUsingTree(directoryUri, documentId);
files.add(fileUri);
}
cursor.close();
}
return files;
}
// Create subdirectory in directory
public Uri createSubdirectory(Uri parentUri, String directoryName) {
try {
Uri newDirUri = DocumentsContract.createDocument(
activity.getContentResolver(),
parentUri,
DocumentsContract.Document.MIME_TYPE_DIR,
directoryName);
return newDirUri;
} catch (Exception e) {
System.out.println("Error creating directory: " + e.getMessage());
return null;
}
}
// Delete file
public boolean deleteFile(Uri fileUri) {
try {
return DocumentsContract.deleteDocument(activity.getContentResolver(), fileUri);
} catch (Exception e) {
System.out.println("Error deleting file: " + e.getMessage());
return false;
}
}
// Rename file
public Uri renameFile(Uri fileUri, String newName) {
try {
return DocumentsContract.renameDocument(activity.getContentResolver(), fileUri, newName);
} catch (Exception e) {
System.out.println("Error renaming file: " + e.getMessage());
return null;
}
}
}
// 6. File Picker with Preview
public class FilePickerWithPreview {
private Activity activity;
private FilePickerHelper filePicker;
private FileInfoExtractor fileInfoExtractor;
private FileIO fileIO;
public FilePickerWithPreview(Activity activity) {
this.activity = activity;
this.filePicker = new FilePickerHelper(activity);
this.fileInfoExtractor = new FileInfoExtractor(activity);
this.fileIO = new FileIO(activity);
}
public void openImagePickerWithPreview() {
filePicker.setOnFileSelectedListener(new FilePickerHelper.OnFileSelectedListener() {
@Override
public void onFileSelected(Uri fileUri) {
FileInfoExtractor.FileInfo info = fileInfoExtractor.getFileInfo(fileUri);
info.print();
// Check if it's an image
if (info.mimeType != null && info.mimeType.startsWith("image/")) {
System.out.println("Image file selected - can display preview");
// Load and display preview image here
}
}
@Override
public void onFilesSelected(List<Uri> fileUris) {
System.out.println("Multiple files selected: " + fileUris.size());
for (Uri uri : fileUris) {
FileInfoExtractor.FileInfo info = fileInfoExtractor.getFileInfo(uri);
System.out.println(" - " + info.name);
}
}
@Override
public void onDirectorySelected(Uri directoryUri) {
System.out.println("Directory selected: " + directoryUri);
AdvancedFileOperations ops = new AdvancedFileOperations(activity);
List<Uri> files = ops.listDirectoryFiles(directoryUri);
System.out.println("Files in directory: " + files.size());
}
@Override
public void onCancelled() {
System.out.println("File selection cancelled");
}
});
filePicker.openFilePicker("image/*");
}
}
// 7. File Picker Configuration
public class FilePickerConfig {
public String mimeType = "*/*";
public boolean allowMultiple = false;
public String initialFileName = null;
public String title = null;
public static class Builder {
private FilePickerConfig config;
public Builder() {
config = new FilePickerConfig();
}
public Builder setMimeType(String mimeType) {
config.mimeType = mimeType;
return this;
}
public Builder allowMultiple(boolean allow) {
config.allowMultiple = allow;
return this;
}
public Builder setInitialFileName(String fileName) {
config.initialFileName = fileName;
return this;
}
public Builder setTitle(String title) {
config.title = title;
return this;
}
public FilePickerConfig build() {
return config;
}
}
public static Builder builder() {
return new Builder();
}
}
// Main demonstration
public class FileDialogDemo {
public static void demonstrateFileDialogs(Activity activity) {
System.out.println("=== Android Java File Dialog Examples ===\n");
// 1. Basic file picker
System.out.println("--- 1. Basic File Picker ---");
FilePickerHelper filePicker = new FilePickerHelper(activity);
filePicker.setOnFileSelectedListener(new FilePickerHelper.OnFileSelectedListener() {
@Override
public void onFileSelected(Uri fileUri) {
System.out.println("File selected: " + fileUri);
FileInfoExtractor extractor = new FileInfoExtractor(activity);
FileInfoExtractor.FileInfo info = extractor.getFileInfo(fileUri);
info.print();
}
@Override
public void onFilesSelected(List<Uri> fileUris) {
System.out.println("Multiple files selected: " + fileUris.size());
}
@Override
public void onDirectorySelected(Uri directoryUri) {
System.out.println("Directory selected: " + directoryUri);
}
@Override
public void onCancelled() {
System.out.println("File selection cancelled");
}
});
// Open text file picker
filePicker.openFilePicker("text/*");
// 2. Multiple files picker
System.out.println("\n--- 2. Multiple Files Picker ---");
filePicker.openMultipleFilesPicker("*/*");
// 3. Directory picker
System.out.println("\n--- 3. Directory Picker ---");
filePicker.openDirectoryPicker();
// 4. Create/save file
System.out.println("\n--- 4. Create/Save File ---");
filePicker.createFile("text/plain", "my_document.txt");
// 5. File type filters
System.out.println("\n--- 5. File Type Filters ---");
// Image picker
filePicker.openFilePicker(FileTypeFilter.imageFilter().getMimeType());
// Video picker
filePicker.openFilePicker(FileTypeFilter.videoFilter().getMimeType());
// PDF picker
filePicker.openFilePicker(FileTypeFilter.pdfFilter().getMimeType());
// 6. Advanced operations
System.out.println("\n--- 6. Advanced File Operations ---");
AdvancedFileOperations advancedOps = new AdvancedFileOperations(activity);
// These would be called after directory selection
// List<Uri> files = advancedOps.listDirectoryFiles(directoryUri);
// Uri newDir = advancedOps.createSubdirectory(directoryUri, "new_folder");
// boolean deleted = advancedOps.deleteFile(fileUri);
// Uri renamed = advancedOps.renameFile(fileUri, "new_name.txt");
// 7. File I/O
System.out.println("\n--- 7. File I/O ---");
FileIO fileIO = new FileIO(activity);
// Read from selected file
// try {
// String content = fileIO.readTextFromUri(fileUri);
// System.out.println("File content: " + content);
// } catch (IOException e) {
// System.out.println("Error reading file: " + e.getMessage());
// }
System.out.println("\n=== All File Dialog Examples Completed ===");
}
}
💻 系统集成 java
🟡 intermediate
⭐⭐⭐
系统托盘通知、状态栏和系统集成功能
⏱️ 30 min
🏷️ java, android, notification, system
Prerequisites:
Intermediate Java, NotificationManager, Android services
// Android Java System Integration Examples
// Using NotificationManager and system integration features
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.widget.RemoteViews;
// 1. Notification Helper
public class NotificationHelper {
private static final String CHANNEL_ID = "my_app_channel";
private static final String CHANNEL_NAME = "My App Notifications";
private static final String CHANNEL_DESC = "Notifications from My App";
private Context context;
private NotificationManager notificationManager;
public NotificationHelper(Context context) {
this.context = context;
this.notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
createNotificationChannel();
}
// Create notification channel (required for API 26+)
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
);
channel.setDescription(CHANNEL_DESC);
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{1000, 1000});
notificationManager.createNotificationChannel(channel);
}
}
// Simple notification
public void showSimpleNotification(int notificationId, String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
notificationManager.notify(notificationId, builder.build());
}
// Notification with tap action
public void showNotificationWithAction(int notificationId, String title, String message,
Class<?> targetActivity) {
Intent intent = new Intent(context, targetActivity);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
notificationManager.notify(notificationId, builder.build());
}
// Big text notification
public void showBigTextNotification(int notificationId, String title, String message, String bigText) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
notificationManager.notify(notificationId, builder.build());
}
// Notification with buttons
public void showNotificationWithButtons(int notificationId, String title, String message) {
// Yes action
Intent yesIntent = new Intent(context, NotificationReceiver.class);
yesIntent.setAction("YES_ACTION");
yesIntent.putExtra("notificationId", notificationId);
PendingIntent yesPendingIntent = PendingIntent.getBroadcast(
context,
0,
yesIntent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
// No action
Intent noIntent = new Intent(context, NotificationReceiver.class);
noIntent.setAction("NO_ACTION");
noIntent.putExtra("notificationId", notificationId);
PendingIntent noPendingIntent = PendingIntent.getBroadcast(
context,
1,
noIntent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.addAction(android.R.drawable.ic_menu_add, "Yes", yesPendingIntent)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, "No", noPendingIntent)
.setAutoCancel(true);
notificationManager.notify(notificationId, builder.build());
}
// Progress notification
public void showProgressNotification(int notificationId, String title, int progress) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(progress + "% completed")
.setProgress(100, progress, false)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true);
notificationManager.notify(notificationId, builder.build());
}
// Complete progress notification
public void completeProgressNotification(int notificationId, String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(message)
.setProgress(0, 0, false)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setOngoing(false)
.setAutoCancel(true);
notificationManager.notify(notificationId, builder.build());
}
// High priority notification
public void showHighPriorityNotification(int notificationId, String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setAutoCancel(true);
notificationManager.notify(notificationId, builder.build());
}
// Silent notification
public void showSilentNotification(int notificationId, String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setSilent(true)
.setAutoCancel(true);
notificationManager.notify(notificationId, builder.build());
}
// Cancel notification
public void cancelNotification(int notificationId) {
notificationManager.cancel(notificationId);
}
// Cancel all notifications
public void cancelAllNotifications() {
notificationManager.cancelAll();
}
}
// 2. Notification Broadcast Receiver
public class NotificationReceiver extends android.content.BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int notificationId = intent.getIntExtra("notificationId", 0);
if ("YES_ACTION".equals(action)) {
System.out.println("User clicked YES");
// Handle yes action
} else if ("NO_ACTION".equals(action)) {
System.out.println("User clicked NO");
// Handle no action
}
// Cancel notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
}
}
// 3. Notification Groups
public class NotificationGroupHelper {
private Context context;
private NotificationHelper notificationHelper;
private static final String GROUP_KEY = "my_app_group";
public NotificationGroupHelper(Context context) {
this.context = context;
this.notificationHelper = new NotificationHelper(context);
}
// Add notification to group
public void addNotificationToGroup(int notificationId, String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NotificationHelper.CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setGroup(GROUP_KEY)
.setAutoCancel(true);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(notificationId, builder.build());
}
// Create summary notification
public void createGroupSummary(int summaryId, String title, int messageCount) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NotificationHelper.CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(messageCount + " new messages")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setGroup(GROUP_KEY)
.setGroupSummary(true)
.setAutoCancel(true);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(summaryId, builder.build());
}
}
// 4. Status Bar Helper
public class StatusBarHelper {
private Context context;
public StatusBarHelper(Context context) {
this.context = context;
}
// Update status bar text (not directly supported, uses notification)
public void showStatusBarMessage(String message) {
NotificationHelper helper = new NotificationHelper(context);
helper.showSimpleNotification(1, "Status", message);
}
// Check if notifications are enabled
public boolean areNotificationsEnabled() {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return manager.areNotificationsEnabled();
}
return true;
}
// Open notification settings
public void openNotificationSettings() {
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
} else {
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(android.net.Uri.parse("package:" + context.getPackageName()));
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
// 5. System Settings Helper
public class SystemSettingsHelper {
private Context context;
public SystemSettingsHelper(Context context) {
this.context = context;
}
// Open WiFi settings
public void openWifiSettings() {
Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
// Open Bluetooth settings
public void openBluetoothSettings() {
Intent intent = new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
// Open application settings
public void openApplicationSettings() {
Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(android.net.Uri.parse("package:" + context.getPackageName()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
// Open system settings
public void openSystemSettings() {
Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
// Check if airplane mode is on
public boolean isAirplaneModeOn() {
return android.provider.Settings.System.getInt(
context.getContentResolver(),
android.provider.Settings.Global.AIRPLANE_MODE_ON,
0
) != 0;
}
}
// 6. Vibration Helper
public class VibrationHelper {
private Context context;
public VibrationHelper(Context context) {
this.context = context;
}
// Vibrate for given duration
public void vibrate(long milliseconds) {
android.os.Vibrator vibrator = (android.os.Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null && vibrator.hasVibrator()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(android.os.VibrationEffect.createOneShot(milliseconds, android.os.VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibrator.vibrate(milliseconds);
}
}
}
// Vibrate with pattern
public void vibratePattern(long[] pattern) {
android.os.Vibrator vibrator = (android.os.Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null && vibrator.hasVibrator()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(android.os.VibrationEffect.createWaveform(pattern, -1));
} else {
vibrator.vibrate(pattern, -1);
}
}
}
// Vibrate with repeating pattern
public void vibratePatternRepeat(long[] pattern, int repeat) {
android.os.Vibrator vibrator = (android.os.Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null && vibrator.hasVibrator()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(android.os.VibrationEffect.createWaveform(pattern, repeat));
} else {
vibrator.vibrate(pattern, repeat);
}
}
}
// Cancel vibration
public void cancelVibration() {
android.os.Vibrator vibrator = (android.os.Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null) {
vibrator.cancel();
}
}
// Check if device can vibrate
public boolean hasVibrator() {
android.os.Vibrator vibrator = (android.os.Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
return vibrator != null && vibrator.hasVibrator();
}
}
// 7. Sound Helper
public class SoundHelper {
private Context context;
public SoundHelper(Context context) {
this.context = context;
}
// Play notification sound
public void playNotificationSound() {
android.media.Ringtone ringtone = android.media.RingtoneManager.getRingtone(
context,
android.media.RingtoneManager.getDefaultUri(android.media.RingtoneManager.TYPE_NOTIFICATION)
);
ringtone.play();
}
// Play ringtone
public void playRingtone() {
android.media.Ringtone ringtone = android.media.RingtoneManager.getRingtone(
context,
android.media.RingtoneManager.getDefaultUri(android.media.RingtoneManager.TYPE_RINGTONE)
);
ringtone.play();
}
// Play alarm sound
public void playAlarmSound() {
android.media.Ringtone ringtone = android.media.RingtoneManager.getRingtone(
context,
android.media.RingtoneManager.getDefaultUri(android.media.RingtoneManager.TYPE_ALARM)
);
ringtone.play();
}
}
// Main demonstration
public class SystemIntegrationDemo {
public static void demonstrateSystemIntegration(Context context) {
System.out.println("=== Android Java System Integration Examples ===\n");
NotificationHelper notificationHelper = new NotificationHelper(context);
VibrationHelper vibrationHelper = new VibrationHelper(context);
SoundHelper soundHelper = new SoundHelper(context);
StatusBarHelper statusBarHelper = new StatusBarHelper(context);
SystemSettingsHelper settingsHelper = new SystemSettingsHelper(context);
// 1. Simple notification
System.out.println("--- 1. Simple Notification ---");
notificationHelper.showSimpleNotification(1, "My App", "This is a simple notification");
// 2. Big text notification
System.out.println("\n--- 2. Big Text Notification ---");
notificationHelper.showBigTextNotification(
2,
"New Message",
"You have received a new message",
"This is a longer text that will be expanded in the notification to show more details to the user."
);
// 3. Notification with buttons
System.out.println("\n--- 3. Notification with Buttons ---");
notificationHelper.showNotificationWithButtons(
3,
"Confirm Action",
"Do you want to proceed?"
);
// 4. Progress notification
System.out.println("\n--- 4. Progress Notification ---");
for (int i = 0; i <= 100; i += 20) {
notificationHelper.showProgressNotification(4, "Downloading", i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// Ignore
}
}
notificationHelper.completeProgressNotification(4, "Download Complete", "File downloaded successfully");
// 5. Vibration
System.out.println("\n--- 5. Vibration ---");
System.out.println("Has vibrator: " + vibrationHelper.hasVibrator());
vibrationHelper.vibrate(500);
// Vibrate pattern
long[] pattern = {0, 200, 100, 200, 100, 200};
vibrationHelper.vibratePattern(pattern);
// 6. Sound
System.out.println("\n--- 6. Sound ---");
soundHelper.playNotificationSound();
// 7. Status bar
System.out.println("\n--- 7. Status Bar ---");
System.out.println("Notifications enabled: " + statusBarHelper.areNotificationsEnabled());
statusBarHelper.showStatusBarMessage("Status bar message");
// 8. System settings
System.out.println("\n--- 8. System Settings ---");
System.out.println("Airplane mode: " + settingsHelper.isAirplaneModeOn());
// Uncomment to open settings
// settingsHelper.openWifiSettings();
// settingsHelper.openApplicationSettings();
// 9. Notification groups
System.out.println("\n--- 9. Notification Groups ---");
NotificationGroupHelper groupHelper = new NotificationGroupHelper(context);
groupHelper.addNotificationToGroup(10, "Message 1", "First message");
groupHelper.addNotificationToGroup(11, "Message 2", "Second message");
groupHelper.addNotificationToGroup(12, "Message 3", "Third message");
groupHelper.createGroupSummary(13, "New Messages", 3);
// 10. Cancel notifications
System.out.println("\n--- 10. Cancel Notifications ---");
// notificationHelper.cancelNotification(1);
// notificationHelper.cancelAllNotifications();
System.out.println("\n=== All System Integration Examples Completed ===");
}
}