首页 > 代码库 > IntentSerive下载文件(2)

IntentSerive下载文件(2)

  • service下载文件,加入标签:

<service android:name=".MyService"></service>

添加相关权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

  • 相关代码:

public class MainActivity extends Activity {
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainactivity);
        button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MainActivity.this,MyIntentSerive.class);
                startService(intent);
            }
        });
    }

/**
* 使用IntentSerive下载图片 1、不用使用多线程 2、自动停止service
*
* @author LEI
*
*/
public class MyIntentSerive extends IntentService {
    private final String DOWNPATH = "http://www.baidu.com/img/bdlogo.png";

    public MyIntentSerive() {
        super("MyIntentSerive");
    }

    @Override
    public void onCreate() {

        // TODO Auto-generated method stub
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(Intent itent) {
        // TODO Auto-generated method stub
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(DOWNPATH);
        HttpResponse httpResponse = null;
        File file = Environment.getExternalStorageDirectory();
        FileOutputStream stream = null;
        try {
            httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                byte[] result = EntityUtils.toByteArray(httpResponse
                        .getEntity());
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    File newFile = new File(file, "abc.png");
                    stream = new FileOutputStream(newFile);
                    stream.write(result, 0, result.length);
                    Toast.makeText(MyIntentSerive.this, "下载文件完毕",
                            Toast.LENGTH_LONG).show();
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (stream != null)
                try {
                    stream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            httpClient.getConnectionManager().shutdown();
        }
    }
}


}

IntentSerive下载文件(2)