1112 lines
32 KiB
Markdown
1112 lines
32 KiB
Markdown
# 核心API
|
||
|
||
## Activity API
|
||
|
||
Activity是Android应用的核心组件之一,代表用户界面中的一个屏幕。以下是Activity的核心API参考。
|
||
|
||
### 核心类和方法
|
||
|
||
#### 生命周期方法
|
||
|
||
```java
|
||
public class Activity extends ContextThemeWrapper
|
||
implements ComponentCallbacks2, OnCreateContextMenuListener,
|
||
Window.Callback, KeyEvent.Callback,
|
||
View.OnCreateContextMenuListener, Window.OnWindowDismissedCallback {
|
||
|
||
// 创建Activity
|
||
protected void onCreate(Bundle savedInstanceState);
|
||
|
||
// Activity可见但不可交互
|
||
protected void onStart();
|
||
|
||
// Activity可交互
|
||
protected void onResume();
|
||
|
||
// Activity失去焦点
|
||
protected void onPause();
|
||
|
||
// Activity不可见
|
||
protected void onStop();
|
||
|
||
// Activity销毁
|
||
protected void onDestroy();
|
||
|
||
// 从停止状态恢复
|
||
protected void onRestart();
|
||
}
|
||
```
|
||
|
||
#### 启动和导航
|
||
|
||
```java
|
||
// 启动Activity
|
||
public void startActivity(Intent intent);
|
||
public void startActivity(Intent intent, Bundle options);
|
||
public void startActivityForResult(Intent intent, int requestCode);
|
||
public void startActivityForResult(Intent intent, int requestCode, Bundle options);
|
||
|
||
// 结束Activity
|
||
public void finish();
|
||
public void finishActivity(int requestCode);
|
||
public void finishAffinity();
|
||
public void finishAndRemoveTask();
|
||
|
||
// 返回结果
|
||
public final void setResult(int resultCode);
|
||
public final void setResult(int resultCode, Intent data);
|
||
```
|
||
|
||
#### 状态保存和恢复
|
||
|
||
```java
|
||
// 保存状态
|
||
protected void onSaveInstanceState(Bundle outState);
|
||
protected void onRestoreInstanceState(Bundle savedInstanceState);
|
||
|
||
// 配置变更处理
|
||
public void onConfigurationChanged(Configuration newConfig);
|
||
```
|
||
|
||
#### 窗口和视图管理
|
||
|
||
```java
|
||
// 设置内容视图
|
||
public void setContentView(int layoutResID);
|
||
public void setContentView(View view);
|
||
public void setContentView(View view, ViewGroup.LayoutParams params);
|
||
|
||
// 获取视图
|
||
public <T extends View> T findViewById(int id);
|
||
public View findViewById(int id);
|
||
|
||
// 窗口管理
|
||
public Window getWindow();
|
||
public void requestWindowFeature(int featureId);
|
||
public void setRequestedOrientation(int requestedOrientation);
|
||
```
|
||
|
||
#### Intent和结果处理
|
||
|
||
```java
|
||
// 获取启动Intent
|
||
public Intent getIntent();
|
||
public void setIntent(Intent newIntent);
|
||
|
||
// 结果处理(已废弃,推荐使用Activity Result API)
|
||
@Deprecated
|
||
protected void onActivityResult(int requestCode, int resultCode, Intent data);
|
||
|
||
// 新的Activity Result API(推荐)
|
||
public final <I, O> ActivityResultLauncher<I> registerForActivityResult(
|
||
ActivityResultContract<I, O> contract,
|
||
ActivityResultCallback<O> callback
|
||
);
|
||
```
|
||
|
||
#### 权限管理
|
||
|
||
```java
|
||
// 请求权限
|
||
public void requestPermissions(String[] permissions, int requestCode);
|
||
|
||
// 权限结果回调
|
||
public void onRequestPermissionsResult(int requestCode,
|
||
String[] permissions,
|
||
int[] grantResults);
|
||
|
||
// 检查权限
|
||
public int checkSelfPermission(String permission);
|
||
public boolean shouldShowRequestPermissionRationale(String permission);
|
||
```
|
||
|
||
#### 系统服务
|
||
|
||
```java
|
||
// 获取系统服务
|
||
public Object getSystemService(String name);
|
||
|
||
// 常用服务
|
||
// - Context.WINDOW_SERVICE: WindowManager
|
||
// - Context.LAYOUT_INFLATER_SERVICE: LayoutInflater
|
||
// - Context.ACTIVITY_SERVICE: ActivityManager
|
||
// - Context.ALARM_SERVICE: AlarmManager
|
||
// - Context.NOTIFICATION_SERVICE: NotificationManager
|
||
```
|
||
|
||
#### Fragment管理
|
||
|
||
```java
|
||
// Fragment管理器
|
||
public FragmentManager getSupportFragmentManager();
|
||
public FragmentManager getFragmentManager(); // 已废弃
|
||
|
||
// Fragment事务
|
||
FragmentTransaction beginTransaction();
|
||
```
|
||
|
||
#### 菜单管理
|
||
|
||
```java
|
||
// 创建选项菜单
|
||
public boolean onCreateOptionsMenu(Menu menu);
|
||
public boolean onPrepareOptionsMenu(Menu menu);
|
||
public boolean onOptionsItemSelected(MenuItem item);
|
||
|
||
// 创建上下文菜单
|
||
public void onCreateContextMenu(ContextMenu menu, View v,
|
||
ContextMenu.ContextMenuInfo menuInfo);
|
||
public boolean onContextItemSelected(MenuItem item);
|
||
```
|
||
|
||
#### 转场动画
|
||
|
||
```java
|
||
// 设置转场动画
|
||
public void overridePendingTransition(int enterAnim, int exitAnim);
|
||
|
||
// 共享元素动画
|
||
public void startActivity(Intent intent, Bundle options);
|
||
```
|
||
|
||
### 常用常量
|
||
|
||
```java
|
||
// 结果码
|
||
public static final int RESULT_OK = -1;
|
||
public static final int RESULT_CANCELED = 0;
|
||
public static final int RESULT_FIRST_USER = 1;
|
||
|
||
// 请求码(自定义)
|
||
private static final int REQUEST_CODE_CAMERA = 1001;
|
||
private static final int REQUEST_CODE_GALLERY = 1002;
|
||
```
|
||
|
||
### Activity启动模式
|
||
|
||
```java
|
||
// AndroidManifest.xml中配置
|
||
// android:launchMode="standard" | "singleTop" | "singleTask" | "singleInstance"
|
||
|
||
// 通过Intent Flag控制
|
||
Intent.FLAG_ACTIVITY_NEW_TASK
|
||
Intent.FLAG_ACTIVITY_SINGLE_TOP
|
||
Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||
Intent.FLAG_ACTIVITY_CLEAR_TASK
|
||
```
|
||
|
||
### 最佳实践示例
|
||
|
||
```java
|
||
public class MainActivity extends AppCompatActivity {
|
||
private static final int REQUEST_CODE = 1001;
|
||
private ActivityResultLauncher<Intent> activityLauncher;
|
||
|
||
@Override
|
||
protected void onCreate(Bundle savedInstanceState) {
|
||
super.onCreate(savedInstanceState);
|
||
setContentView(R.layout.activity_main);
|
||
|
||
// 注册Activity Result Launcher
|
||
activityLauncher = registerForActivityResult(
|
||
new ActivityResultContracts.StartActivityForResult(),
|
||
result -> {
|
||
if (result.getResultCode() == RESULT_OK) {
|
||
Intent data = result.getData();
|
||
// 处理返回结果
|
||
}
|
||
}
|
||
);
|
||
}
|
||
|
||
private void startSecondActivity() {
|
||
Intent intent = new Intent(this, SecondActivity.class);
|
||
intent.putExtra("key", "value");
|
||
activityLauncher.launch(intent);
|
||
}
|
||
|
||
@Override
|
||
protected void onSaveInstanceState(Bundle outState) {
|
||
super.onSaveInstanceState(outState);
|
||
// 保存临时状态
|
||
outState.putString("key", "value");
|
||
}
|
||
|
||
@Override
|
||
protected void onRestoreInstanceState(Bundle savedInstanceState) {
|
||
super.onRestoreInstanceState(savedInstanceState);
|
||
// 恢复状态
|
||
String value = savedInstanceState.getString("key");
|
||
}
|
||
}
|
||
```
|
||
|
||
### 相关API链接
|
||
|
||
- [Activity官方文档](https://developer.android.com/reference/android/app/Activity)
|
||
- [AppCompatActivity文档](https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity)
|
||
- [Activity Result API](https://developer.android.com/training/basics/intents/result)
|
||
- [Activity生命周期指南](https://developer.android.com/guide/components/activities/activity-lifecycle)
|
||
## Service API
|
||
|
||
Service是Android应用的后台服务组件,用于执行长时间运行的操作。以下是Service的核心API参考。
|
||
|
||
### 核心类和方法
|
||
|
||
#### 生命周期方法
|
||
|
||
```java
|
||
public abstract class Service extends ContextWrapper implements ComponentCallbacks2 {
|
||
|
||
// Service创建
|
||
public void onCreate();
|
||
|
||
// 启动Service(startService)
|
||
public abstract IBinder onBind(Intent intent);
|
||
|
||
// 启动命令(startService)
|
||
public int onStartCommand(Intent intent, int flags, int startId);
|
||
|
||
// Service销毁
|
||
public void onDestroy();
|
||
|
||
// 解绑Service(bindService)
|
||
public boolean onUnbind(Intent intent);
|
||
|
||
// 重新绑定时调用
|
||
public void onRebind(Intent intent);
|
||
}
|
||
```
|
||
|
||
#### 启动和停止
|
||
|
||
```java
|
||
// 启动Service
|
||
public ComponentName startService(Intent service);
|
||
public int startForegroundService(Intent service); // Android 8.0+
|
||
|
||
// 停止Service
|
||
public boolean stopService(Intent name);
|
||
public final void stopSelf();
|
||
public final void stopSelf(int startId);
|
||
|
||
// 绑定Service
|
||
public boolean bindService(Intent service, ServiceConnection conn, int flags);
|
||
|
||
// 解绑Service
|
||
public void unbindService(ServiceConnection conn);
|
||
```
|
||
|
||
#### 前台Service
|
||
|
||
```java
|
||
// 启动前台Service
|
||
public final void startForeground(int id, Notification notification);
|
||
public final void startForeground(int id, Notification notification, int foregroundServiceType);
|
||
|
||
// 停止前台Service
|
||
public final void stopForeground(int flags);
|
||
public final void stopForeground(boolean removeNotification);
|
||
```
|
||
|
||
#### Service类型常量
|
||
|
||
```java
|
||
// onStartCommand返回值
|
||
public static final int START_STICKY = 1; // 系统重启后重新创建
|
||
public static final int START_NOT_STICKY = 2; // 系统重启后不重新创建
|
||
public static final int START_REDELIVER_INTENT = 3; // 重新传递Intent
|
||
|
||
// bindService标志
|
||
public static final int BIND_AUTO_CREATE = 0x0001;
|
||
public static final int BIND_DEBUG_UNBIND = 0x0002;
|
||
public static final int BIND_NOT_FOREGROUND = 0x0004;
|
||
public static final int BIND_ABOVE_CLIENT = 0x0008;
|
||
public static final int BIND_ALLOW_OOM_MANAGEMENT = 0x0010;
|
||
public static final int BIND_WAIVE_PRIORITY = 0x0020;
|
||
public static final int BIND_IMPORTANT = 0x0040;
|
||
public static final int BIND_ADJUST_WITH_ACTIVITY = 0x0080;
|
||
```
|
||
|
||
#### Service通信
|
||
|
||
```java
|
||
// Binder通信
|
||
public class LocalBinder extends Binder {
|
||
public MyService getService() {
|
||
return MyService.this;
|
||
}
|
||
}
|
||
|
||
// ServiceConnection
|
||
public interface ServiceConnection {
|
||
void onServiceConnected(ComponentName name, IBinder service);
|
||
void onServiceDisconnected(ComponentName name);
|
||
default void onBindingDied(ComponentName name) {}
|
||
default void onNullBinding(ComponentName name) {}
|
||
}
|
||
```
|
||
|
||
### 最佳实践示例
|
||
|
||
```java
|
||
// 普通Service
|
||
public class MyService extends Service {
|
||
@Override
|
||
public void onCreate() {
|
||
super.onCreate();
|
||
}
|
||
|
||
@Override
|
||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||
// 执行后台任务
|
||
return START_STICKY;
|
||
}
|
||
|
||
@Override
|
||
public IBinder onBind(Intent intent) {
|
||
return null; // 不绑定
|
||
}
|
||
|
||
@Override
|
||
public void onDestroy() {
|
||
super.onDestroy();
|
||
}
|
||
}
|
||
|
||
// 绑定Service
|
||
public class BoundService extends Service {
|
||
private LocalBinder binder = new LocalBinder();
|
||
|
||
public class LocalBinder extends Binder {
|
||
BoundService getService() {
|
||
return BoundService.this;
|
||
}
|
||
}
|
||
|
||
@Override
|
||
public IBinder onBind(Intent intent) {
|
||
return binder;
|
||
}
|
||
|
||
public void doWork() {
|
||
// Service方法
|
||
}
|
||
}
|
||
```
|
||
|
||
### 相关API链接
|
||
|
||
- [Service官方文档](https://developer.android.com/reference/android/app/Service)
|
||
- [Service生命周期指南](https://developer.android.com/guide/components/services)
|
||
- [前台Service指南](https://developer.android.com/guide/components/foreground-services)
|
||
|
||
---
|
||
|
||
## BroadcastReceiver API
|
||
|
||
BroadcastReceiver是Android应用的广播接收器组件,用于接收系统或应用发送的广播消息。以下是BroadcastReceiver的核心API参考。
|
||
|
||
### 核心类和方法
|
||
|
||
#### 接收广播
|
||
|
||
```java
|
||
public abstract class BroadcastReceiver {
|
||
|
||
// 接收广播
|
||
public abstract void onReceive(Context context, Intent intent);
|
||
|
||
// 设置结果码
|
||
public final void setResultCode(int code);
|
||
public final int getResultCode();
|
||
|
||
// 设置结果数据
|
||
public final void setResultData(String data);
|
||
public final String getResultData();
|
||
|
||
// 设置结果扩展数据
|
||
public final void setResultExtras(Bundle extras);
|
||
public final Bundle getResultExtras(boolean makeMap);
|
||
|
||
// 中止广播(有序广播)
|
||
public final void abortBroadcast();
|
||
|
||
// 检查是否已中止
|
||
public final boolean getAbortBroadcast();
|
||
}
|
||
```
|
||
|
||
#### 注册和注销
|
||
|
||
```java
|
||
// 动态注册
|
||
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter);
|
||
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
|
||
int flags);
|
||
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
|
||
String broadcastPermission, Handler scheduler);
|
||
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
|
||
String broadcastPermission, Handler scheduler,
|
||
int flags);
|
||
|
||
// 注销
|
||
public void unregisterReceiver(BroadcastReceiver receiver);
|
||
```
|
||
|
||
#### 发送广播
|
||
|
||
```java
|
||
// 发送普通广播
|
||
public void sendBroadcast(Intent intent);
|
||
public void sendBroadcast(Intent intent, String receiverPermission);
|
||
public void sendBroadcast(Intent intent, String receiverPermission, Bundle options);
|
||
|
||
// 发送有序广播
|
||
public void sendOrderedBroadcast(Intent intent, String receiverPermission);
|
||
public void sendOrderedBroadcast(Intent intent, String receiverPermission,
|
||
BroadcastReceiver resultReceiver, Handler scheduler,
|
||
int initialCode, String initialData, Bundle initialExtras);
|
||
|
||
// 发送粘性广播(已废弃)
|
||
@Deprecated
|
||
public void sendStickyBroadcast(Intent intent);
|
||
```
|
||
|
||
#### IntentFilter
|
||
|
||
```java
|
||
public class IntentFilter implements Parcelable {
|
||
|
||
// 添加Action
|
||
public final void addAction(String action);
|
||
|
||
// 添加Category
|
||
public final void addCategory(String category);
|
||
|
||
// 添加Data
|
||
public final void addDataScheme(String scheme);
|
||
public final void addDataAuthority(String host, String port);
|
||
public final void addDataPath(String path, int type);
|
||
|
||
// 设置优先级(有序广播)
|
||
public final void setPriority(int priority);
|
||
public final int getPriority();
|
||
}
|
||
```
|
||
|
||
### 常用系统广播
|
||
|
||
```java
|
||
// 系统广播Action
|
||
Intent.ACTION_BOOT_COMPLETED // 系统启动完成
|
||
Intent.ACTION_SCREEN_ON // 屏幕点亮
|
||
Intent.ACTION_SCREEN_OFF // 屏幕熄灭
|
||
Intent.ACTION_BATTERY_CHANGED // 电池状态变化
|
||
Intent.ACTION_POWER_CONNECTED // 电源连接
|
||
Intent.ACTION_POWER_DISCONNECTED // 电源断开
|
||
Intent.ACTION_TIMEZONE_CHANGED // 时区变化
|
||
Intent.ACTION_LOCALE_CHANGED // 语言变化
|
||
Intent.ACTION_PACKAGE_ADDED // 应用安装
|
||
Intent.ACTION_PACKAGE_REMOVED // 应用卸载
|
||
Intent.ACTION_PACKAGE_REPLACED // 应用更新
|
||
Intent.ACTION_MY_PACKAGE_REPLACED // 自己的应用更新
|
||
Intent.ACTION_PACKAGE_FULLY_REMOVED // 应用完全移除
|
||
```
|
||
|
||
### 最佳实践示例
|
||
|
||
```java
|
||
// 动态注册
|
||
public class MainActivity extends AppCompatActivity {
|
||
private BroadcastReceiver receiver = new BroadcastReceiver() {
|
||
@Override
|
||
public void onReceive(Context context, Intent intent) {
|
||
String action = intent.getAction();
|
||
if (Intent.ACTION_SCREEN_ON.equals(action)) {
|
||
// 处理屏幕点亮
|
||
}
|
||
}
|
||
};
|
||
|
||
@Override
|
||
protected void onCreate(Bundle savedInstanceState) {
|
||
super.onCreate(savedInstanceState);
|
||
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
|
||
registerReceiver(receiver, filter);
|
||
}
|
||
|
||
@Override
|
||
protected void onDestroy() {
|
||
super.onDestroy();
|
||
unregisterReceiver(receiver);
|
||
}
|
||
}
|
||
|
||
// 静态注册(AndroidManifest.xml)
|
||
// <receiver android:name=".MyReceiver">
|
||
// <intent-filter>
|
||
// <action android:name="android.intent.action.BOOT_COMPLETED" />
|
||
// </intent-filter>
|
||
// </receiver>
|
||
```
|
||
|
||
### 相关API链接
|
||
|
||
- [BroadcastReceiver官方文档](https://developer.android.com/reference/android/content/BroadcastReceiver)
|
||
- [广播系统指南](https://developer.android.com/guide/components/broadcasts)
|
||
- [系统广播列表](https://developer.android.com/guide/components/broadcasts#system-broadcasts)
|
||
|
||
---
|
||
|
||
## ContentProvider API
|
||
|
||
ContentProvider是Android应用的内容提供者组件,用于在不同应用间共享数据。以下是ContentProvider的核心API参考。
|
||
|
||
### 核心类和方法
|
||
|
||
#### ContentProvider
|
||
|
||
```java
|
||
public abstract class ContentProvider implements ComponentCallbacks2 {
|
||
|
||
// Provider创建
|
||
public boolean onCreate();
|
||
|
||
// 查询数据
|
||
public abstract Cursor query(Uri uri, String[] projection, String selection,
|
||
String[] selectionArgs, String sortOrder);
|
||
|
||
// 插入数据
|
||
public abstract Uri insert(Uri uri, ContentValues values);
|
||
|
||
// 更新数据
|
||
public abstract int update(Uri uri, ContentValues values, String selection,
|
||
String[] selectionArgs);
|
||
|
||
// 删除数据
|
||
public abstract int delete(Uri uri, String selection, String[] selectionArgs);
|
||
|
||
// 获取数据类型
|
||
public abstract String getType(Uri uri);
|
||
|
||
// 批量操作
|
||
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations);
|
||
|
||
// 打开文件
|
||
public ParcelFileDescriptor openFile(Uri uri, String mode);
|
||
public AssetFileDescriptor openAssetFile(Uri uri, String mode);
|
||
}
|
||
```
|
||
|
||
#### ContentResolver
|
||
|
||
```java
|
||
public abstract class ContentResolver {
|
||
|
||
// 查询数据
|
||
public final Cursor query(Uri uri, String[] projection, String selection,
|
||
String[] selectionArgs, String sortOrder);
|
||
|
||
// 插入数据
|
||
public final Uri insert(Uri uri, ContentValues values);
|
||
|
||
// 更新数据
|
||
public final int update(Uri uri, ContentValues values, String selection,
|
||
String[] selectionArgs);
|
||
|
||
// 删除数据
|
||
public final int delete(Uri uri, String selection, String[] selectionArgs);
|
||
|
||
// 批量操作
|
||
public ContentProviderResult[] applyBatch(String authority,
|
||
ArrayList<ContentProviderOperation> operations);
|
||
|
||
// 注册观察者
|
||
public void registerContentObserver(Uri uri, boolean notifyForDescendants,
|
||
ContentObserver observer);
|
||
|
||
// 注销观察者
|
||
public void unregisterContentObserver(ContentObserver observer);
|
||
|
||
// 通知数据变化
|
||
public void notifyChange(Uri uri, ContentObserver observer);
|
||
public void notifyChange(Uri uri, ContentObserver observer, int flags);
|
||
}
|
||
```
|
||
|
||
#### Uri和UriMatcher
|
||
|
||
```java
|
||
// Uri操作
|
||
public abstract class Uri implements Parcelable, Comparable<Uri> {
|
||
public static Uri parse(String uriString);
|
||
public String getScheme();
|
||
public String getAuthority();
|
||
public List<String> getPathSegments();
|
||
public String getLastPathSegment();
|
||
}
|
||
|
||
// UriMatcher匹配
|
||
public class UriMatcher {
|
||
public static final int NO_MATCH = -1;
|
||
|
||
public UriMatcher(int code);
|
||
public void addURI(String authority, String path, int code);
|
||
public int match(Uri uri);
|
||
}
|
||
|
||
// Uri构建
|
||
public class ContentUris {
|
||
public static Uri withAppendedId(Uri contentUri, long id);
|
||
public static long parseId(Uri contentUri);
|
||
}
|
||
```
|
||
|
||
#### ContentValues
|
||
|
||
```java
|
||
public class ContentValues implements Parcelable {
|
||
|
||
public ContentValues();
|
||
public ContentValues(int size);
|
||
public ContentValues(ContentValues from);
|
||
|
||
// 添加值
|
||
public void put(String key, String value);
|
||
public void put(String key, Integer value);
|
||
public void put(String key, Long value);
|
||
public void put(String key, Boolean value);
|
||
public void put(String key, Float value);
|
||
public void put(String key, Double value);
|
||
public void put(String key, byte[] value);
|
||
public void putNull(String key);
|
||
|
||
// 获取值
|
||
public Object get(String key);
|
||
public String getAsString(String key);
|
||
public Integer getAsInteger(String key);
|
||
public Long getAsLong(String key);
|
||
public Boolean getAsBoolean(String key);
|
||
public Float getAsFloat(String key);
|
||
public Double getAsDouble(String key);
|
||
public byte[] getAsByteArray(String key);
|
||
}
|
||
```
|
||
|
||
#### ContentObserver
|
||
|
||
```java
|
||
public abstract class ContentObserver {
|
||
|
||
public ContentObserver(Handler handler);
|
||
|
||
// 数据变化回调
|
||
public void onChange(boolean selfChange);
|
||
public void onChange(boolean selfChange, Uri uri);
|
||
public void onChange(boolean selfChange, Collection<Uri> uris, int flags);
|
||
}
|
||
```
|
||
|
||
### URI格式
|
||
|
||
```java
|
||
// URI格式:content://authority/path/id
|
||
// 示例
|
||
content://com.example.provider/user // 所有用户
|
||
content://com.example.provider/user/1 // ID为1的用户
|
||
content://com.example.provider/user/1/name // 用户1的name字段
|
||
```
|
||
|
||
### 最佳实践示例
|
||
|
||
```java
|
||
// 使用ContentResolver查询
|
||
Uri uri = Uri.parse("content://com.example.provider/user");
|
||
Cursor cursor = getContentResolver().query(
|
||
uri,
|
||
new String[]{"id", "name", "email"},
|
||
"age > ?",
|
||
new String[]{"18"},
|
||
"name ASC"
|
||
);
|
||
|
||
// 插入数据
|
||
ContentValues values = new ContentValues();
|
||
values.put("name", "John");
|
||
values.put("email", "john@example.com");
|
||
Uri newUri = getContentResolver().insert(uri, values);
|
||
|
||
// 注册观察者
|
||
ContentObserver observer = new ContentObserver(new Handler()) {
|
||
@Override
|
||
public void onChange(boolean selfChange, Uri uri) {
|
||
// 数据变化处理
|
||
}
|
||
};
|
||
getContentResolver().registerContentObserver(uri, true, observer);
|
||
```
|
||
|
||
### 相关API链接
|
||
|
||
- [ContentProvider官方文档](https://developer.android.com/reference/android/content/ContentProvider)
|
||
- [ContentProvider指南](https://developer.android.com/guide/topics/providers/content-providers)
|
||
- [ContentResolver文档](https://developer.android.com/reference/android/content/ContentResolver)
|
||
|
||
---
|
||
|
||
## Fragment API
|
||
|
||
Fragment是Android应用的UI片段组件,用于构建灵活的模块化界面。以下是Fragment的核心API参考。
|
||
|
||
### 核心类和方法
|
||
|
||
#### 生命周期方法
|
||
|
||
```java
|
||
public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListener {
|
||
|
||
// 附加到Activity
|
||
public void onAttach(Context context);
|
||
public void onAttach(Activity activity); // 已废弃
|
||
|
||
// Fragment创建
|
||
public void onCreate(Bundle savedInstanceState);
|
||
|
||
// 创建视图
|
||
public View onCreateView(LayoutInflater inflater, ViewGroup container,
|
||
Bundle savedInstanceState);
|
||
|
||
// Activity创建完成
|
||
public void onActivityCreated(Bundle savedInstanceState); // 已废弃
|
||
|
||
// Fragment可见
|
||
public void onStart();
|
||
public void onResume();
|
||
|
||
// Fragment不可见
|
||
public void onPause();
|
||
public void onStop();
|
||
|
||
// 销毁视图
|
||
public void onDestroyView();
|
||
|
||
// Fragment销毁
|
||
public void onDestroy();
|
||
|
||
// 从Activity分离
|
||
public void onDetach();
|
||
|
||
// 保存状态
|
||
public void onSaveInstanceState(Bundle outState);
|
||
|
||
// 配置变更
|
||
public void onConfigurationChanged(Configuration newConfig);
|
||
}
|
||
```
|
||
|
||
#### Fragment管理
|
||
|
||
```java
|
||
// FragmentManager
|
||
public abstract class FragmentManager {
|
||
|
||
// 开始事务
|
||
public abstract FragmentTransaction beginTransaction();
|
||
|
||
// 查找Fragment
|
||
public abstract Fragment findFragmentById(int id);
|
||
public abstract Fragment findFragmentByTag(String tag);
|
||
|
||
// 弹出回退栈
|
||
public abstract void popBackStack();
|
||
public abstract void popBackStack(String name, int flags);
|
||
public abstract void popBackStackImmediate();
|
||
|
||
// 执行待处理操作
|
||
public abstract boolean executePendingTransactions();
|
||
}
|
||
|
||
// FragmentTransaction
|
||
public abstract class FragmentTransaction {
|
||
|
||
// 添加Fragment
|
||
public abstract FragmentTransaction add(int containerViewId, Fragment fragment);
|
||
public abstract FragmentTransaction add(int containerViewId, Fragment fragment, String tag);
|
||
|
||
// 替换Fragment
|
||
public abstract FragmentTransaction replace(int containerViewId, Fragment fragment);
|
||
public abstract FragmentTransaction replace(int containerViewId, Fragment fragment, String tag);
|
||
|
||
// 移除Fragment
|
||
public abstract FragmentTransaction remove(Fragment fragment);
|
||
|
||
// 显示/隐藏Fragment
|
||
public abstract FragmentTransaction show(Fragment fragment);
|
||
public abstract FragmentTransaction hide(Fragment fragment);
|
||
|
||
// 添加到回退栈
|
||
public abstract FragmentTransaction addToBackStack(String name);
|
||
|
||
// 提交事务
|
||
public abstract int commit();
|
||
public abstract int commitAllowingStateLoss();
|
||
public abstract void commitNow();
|
||
public abstract void commitNowAllowingStateLoss();
|
||
|
||
// 设置动画
|
||
public abstract FragmentTransaction setCustomAnimations(int enter, int exit);
|
||
public abstract FragmentTransaction setCustomAnimations(int enter, int exit,
|
||
int popEnter, int popExit);
|
||
}
|
||
```
|
||
|
||
#### Fragment与Activity通信
|
||
|
||
```java
|
||
// 获取Activity
|
||
public final Activity getActivity();
|
||
public final Context getContext();
|
||
|
||
// 获取父Fragment
|
||
public final Fragment getParentFragment();
|
||
|
||
// 获取FragmentManager
|
||
public final FragmentManager getFragmentManager(); // 已废弃
|
||
public final FragmentManager getParentFragmentManager();
|
||
public final FragmentManager getChildFragmentManager();
|
||
|
||
// 设置参数
|
||
public void setArguments(Bundle args);
|
||
public Bundle getArguments();
|
||
|
||
// 获取目标Fragment(用于结果回调)
|
||
public Fragment getTargetFragment();
|
||
public int getTargetRequestCode();
|
||
public void setTargetFragment(Fragment fragment, int requestCode);
|
||
```
|
||
|
||
#### Fragment结果API
|
||
|
||
```java
|
||
// 设置结果
|
||
public void setResult(int resultCode);
|
||
public void setResult(int resultCode, Bundle result);
|
||
|
||
// 获取结果
|
||
public Bundle getResult();
|
||
public int getResultCode();
|
||
|
||
// 结果回调
|
||
public interface OnBackPressedDispatcherOwner {
|
||
OnBackPressedDispatcher getOnBackPressedDispatcher();
|
||
}
|
||
```
|
||
|
||
### 最佳实践示例
|
||
|
||
```java
|
||
// 创建Fragment
|
||
public class MyFragment extends Fragment {
|
||
@Override
|
||
public View onCreateView(LayoutInflater inflater, ViewGroup container,
|
||
Bundle savedInstanceState) {
|
||
return inflater.inflate(R.layout.fragment_my, container, false);
|
||
}
|
||
|
||
@Override
|
||
public void onViewCreated(View view, Bundle savedInstanceState) {
|
||
super.onViewCreated(view, savedInstanceState);
|
||
// 初始化视图
|
||
}
|
||
}
|
||
|
||
// 使用Fragment
|
||
FragmentManager fm = getSupportFragmentManager();
|
||
FragmentTransaction transaction = fm.beginTransaction();
|
||
transaction.replace(R.id.container, new MyFragment());
|
||
transaction.addToBackStack(null);
|
||
transaction.commit();
|
||
```
|
||
|
||
### 相关API链接
|
||
|
||
- [Fragment官方文档](https://developer.android.com/reference/androidx/fragment/app/Fragment)
|
||
- [Fragment指南](https://developer.android.com/guide/fragments)
|
||
- [FragmentManager文档](https://developer.android.com/reference/androidx/fragment/app/FragmentManager)
|
||
|
||
---
|
||
|
||
## Intent API
|
||
|
||
Intent是Android应用的意图组件,用于组件间通信和启动。以下是Intent的核心API参考。
|
||
|
||
### 核心类和方法
|
||
|
||
#### Intent构造
|
||
|
||
```java
|
||
public class Intent implements Parcelable, Cloneable {
|
||
|
||
// 构造方法
|
||
public Intent();
|
||
public Intent(Intent o);
|
||
public Intent(String action);
|
||
public Intent(String action, Uri uri);
|
||
public Intent(Context packageContext, Class<?> cls);
|
||
public Intent(String action, Uri uri, Context packageContext, Class<?> cls);
|
||
|
||
// 创建Intent
|
||
public static Intent createChooser(Intent target, CharSequence title);
|
||
}
|
||
```
|
||
|
||
#### 组件设置
|
||
|
||
```java
|
||
// 设置组件
|
||
public Intent setComponent(ComponentName component);
|
||
public Intent setClass(Context packageContext, Class<?> cls);
|
||
public Intent setClassName(Context packageContext, String className);
|
||
public Intent setClassName(String packageName, String className);
|
||
|
||
// 获取组件
|
||
public ComponentName getComponent();
|
||
public String getPackage();
|
||
public Intent setPackage(String packageName);
|
||
```
|
||
|
||
#### Action和Category
|
||
|
||
```java
|
||
// 设置Action
|
||
public Intent setAction(String action);
|
||
public String getAction();
|
||
|
||
// 添加Category
|
||
public Intent addCategory(String category);
|
||
public void removeCategory(String category);
|
||
public boolean hasCategory(String category);
|
||
public Set<String> getCategories();
|
||
|
||
// 常用Action
|
||
public static final String ACTION_VIEW = "android.intent.action.VIEW";
|
||
public static final String ACTION_SEND = "android.intent.action.SEND";
|
||
public static final String ACTION_EDIT = "android.intent.action.EDIT";
|
||
public static final String ACTION_DIAL = "android.intent.action.DIAL";
|
||
public static final String ACTION_CALL = "android.intent.action.CALL";
|
||
public static final String ACTION_PICK = "android.intent.action.PICK";
|
||
public static final String ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT";
|
||
|
||
// 常用Category
|
||
public static final String CATEGORY_DEFAULT = "android.intent.category.DEFAULT";
|
||
public static final String CATEGORY_LAUNCHER = "android.intent.category.LAUNCHER";
|
||
public static final String CATEGORY_BROWSABLE = "android.intent.category.BROWSABLE";
|
||
```
|
||
|
||
#### Data和Type
|
||
|
||
```java
|
||
// 设置Data
|
||
public Intent setData(Uri data);
|
||
public Intent setDataAndType(Uri data, String type);
|
||
public Uri getData();
|
||
|
||
// 设置Type
|
||
public Intent setType(String type);
|
||
public String getType();
|
||
public Intent setTypeAndNormalize(String type);
|
||
|
||
// 添加Data
|
||
public Intent addCategory(String category);
|
||
```
|
||
|
||
#### Extra数据
|
||
|
||
```java
|
||
// 添加Extra
|
||
public Intent putExtra(String name, String value);
|
||
public Intent putExtra(String name, int value);
|
||
public Intent putExtra(String name, long value);
|
||
public Intent putExtra(String name, boolean value);
|
||
public Intent putExtra(String name, float value);
|
||
public Intent putExtra(String name, double value);
|
||
public Intent putExtra(String name, byte[] value);
|
||
public Intent putExtra(String name, Parcelable value);
|
||
public Intent putExtra(String name, Serializable value);
|
||
public Intent putExtras(Intent src);
|
||
public Intent putExtras(Bundle extras);
|
||
|
||
// 获取Extra
|
||
public boolean hasExtra(String name);
|
||
public Object getExtra(String name);
|
||
public String getStringExtra(String name);
|
||
public int getIntExtra(String name, int defaultValue);
|
||
public long getLongExtra(String name, long defaultValue);
|
||
public boolean getBooleanExtra(String name, boolean defaultValue);
|
||
public float getFloatExtra(String name, float defaultValue);
|
||
public double getDoubleExtra(String name, double defaultValue);
|
||
public byte[] getByteArrayExtra(String name);
|
||
public <T extends Parcelable> T getParcelableExtra(String name);
|
||
public Serializable getSerializableExtra(String name);
|
||
public Bundle getExtras();
|
||
```
|
||
|
||
#### Flags
|
||
|
||
```java
|
||
// 设置Flags
|
||
public Intent setFlags(int flags);
|
||
public Intent addFlags(int flags);
|
||
public int getFlags();
|
||
|
||
// 常用Flags
|
||
public static final int FLAG_ACTIVITY_NEW_TASK = 0x10000000;
|
||
public static final int FLAG_ACTIVITY_CLEAR_TOP = 0x04000000;
|
||
public static final int FLAG_ACTIVITY_SINGLE_TOP = 0x20000000;
|
||
public static final int FLAG_ACTIVITY_CLEAR_TASK = 0x00008000;
|
||
public static final int FLAG_ACTIVITY_NO_HISTORY = 0x40000000;
|
||
public static final int FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS = 0x00800000;
|
||
public static final int FLAG_GRANT_READ_URI_PERMISSION = 0x00000001;
|
||
public static final int FLAG_GRANT_WRITE_URI_PERMISSION = 0x00000002;
|
||
```
|
||
|
||
#### Intent解析
|
||
|
||
```java
|
||
// 解析Intent
|
||
public static Intent parseUri(String uri, int flags);
|
||
public String toUri(int flags);
|
||
public String toString();
|
||
|
||
// 匹配Intent
|
||
public boolean filterEquals(Intent other);
|
||
public int filterHashCode();
|
||
```
|
||
|
||
### 最佳实践示例
|
||
|
||
```java
|
||
// 显式Intent
|
||
Intent intent = new Intent(this, MainActivity.class);
|
||
intent.putExtra("key", "value");
|
||
startActivity(intent);
|
||
|
||
// 隐式Intent
|
||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||
intent.setData(Uri.parse("https://www.example.com"));
|
||
startActivity(intent);
|
||
|
||
// 分享Intent
|
||
Intent shareIntent = new Intent(Intent.ACTION_SEND);
|
||
shareIntent.setType("text/plain");
|
||
shareIntent.putExtra(Intent.EXTRA_TEXT, "分享内容");
|
||
startActivity(Intent.createChooser(shareIntent, "选择分享方式"));
|
||
```
|
||
|
||
### 相关API链接
|
||
|
||
- [Intent官方文档](https://developer.android.com/reference/android/content/Intent)
|
||
- [Intent和Intent过滤器指南](https://developer.android.com/guide/components/intents-filters)
|
||
- [常见Intent操作](https://developer.android.com/guide/components/intents-common)
|