按钮onClick上的android服务语法错误

时间:2013-11-13 17:56:02

标签: android button service onclick

服务无法启动。它在按钮onclick下给我一个语法错误,以在startService(intService)启动服务;看起来服务被正确声明但是它在按钮的onclick下要求我将服务声明为变量

    public class Ship extends Activity implements View.OnClickListener {
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);
    Intent intService =  new Intent(Ship.this, Shipservice.class);
    intService.putExtra("TIME_IN_MINUTES", 1000);
    startService(intService);

}

// Handle button callback
@Override
public void onClick(View v) {
          Intent intService =  new Intent(Ship.this, Shipservice.class);
    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(new Intent(this, Shipservice.class));
        break;
    }
}
}

1 个答案:

答案 0 :(得分:1)

您在Intent中声明并初始化了onCreate变量。它是onCraete方法的局部变量。您应该将变量声明为类成员。