![](/img/trans.png)
[英]how to call Strings in mainactivity.xml from Strings.xml file
[英]Android Studio - How to send data from MainActivity.xml to Service?
在創建應用程序時,我遇到了一個問題。 我有很多復選框,每個復選框都負責打開/關閉特定的聲音。 我使用 MediaPlayer 提供服務,但我不知道如何將 MainActivity.xml 中的復選框值“選中”發送到服務。
主活動.xml:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class));
CheckBox soundCheckBox = (CheckBox)findViewById(R.id.sound1cb);
CheckBox sound2CheckBox = (CheckBox)findViewById(R.id.sound2cb);
CheckBox sound3CheckBox = (CheckBox)findViewById(R.id.sound3cb);
CheckBox sound4CheckBox = (CheckBox)findViewById(R.id.sound4cb);
CheckBox sound5CheckBox = (CheckBox)findViewById(R.id.sound5cb);
根據意圖添加您的數據,
intent.putExtra("key" , "value");
因為您想從 Activity 到 Service(可能還有其他方式)進行通信,所以您需要使用BoundService 。 這將使您在 Activity 中獲得服務 Binder,然后調用服務方法......這是很大的簡化,但我認為深入研究將解決您的問題。
你必須先把這條線激活
startService(new Intent(activity, SampleService.class).putExtra("key", "value"))
並將此行添加到服務以在 onCreate 或 onStartCommand 方法中獲取數據
intent.getStringExtra("key")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.