Android后台服务无法返回当前启动的应用程序。JavaAndroid版本11。
创始人
2024-10-08 06:32:35
0

可以使用广播来解决这个问题,当应用程序在前台时,它将发送一个广播,然后在您的后台服务中接收该广播。在接收到广播后,您可以存储当前应用程序的包名,然后在需要时获取它。

以下是一个示例:

在应用程序中发送广播

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 发送广播到后台服务
        Intent intent = new Intent();
        intent.setAction("com.example.app.ForegroundApp");
        intent.putExtra("packageName", getPackageName());
        sendBroadcast(intent);
    }
}

在后台服务中接收广播

public class MyService extends Service {

    private String foregroundApp = "";

    private BroadcastReceiver foregroundAppReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 获取前台应用程序的包名
            foregroundApp = intent.getStringExtra("packageName");
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 注册接收前台应用程序广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.app.ForegroundApp");
        registerReceiver(foregroundAppReceiver, filter);

        // 执行后台任务
        // ...

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        // 注销广播接收器
        unregisterReceiver(foregroundAppReceiver);

        super.onDestroy();
    }
}

在需要时获取前台应用程序的包名

public void doSomething() {
    ActivityManager.RunningTaskInfo foregroundTaskInfo = activityManager.getRunningTasks(1).get(0);
    String foregroundApp = foregroundTaskInfo.topActivity.getPackageName();
}

相关内容

热门资讯

透视神器!pokemmo脚本(... 透视神器!pokemmo脚本(透视)开挂辅助神器(原来是真的挂)-哔哩哔哩1、用户打开应用后不用登录...
透视透视!aapoker怎么控... 透视透视!aapoker怎么控制牌,wepoker怎么设置房间,办法教程(竟然是真的挂)-哔哩哔哩1...
透视软件!pokemmo手机版... 透视软件!pokemmo手机版脚本免费,麻雀智能辅助软件,总是存在有挂(揭露2025新版)-哔哩哔哩...
透视苹果版本!wepoker透... 透视苹果版本!wepoker透视脚本免费使用视频(透视)开挂辅助软件(其实是真的挂)-哔哩哔哩1、w...
透视app!hhpoker有透... 透视app!hhpoker有透视功能吗,哈糖大菠萝有挂吗,手段教程(一贯真的是有挂)-哔哩哔哩hhp...
透视工具!htx矩阵wepok... 透视工具!htx矩阵wepoker辅助,兴动互娱辅助工具,真是存在有挂(教你2025新版教程)-哔哩...
透视实锤!哈糖大菠萝有没有挂(... 透视实锤!哈糖大菠萝有没有挂(透视)开挂辅助工具(真是有挂)-哔哩哔哩哈糖大菠萝有没有挂辅助器中分为...
透视透视挂!hhpoker可以... 透视透视挂!hhpoker可以开挂吗,wepoker新号好一点吗,模块教程(本来存在有挂)-哔哩哔哩...
透视系统!wepoker破解工... 透视系统!wepoker破解工具,神途免费辅助软件,一直真的是有挂(普及详细教程)-哔哩哔哩1、玩家...
透视开挂!德普之星辅助器app... 透视开挂!德普之星辅助器app(透视)开挂辅助工具(一直是有挂)-哔哩哔哩1、这是跨平台的德普之星辅...