android 监听应用启动
时间: 2023-09-30 14:06:27 浏览: 52
要监听 Android 应用启动,可以使用 BroadcastReceiver 和 IntentFilter。具体步骤如下:
1. 创建一个 BroadcastReceiver 子类,实现 onReceive() 方法,该方法会在应用启动时被调用。
```java
public class AppInstallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {
String packageName = intent.getDataString().substring(8); // 获取应用包名
Log.d("AppInstallReceiver", "应用已安装:" + packageName);
} else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
String packageName = intent.getDataString().substring(8); // 获取应用包名
Log.d("AppInstallReceiver", "应用已卸载:" + packageName);
}
}
}
```
2. 在 AndroidManifest.xml 中注册 BroadcastReceiver,并添加 IntentFilter。
```xml
<receiver android:name=".AppInstallReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
```
3. 在 Activity 或 Service 中注册 BroadcastReceiver。
```java
AppInstallReceiver receiver = new AppInstallReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
registerReceiver(receiver, filter);
```
这样,当有应用被安装或卸载时,AppInstallReceiver 的 onReceive() 方法会被调用,并输出相应的日志信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)