【问题标题】:How to modify a layout of an activity in a service class in Android Studio如何在 Android Studio 中修改服务类中的活动布局
【发布时间】:2022-10-13 14:44:30
【问题描述】:

有一个活动(“MainActivity.java”)及其布局文件(“activity_main.xml”)。现在我有一个名为“MyService.java”的类,它扩展了“Service”,我想通过调用“onStartCommand”函数来更改“MyService.java”中“@+id/service_iv”的背景。如何将“MyService.java”中“MainActivity.java”的布局或视图作为对象获取并修改?谢谢!

我的服务.java

public class MyService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <Button
        android:id="@+id/service_off_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="turn off"
        android:layout_marginTop="100dp"/>

    <Button
        android:id="@+id/service_on_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:visibility="gone"
        android:text="turn on"/>

    <ImageView
        android:id="@+id/service_iv"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@mipmap/rabbit"/>

</LinearLayout>

【问题讨论】:

    标签: java android android-studio android-layout android-service


    【解决方案1】:

    您可以使用接口来调用主要活动中的方法。在主要活动中,您添加该方法并相应地更改图像视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多