package demo.lxiangjian.com.android_service;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//开启服务
public void start(View view) {
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("data","key");
//启动服务
startService(intent);
}
//停止服务
public void stop(View view) {
Intent intent = new Intent(MainActivity.this,MyService.class);
stopService(intent);
}
}
<pre name="code" class="java">package demo.lxiangjian.com.android_service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
Log.i("TAG", "-------onBind-----------");
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i("TAG", "-------onCreate-----------");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("TAG","-------onStartCommand-----------");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("TAG","-------onDestroy-----------");
super.onDestroy();
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:onClick="start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动服务" />
<Button
android:onClick="stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止服务" />
</LinearLayout>
在清单文件注册服务:
</activity><service android:name=".MyService"></service>