我正在尝试将用户在活动类中选择的值移动到服务类,以便服务将运行那么长时间。我知道我必须从微调器中获取选定的值,进行数学运算以将毫秒转换为分钟,然后将该值传递给服务。它只是不适合我的方式,我不知道为什么。我知道我不能将字符串值作为 int 值传递,但是当我尝试将值设为 int 时,它会出现语法错误以改回字符串。
活动
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();
}
}