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

    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);
       }
    }

10-07 20:04
查看更多