android startService小例子

MainActivity.java类

package com.example.xservice; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; 
import android.view.View.OnClickListener; import android.widget.Button; 
public class MainActivity extends Activity {  private Button btn1,btn2;  @Override 
 protected void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main);   btn1=(Button)findViewById(R.id.btn1);   btn2=(Button)findViewById(R.id.btn2);   btn1.setOnClickListener(listener);   btn2.setOnClickListener(listener);  } 
 private OnClickListener listener=new OnClickListener() {   @Override 
  public void onClick(View v) { 
   Intent intent=new Intent(MainActivity.this,Myservice.class); //启动服务要先传递一个intent 
   switch (v.getId()) {    case R.id.btn1:     startService(intent);//启动服务     break; 


case R.id.btn2: 
    stopService(intent);//终止服务     break;    default:     break;    }   }  }; 
 @Override 
 public boolean onCreateOptionsMenu(Menu menu) {   getMenuInflater().inflate(R.menu.main, menu);   return true;  } 
}

你可能感兴趣的:(Java,AS)