1. Activity 与 Service 的交互
Activity 和 Service 是 Android 应用的两个重要组成部分。Service 通常用于执行长期运行的后台任务,而 Activity 则用于与用户交互。它们之间的通信可以通过多种方式实现,如通过 Intent
、绑定服务等。
1.1 通过 Intent
进行通信
通过 Intent
启动和停止 Service,是 Activity 与 Service 交互的基本方式。
java
代码解读
复制代码
// 在 Activity 中启动 Service
Intent intent = new Intent(this, MyService.class);
intent.putExtra("key", "value");
startService(intent);
// 在 Activity 中停止 Service
stopService(intent);
在 Service 中可以通过 onStartCommand
方法处理传递的 Intent
。
java
代码解读
复制代码
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String value = intent.getStringExtra("key");
// 处理传递的数据
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
1.2 绑定 Service
绑定 Service 允许 Activity 与 Service 进行更复杂的交互,如调用 Service 中的方法、传递回调等。
java
代码解读
复制代码
// 在 Activity 中绑定 Service
private MyService mService;
private boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
MyService.LocalBinder binder = (MyService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
// 在 Service 中实现 Binder
public class MyService extends Service {
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// 自定义服务方法
public void performTask() {
// 执行任务
}
}
1.3 使用 Messenger 进行通信
可以使用 Messenger
进行进程间通信,适用于在不同进程中运行的 Activity 和 Service。
java
代码解读
复制代码
// 在 Service 中创建 Messenger
public class MyService extends Service {
private final Messenger mMessenger = new Messenger(new IncomingHandler());
private static class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SAY_HELLO:
// 处理消息
break;
default:
super.handleMessage(msg);
}
}
}
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
}
// 在 Activity 中绑定 Messenger
private Messenger mService = null;
private boolean mBound;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName className) {
mService = null;
mBound = false;
}
};
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
// 发送消息到 Service
if (mBound) {
Message msg = Message.obtain(null, MSG_SAY_HELLO, 0, 0);
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
2. Activity 与 BroadcastReceiver 的交互
BroadcastReceiver
用于监听和响应全局广播事件。Activity 可以发送和接收广播,与其他应用或系统组件进行通信。
2.1 发送广播
可以在 Activity 中发送广播。
java
代码解读
复制代码
// 发送标准广播
Intent intent = new Intent("com.example.ACTION_MY_BROADCAST");
intent.putExtra("key", "value");
sendBroadcast(intent);
// 发送有序广播
sendOrderedBroadcast(intent, null);
2.2 接收广播
可以在 AndroidManifest.xml 中声明 BroadcastReceiver,也可以在代码中动态注册。
xml
代码解读
复制代码
<!-- 在 AndroidManifest.xml 中声明 BroadcastReceiver -->
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.ACTION_MY_BROADCAST"/>
</intent-filter>
</receiver>
java
代码解读
复制代码
// 动态注册 BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String value = intent.getStringExtra("key");
// 处理广播
}
};
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter("com.example.ACTION_MY_BROADCAST");
registerReceiver(mReceiver, filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(mReceiver);
}
3. 深度链接和 App Links
深度链接和 App Links 允许应用响应外部链接,直接打开特定页面或功能。
3.1 深度链接
通过 Intent 过滤器在 AndroidManifest.xml 中声明支持的深度链接。
xml
代码解读
复制代码
<activity android:name=".MyActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:scheme="http"
android:host="www.example.com"
android:pathPrefix="/path"/>
</intent-filter>
</activity>
在 Activity 中处理深度链接。
java
代码解读
复制代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
if (uri != null) {
String path = uri.getPath();
// 处理深度链接
}
}
}
3.2 App Links
App Links 是更高级的深度链接,允许自动将外部链接定向到应用。需要在 AndroidManifest.xml 中配置。
xml
代码解读
复制代码
<activity android:name=".MyActivity">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:scheme="https"
android:host="www.example.com"
android:pathPrefix="/path"/>
</intent-filter>
</activity>
还需要在服务器上配置 Digital Asset Links 文件,以验证域名。
json
代码解读
复制代码
[
{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.example.myapp",
"sha256_cert_fingerprints": ["<YOUR_APP_CERTIFICATE_SHA256_FINGERPRINT>"]
}
}
]
4. 任务返回栈管理
任务返回栈(back stack)是管理用户导航历史的机制。在 Android 中,可以通过 Intent
标志和任务相关的属性来控制返回栈行为。
4.1 使用 FLAG_ACTIVITY_NEW_TASK
启动新任务
java
代码解读
复制代码
Intent intent = new Intent(this, NewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
4.2 使用 FLAG_ACTIVITY_CLEAR_TOP
清除返回栈中的 Activity
java
代码解读
复制代码
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
4.3 使用 FLAG_ACTIVITY_SINGLE_TOP
避免重复实例化 Activity
java
代码解读
复制代码
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
4.4 使用 TaskStackBuilder
构建返回栈
java
代码解读
复制代码
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(DetailActivity.class);
stackBuilder.addNextIntent(new Intent(this, DetailActivity.class));
stackBuilder.startActivities();
总结
通过对 Android Activity
的深入理解和灵活应用,可以实现丰富的用户体验和高效的应用程序。理解其生命周期、权限管理、数据传递、动画效果、导航和返回栈管理、资源管理、配置变更处理、视图层次
结构、性能优化、内存管理、测试、Service 交互、BroadcastReceiver 交互、深度链接与 App Links 以及 Fragment 的使用,是构建高质量 Android 应用的基础。在实际开发过程中,合理使用这些技术和设计模式,可以显著提升应用的稳定性、可维护性和用户体验。
作者:我说HelloWorld
链接:https://juejin.cn/post/7384617995874254885
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。