Service启动和停止

Layout




    

创建一个MyService 继承 Service

public class MyService extends Service {

    private final String TAG = "123";

    public MyService(){
    }

    public IBinder onBind(Intent intent){
        //throw new UnsupportedOperationException("Not yet implemented");
        return null;
    }
    public void onCreate(){
        super.onCreate();
        Log.d(TAG,"-->onCreate");
    }

    public  int onStartCommand(Intent intent, int flags, int startId){
        Log.d(TAG,"-->onStartCommand");
        return super.onStartCommand(intent,flags,startId);
        //stopSelf();
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
    }
}

Activity

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private final String TAG = "123";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Button startService = (Button)findViewById(R.id.start_service);
        Button stopService = (Button)findViewById(R.id.stop_service);

        startService.setOnClickListener(MainActivity.this);
        stopService.setOnClickListener(MainActivity.this);
    }

    public void onClick(View v){
        switch (v.getId()){
            case R.id.start_service:
                Log.d(TAG,"-->activity start_service");
                Intent startIntent = new Intent(this,MyService.class);
                startService(startIntent);
                break;
            case R.id.stop_service:
                Log.d(TAG,"-->activity stop_sercie");
                Intent stopIntent = new Intent(this,MyService.class);
                stopService(stopIntent);
                break;

                default:
                    break;
        }
    }
}

注意:
1、 需要在AndroidManifest.xml文件注册

        

运行效果

image.png

你可能感兴趣的:(Service启动和停止)