我找不到任何关于如何在活动和服务之间发送消息的示例,我花了太多时间来搞清楚这一点.这是一个供其他人参考的示例项目.
此示例允许您直接启动或停止服务,并单独绑定/取消绑定服务.当服务运行时,它会以10 Hz的频率递增一个数字.如果活动绑定到Service,则会显示当前值.数据作为整数和字符串传输,因此您可以看到如何以两种不同的方式进行操作.活动中还有按钮将消息发送到服务(更改增量值).
截图:

AndroidManifest.xml中:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exampleservice"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService"></service>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
Run Code Online (Sandbox Code Playgroud)
水库\值\ strings.xml中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ExampleService</string>
<string name="service_started">Example Service started</string>
<string name="service_label">Example Service Label</string>
</resources>
Run Code Online (Sandbox Code Playgroud)
水库\布局\ main.xml中:
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service" >
</Button>
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Stop Service" >
</Button>
</RelativeLayout>
<RelativeLayout …Run Code Online (Sandbox Code Playgroud)