【发布时间】: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