2016-05-16 48 views
1
public void getServerApk() { 
Uri mUri = Uri.parse(Url); //Uri == my server domain 
DownloadManager.Request r = new DownloadManager.Request(mUrl); 
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "my.apk"); 
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 
dm.enqueue(r); 

,並在下載完成my.apk ......如果我的APK服務器上存在當APK沒有我的服務器上不存在於Android

private BroadcastReceiver apkReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     try { 
     String InstallCommand,RebootCommand; 

     InstallCommand = "pm install -r /sdcard/Download/my.apk"; 
     RebootCommand = "reboot"; 
     Process Insproc = Runtime.getRuntime().exec(new String[]{"su", "-c", InstallCommand}); 
     Insproc.waitFor(); 

     Process Rebootproc = Runtime.getRuntime().exec(new String[] {"su", "-c", RebootCommand}); 
     Rebootproc.waitFor(); 
     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
    } 
    }; 

這段代碼工作。這是正常操作

但是當我的服務器上不存在Apk時,不存在apk。只有重啓。

我想如果Apk不存在。 android.os.Process.killProcess(android.os.Process.myPid()); 執行。

當我的服務器上不存在Apk時,如何執行下面的代碼。 android.os.Process.killProcess(android.os.Process.myPid());以編程方式安卓android?

+0

請問你的接收器被調用?它傾聽哪個動作?以及誰發送/廣播這些操作? – Yazan

+0

'@Override public void onResume(){ super.onResume(); IntentFilter apkcompleteFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); registerReceiver(apkcompleteReceiver,apkcompleteFilter); }' – chohyunwook

+0

當你得到這個動作的時候,你可以在apk路徑下創建'File'實例'/ sdcard/Download/my.apk',然後確保它存在,並檢查它的大小> 0或其他大小,如果一切都很好,那麼開始執行你的命令 – Yazan

回答

0

這就是我的意思是(檢查文件存在,並且文件大小爲好) 在onReceive()方法如下更改代碼:

@Override 
public void onReceive(Context context, Intent intent) { 
    try { 
     //------START add this code ------- 
     File apkFile = new File("/sdcard/Download/my.apk"); 

     //length is file size in bytes, use other size if you want, like (minimum size) 
     //(apkFile.length < 512000) where 512000 byte = 500KB, this will mean file size should be at least 500KB 
     if(!apkFile.exists() || apkFile.length <= 0){ 
      //download failed 
      android.os.Process.killProcess(android.os.Process.myPid()); 
      return; 
     } 
     //------END add this code ------- 

     String InstallCommand,RebootCommand; 

     InstallCommand = "pm install -r /sdcard/Download/my.apk"; 
     RebootCommand = "reboot"; 
     Process Insproc = Runtime.getRuntime().exec(new String[]{"su", "-c", InstallCommand}); 
     Insproc.waitFor(); 

     Process Rebootproc = Runtime.getRuntime().exec(new String[] {"su", "-c", RebootCommand}); 
     Rebootproc.waitFor(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

謝謝,這段代碼是創建另一個類的? – chohyunwook

+0

也許,我編寫registerReceiver是什麼? – chohyunwook

+1

哦謝謝你的回答正確 – chohyunwook

相關問題