我試圖將用戶在活動類中選擇的值移動到服務類,以便服務運行那麼久。我知道我必須從微調器中獲取選定的值,將數學運算轉換爲幾分鐘,然後將該值傳遞給服務。它只是沒有爲我這樣做,我無法弄清楚爲什麼。我知道我不能將字符串值作爲int值傳遞,但是當我嘗試使值爲int時,它會給出語法錯誤以將其更改回字符串。將微調值從活動移動到服務android
活動
private static final String TAG = "ShipService";
public static final Integer[] TIME_IN_MINUTES = { 30, 45, 60, 180, 360 };
public MediaPlayer mediaPlayer;
public Handler handler = new Handler();
public Button button2;
public Button stop1;
public Spinner spinner2;
// Initialize the activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ship);
button2 = (Button) findViewById(R.id.btn2);
button2.setOnClickListener(this);
stop1 = (Button) findViewById(R.id.stop);
stop1.setOnClickListener(this);
spinner2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,
android.R.layout.simple_spinner_item, TIME_IN_MINUTES);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter);
int getTime = TIME_IN_MINUTES[spinner2.getSelectedItemPosition()];
long time = (getTime * 60000);***Gives error here***
Intent intService = new Intent(Ship.this, Shipservice.class);***Gives
error here***
intService.hasExtra(time);***Gives error here***
}
// Handle button callback
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn2:
Log.d(TAG, "onClick: starting service");
startService(intService);***Gives error here***
break;
case R.id.stop:
Log.d(TAG, "onClick: stopping srvice");
stopService(intService);***Gives error here***
break;
}
}
}
服務
public class Shipservice extends Service {
private static final String TAG = "Shipservice";
MediaPlayer myPlayer;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
myPlayer = MediaPlayer.create(this, R.raw.ocean_ship);
myPlayer.setLooping(false); // Set looping
}
@Override
public void onDestroy() {
Toast.makeText(this, "Ship Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
myPlayer.stop();
}
@Override
public void onStart(Intent intent, int startid) {
long time = 0;
if (intent.hasExtra(time)) {
time = intent.getLongExtra(time);
}
Toast.makeText(this, "Ship Service Started for" + time,
Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
myPlayer.start();
}
}
你可以請張貼您的stacktrace以獲得更好的支持 – Subbu
我無法使用當前存在的錯誤生成項目 – user2980560
分享您所看到的錯誤 – Subbu