gpt4 book ai didi

android - 我如何将字符串从 Activity 传递到 Android 中的服务?

转载 作者:太空狗 更新时间:2023-10-29 16:23:10 25 4
gpt4 key购买 nike

谁能告诉我如何将字符串或整数从 Activity 传递到服务。我试图传递一个整数 setpossition(4),但它不需要,启动时总是需要 0 Service 我不知道为什么我不能通过使用 Service 实例从 Activity 进行操作。

    public class MainMP3 extends Activity{
Button play,stop,prev,next,list;

static final String MEDIA_PATH = new String("/sdcard/");
Activity main_activity;

@Override
public void onCreate(Bundle savedInstanceState) {
main_activity=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.mp3interface);


play= (Button) findViewById(R.id.play);
stop= (Button) findViewById(R.id.stop);
prev= (Button) findViewById(R.id.prev);
next= (Button) findViewById(R.id.next);
list= (Button) findViewById(R.id.listofsongs);


play.setOnClickListener(new StartClick());

stop.setOnClickListener(new StopClick());

prev.setOnClickListener(new PullClick());





next.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {


}
});


list.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

Intent i= new Intent(MainMP3.this,songlist.class);
startActivity(i);

}
});

}




ServiceMP3 service = null;

ServiceConnection connection = new ServiceConnection() {

@Override // Called when connection is made
public void onServiceConnected(ComponentName cName, IBinder binder) {
service = ((ServiceMP3.SlowBinder)binder).getService();
}
@Override //
public void onServiceDisconnected(ComponentName cName) {
service = null;
}
};


private class StartClick implements View.OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(main_activity,ServiceMP3.class);
service.setposition(4);
main_activity.startService(intent);



}
}

private class StopClick implements View.OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(main_activity,ServiceMP3.class);
main_activity.stopService(intent);

}
}


private class PullClick implements View.OnClickListener {
public void onClick(View v) {



}
}


}

最佳答案

您必须在 Intent 中设置值并在启动服务时传递该 Intent ,您可以在 serivce onStartCommand(Intent intent, int flags, int startId) 中获取值。

这就是您必须通过 Intent 传递该整数的方式。

private class StartClick implements View.OnClickListener {      
public void onClick(View v) {
Intent intent = new Intent(main_activity,ServiceMP3.class);
intent.putExtra("position",4);
main_activity.startService(intent);

}
}

你可以得到值是这样的服务

 public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null){
int position = intent.getIntExtra("position", 0);
}
}

关于android - 我如何将字符串从 Activity 传递到 Android 中的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9370108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com