我正在尝试从我的活动传递时间值,用户从微调器中选择它到服务,因此音频剪辑将播放该时间长度。到目前为止,我没有得到任何错误,但服务没有在请求的时间内播放。我没有发布logcat,因为我没有错误,我假设它是一些简单的我可以忽略。我想从活动中获取TIME_IN_MINUTES值并让服务播放那么久。
服务类
@Override
public void onStart(Intent intent, int startid) {
long time = 0;
if (intent.hasExtra("TIME_IN_MINUTESC")) {
time = intent.getLongExtra("TIME_IN_MINUTES", 1000);
}
Toast.makeText(this, "Ship Service Started for" + time,
Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
myPlayer.start();
}
}
活动类。
@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);
Intent intService = new Intent(Ship.this, Shipservice.class);
intService.putExtra("TIME_IN_MINUTES", 1000);
}
// Handle button callback
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn2:
Log.d(TAG, "onClick: starting service");
startService(new Intent(this, Shipservice.class));
break;
case R.id.stop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, Shipservice.class));
break;
}
答案 0 :(得分:1)
您还没有像这样开始Service
启动服务..
Intent intService = new Intent(Ship.this, Shipservice.class);
intService.putExtra("TIME_IN_MINUTES", 1000);
startService(intService);
在按钮onClick
中,您已经启动了服务但是Intent没有放置任何值。使用相同的Service
启动Intnet
或将数据添加到新Intnet
。
或者像这样简单地使用这种方法..
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn2:
Log.d(TAG, "onClick: starting service");
startService(intService);
break;
case R.id.stop:
Log.d(TAG, "onClick: stopping srvice");
stopService(intService);
break;
}
将intservice
作为私有变量..
答案 1 :(得分:0)
在活动课上试试
intent = new Intent(this, Service.class);
intent.putExtra("key", resultReceiver);
startService(intent);
}
private final ResultReceiver resultReceiver = new ResultReceiver(
new Handler()) {
@SuppressWarnings("unchecked")
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
progressBar.setVisibility(View.GONE);
//do functionality
};
};
在服务类中; -
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
// TODO Auto-generated constructor stub
//do functionality
Bundle bundle = new Bundle();
bundle.putSerializable("key", "data to send");
ResultReceiver receiver = intent.getParcelableExtra("key");
receiver.send(0, bundle);
}