startService():一般用于在后台上传文件或者下载文件等,不跟其他组件通信,就算启动它的应用被销毁了,它仍然会欢快的在后台执行,直到完成任务的时候自刎(自己调用stopSelf())或者被其他人下黑手(调用stopService())。
1、activity_main.xml 里面只含有两个button,用于启动和停止服务
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.startservice.MainActivity" >
<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="StartService" />
<Button
android:id="@+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/start"
android:text="StopService" />
</RelativeLayout>
2、MyStartService.java
这里面什么也没有做,只是打印了一些log日志,onCreate()---->onStartCommand()---->onDestroy()
package com.example.startservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyStartService extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.i("info", "Service--->onCreate()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("info", "Service--->onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
Log.i("info", "Service--->onBind()");
return null;
}
@Override
public void onDestroy() {
Log.i("info", "Service--->onDestroy()");
super.onDestroy();
}
}
3、MainActivity.java
使用startService(intent)启动服务,服务还继续在后台运行;使用stopService(intent)停止服务,服务完全销毁了。
package com.example.startservice;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button start,stop;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button) findViewById(R.id.start);
stop=(Button) findViewById(R.id.stop);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
intent = new Intent(MainActivity.this, MyStartService.class);
startService(intent);
break;
case R.id.stop:
stopService(intent);
break;
}
}
}
启动结果:
点击StartService按钮:
再次点击StartService按钮,只会启动一次onCreate()方法
点击StopService按钮
代码:http://download.youkuaiyun.com/detail/yihuangol/9259163