安卓service中上传文件

在service中写一个新线程用来上传文件,还没测试通不通。先把代码放上来~

public class WifiService extends Service {
    public static final String WIFISERVICE_ACTION = "com.smartapp.service.WifiService";
    private static final String TAG = "WIFI_SERVICE";
    private WifiManager mWifiManager;
    private List<ScanResult> mWifiList;
    private boolean isOpen = true;
    private Handler handler;
    private Runnable runnable;

    private BroadcastReceiver batteryBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.equals(intent.getAction(), intent.ACTION_BATTERY_CHANGED)) {
                int currentBattery = intent.getIntExtra("level", 0);
                int totalBattery = intent.getIntExtra("scale", 1);
                Log.v(TAG, "ACTION_BATTERY_CHANGED");
                Log.v(TAG, currentBattery * 100 / totalBattery + "%");
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        mWifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        Log.v(TAG, String.valueOf(mWifiManager.getWifiState()));
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryBroadcastReceiver, filter);
        openWifi();
        
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                startScanWifi();

                //每隔10s,扫描一次
               // handler.postDelayed(this, 10000);
            }
        };
        handler.postDelayed(runnable, 0);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeWifi();
        unregisterReceiver(batteryBroadcastReceiver);
        handler.removeCallbacks(runnable);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    	
    }

    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
            isOpen = false;
        }
    }

    public void closeWifi() {
        if (mWifiManager.isWifiEnabled() && !isOpen) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    public void startScanWifi() {
        Log.v(TAG, String.valueOf(System.currentTimeMillis()));
        mWifiManager.startScan();
        mWifiList = mWifiManager.getScanResults();
        Log.v(TAG, String.valueOf(System.currentTimeMillis()));
        Log.v(TAG, String.valueOf(mWifiList));
<span style="white-space:pre">	</span><span style="color:#ff9900;">//先生成一个文件存储在SD卡</span>
        final File file = new File(Environment.getExternalStorageDirectory().getPath()+ "/wifiList"+refFormatNowDate()+".txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            randomAccessFile.seek(file.length());
            randomAccessFile.writeBytes(refFormatNowDate());
            randomAccessFile.writeBytes("\r\n");
            randomAccessFile.writeBytes(String.valueOf(mWifiList));
            randomAccessFile.writeBytes("\r\n");
            randomAccessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        <span style="color:#ff9900;">//以下是新线程,用http上传文件</span>
        Thread t = new Thread(){
        	
        	private URL url;
        	private String content;

        	private int TIME_OUT = 60 * 1000;
        	private String PREFIX = "--";
        	private String LINE_END = "\r\n";
        	private String BOUNDARY = UUID.randomUUID().toString();
        	private String TAG = "UPLOAD";
        	private String CHARSET = "utf-8";
        	public  String backMsg = "";
        	private Handler handler;
        	private BufferedReader in;
        	
        	public void run(){
        	
        	
        	

        	try {
    			url = new URL("");<span style="color:#ff9900;">//此处写后台url代码</span>

    			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    			conn.setReadTimeout(TIME_OUT);
    			conn.setConnectTimeout(TIME_OUT);
    			conn.setRequestMethod("POST");
    			conn.setRequestProperty("Content-Type", "multipart/form-data"
    					+ ";boundary=" + BOUNDARY);
    			Log.v("yizhuang", "BOUNDARY: " + BOUNDARY);
    			// conn.setRequestProperty("accept", "*/*");
    			conn.setRequestProperty("connection", "Keep-Alive");
    			conn.setRequestProperty("user-agent",
    					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
    			conn.setRequestProperty("Charsert", "UTF-8");
    			// conn.setUseCaches(true);
    			// System.setProperty("http.keepAlive", "false");
    			conn.setDoOutput(true);
    			conn.setDoInput(true);

    			conn.setDoOutput(true);
    			conn.setDoInput(true);

    			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
    			StringBuffer sb = new StringBuffer();
    			sb.append(PREFIX);
    			sb.append(BOUNDARY);
    			sb.append(LINE_END);
    			sb.append("Content-Disposition: form-data; name=\"" + content
    					+ "\"; filename=\"" + file.getName() + "\"" + LINE_END);
    			sb.append("Content-Type: application/octet-stream; charset="
    					+ CHARSET + LINE_END);
    			sb.append(LINE_END);
    			dos.write(sb.toString().getBytes());
    			Log.e(TAG, sb.toString());
    			InputStream is = new FileInputStream(file);<span style="color:#ff9900;">//将file上传到后台</span>
    			byte[] buffer = new byte[1024];
    			int len = 0;
    			while ((len = is.read(buffer)) != -1) {
    				dos.write(buffer, 0, len);
    			}
    			dos.write(LINE_END.getBytes());
    			Log.w(TAG, "dos.write pic");
    			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
    					.getBytes();
    			dos.write(end_data);
    			Log.w(TAG, "dos.write end data");
    			dos.flush();
    			Log.w(TAG, "flush");
    			Log.e(TAG, "request success");

    			in = new BufferedReader(
    					new InputStreamReader(conn.getInputStream()));
    			String line;
    			while ((line = in.readLine()) != null) {
    				backMsg = line;
    			}

    			if (backMsg.equals("success")) {
    				//file.delete();
    			}

    			Log.e("wifi", "reading:" + backMsg);
    			is.close();
    			dos.close();
    			in.close();

    			Message msg = new Message();
    			msg.what = 0x777;
    			msg.obj = backMsg;
    			handler.sendMessage(msg);

    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        	}
        };
        t.start();
        
        
    }
    public String refFormatNowDate() {
    	  Date nowTime = new Date(System.currentTimeMillis());
    	  SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    	  String retStrFormatNowDate = sdFormatter.format(nowTime);
    	  return retStrFormatNowDate;
    	}
  
}


猜你喜欢

转载自blog.csdn.net/ulike_mfy/article/details/52483842
今日推荐