package com.evt.services;import java.io.FileDescriptor;import java.io.PrintWriter;import com.evt.MyApplication;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class ServicesUpload extends Service { // 进度条最大值 public static final int max_progress = 100; // 进度条进度值 private int progress = 0; public int getProgress() { return progress; } public void setProgress(int progress) { this.progress = progress; } /** * 模拟下载任务,每秒钟更新一次 */ public void startDownLoad() { Log.d(MyApplication.TAG, "开始下载"); new Thread(new Runnable() { @Override public void run() { while (progress < max_progress) { progress += 5; try { Thread.sleep(1000); Log.d(MyApplication.TAG, "线程睡眠一秒钟"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return new ServicesUploadBinder(); } public class ServicesUploadBinder extends Binder { public ServicesUpload getServicesUpload() { return ServicesUpload.this; } } @Override protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { // TODO Auto-generated method stub super.dump(fd, writer, args); } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); Log.d(MyApplication.TAG, "上传服务启动"); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Log.d(MyApplication.TAG, "上传服务销毁"); }
}
<!-- 上传服务 --> <service android:name="com.evt.services.ServicesUpload" android:enabled="true" android:exported="false" > <intent-filter> <action android:name="com.evt.services.ServicesUpload" /> </intent-filter> </service>
activity中:
private ServicesUpload servicesUpload; // 上传服务
Intent intent = new Intent("com.evt.services.ServicesUpload"); bindService(intent, conn, Context.BIND_AUTO_CREATE);
ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName arg0, IBinder arg1) { // TODO Auto-generated method stub servicesUpload = ((ServicesUpload.ServicesUploadBinder) arg1) .getServicesUpload(); } @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub } }; @Override protected void onDestroy() { // TODO Auto-generated method stub unbindService(conn); super.onDestroy(); }
调用方法:
servicesUpload.startDownLoad();