public class ApkClientActivity extends Activity { static final String TAG = "ApkClientActivity"; Context mContext; DownloadManager manager ; DownloadCompleteReceiver receiver; Button downBtn ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mContext = this; //获取下载服务 manager =(DownloadManager)getSystemService(DOWNLOAD_SERVICE); receiver = new DownloadCompleteReceiver(); downBtn = (Button)findViewById(R.id.downBtn); downBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //建立下载请求 DownloadManager.Request down=new DownloadManager.Request (Uri.parse("http://192.168.0.66:8080/qqinput.apk")); //设置容许使用的网络类型,这里是移动网络和wifi均可以 down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI); //禁止发出通知,既后台下载 down.setShowRunningNotification(false); //不显示下载界面 down.setVisibleInDownloadsUi(false); //设置下载后文件存放的位置 down.setDestinationInExternalFilesDir(mContext, null, "qqinput.apk"); //将下载请求放入队列 manager.enqueue(down); } }); } //接受下载完成后的intent class DownloadCompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){ long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); Log.v(TAG," download complete! id : "+downId); Toast.makeText(context, intent.getAction()+"id : "+downId, Toast.LENGTH_SHORT).show(); } } } @Override protected void onResume() { registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); super.onResume(); } @Override protected void onDestroy() { if(receiver != null)unregisterReceiver(receiver); super.onDestroy(); } }
其中在设置 down.setShowRunningNotification(false);时,须要添加相应的权限: java
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" /> android
不然,会报错! 网络
AndroidManifest.xml文件内容以下: app
<strong><uses-sdk android:minSdkVersion="9" /></strong> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".ApkClientActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />