若要学习创建绑定服务,请查看下篇Android服务二 创建绑定服务
启动服务
基于Service
package service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* 创建启动服务
*/
public class MyService extends Service {
@Override
public void onCreate() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return 0;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
}
}
String address = "https://img-blog.csdn.net/20160527205804527";
Intent intent = new Intent(this, MyService.class);
intent.putExtra("address", address);
startService(intent);
基于IntentService
package service;
import android.app.IntentService;
import android.content.Intent;
import HttpURL.HttpUtil;
/**
* 使用IntentService创建启动服务
*/
public class StartIntentService extends IntentService {
public StartIntentService() {
super("Download Picture");
}
@Override
protected void onHandleIntent(Intent intent) {
HttpUtil.downloadPicture(intent.getStringExtra("address"));
}
}
String address = "https://img-blog.csdn.net/20160527205804527";
Intent intent = new Intent(this, MyService.class);
intent.putExtra("address", address);
startService(intent);