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" />