0
我有一個啓動我的DelayedMessageService的按鈕。該服務是非常簡單的服務,因爲它所做的只是計算用戶行進的距離。我想顯示行進的總距離,但問題是它沒有在我的MainAcitivy的TextView中顯示值。有人可以幫我解決這個問題。這裏是我的MainAcvity,服務和activity_main.xml中:TextView值未被服務更新 - Android GPS
MainActivity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
String distanceStr;
DelayedMessageService mDelayedMessageService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
watchMileage();
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DelayedMessageService.class);
intent.putExtra(DelayedMessageService.EXTRA_MESSAGE,
getResources().getString(R.string.button_response));
startService(intent);
}
});
}
private void watchMileage() {
final TextView distanceView = (TextView)findViewById(R.id.distance);
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
double distance = 0.0;
if (mDelayedMessageService != null) {
distance = mDelayedMessageService.getMiles();
}
distanceStr = String.format("%1$,.2f miles", distance);
distanceView.setText(distanceStr);
handler.postDelayed(this, 1000);
}
});
}
//Log.v("INOCRECTEA", distanceStr.toString());
}
// activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:id="@+id/button"
android:onClick="onClick"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView android:text=""
android:id="@+id/distance"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:singleLine="false"
android:textSize="50sp"/>
</LinearLayout>
謝謝@Renat Kaitmazov。我在哪裏使用mDelayedMessageService來爲此工作? 做我寫的watchMileage(內mDelayedMessageService =新DelayedMessageService()) 我想這個的代碼已經開始和iniatilise DelayedMessageService 意向意圖=新意圖(MainActivity.this,DelayedMessageService.class); intent.putExtra(DelayedMessageService.EXTRA_MESSAGE, getResources()。getString(R.string.button_response)); startService(intent); –
不可以。您不應該自己初始化服務。它是一個系統組件,系統本身爲你做了一切。在這裏你通過'startService()'方法使用了一個所謂的啓動服務。爲了獲得對服務的引用,您需要一個所謂的綁定服務。這裏是文檔https://developer.android.com/guide/components/bound-services.html –
還有一件事要注意。距離的實際計算僅在用戶單擊按鈕後觸發。在計算髮生之前,你可以在'onCreate()'裏面調用'watchMileage()'。當用戶點擊該按鈕時,您需要存儲結果以便下次顯示。 –