2016-08-05 90 views
0

我有一個應用程序在發出通知時下載數據並將其放入SQLite數據庫。此應用程序正在使用時正常工作,但我也需要它在應用程序關閉時工作。當應用程序關閉時從廣播接收器運行任務[Android]

我已經在應用程序關閉時調用BroadcastReceiver,但我不知道如何讓它繼續添加到數據庫。

這裏是我使用的代碼:

AndroidManifest.xml中

<manifest.... 

    <application... 

    <receiver android:name=".broadcast.PacksReceiver" > 
     <intent-filter> 
      <action android:name="ADD_PACK" > 
      </action> 
     </intent-filter> 
    </receiver> 

PacksReceiver

public class PacksReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
    Log.d("PacksReceiver", "onReceive"); 

    String message = intent.getStringExtra("message"); 

    PacksActivity pa = new PacksActivity(); 
    pa.downloadPack(null, message); 
    } 
} 

PacksActivity

public void downloadPack(View v, String thisPackID){ 
    Log.d("download", "pack"); 
    //THIS LOG IS CALLED EVERYTIME 
    vRef = v; 
    if(vRef != null){ 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       onScreenProgressBar = (ProgressBar) vRef.findViewById(R.id.onScreenProgress); 
       onScreenProgressCircle = (ProgressBar) vRef.findViewById(R.id.onScreenProgressCircle); 
       dlPercent = (TextView) vRef.findViewById(R.id.dlPercent); 

       onScreenProgressCircle.setVisibility(View.VISIBLE); 

       onScreenProgressBar.setVisibility(View.VISIBLE); 
       onScreenProgressCircle.setProgress(0); 
      } 
     }); 
    } 
    if(thisPackID == null){ 
     thisPackID = pack_id; 
    } 

    String url = MyApp.getAppContext().getString(R.string.serverURL) + 
      MyApp.getAppContext().getString(R.string.getAppendixA) + "/" + thisPackID; 
    Intent appA_Intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class); 
    appA_Intent.putExtra("url", url); 
    appA_Intent.putExtra("onCreate", "false"); 
    appA_Intent.putExtra("receiver", downloadPackReceiver); 
    appA_Intent.putExtra("downloadType", "GET_APPENDIX_A"); 
    appA_Intent.putExtra("requestId", 101); 
    MyApp.getAppContext().startService(appA_Intent); 
} 

回答

1

onReceive() 

方法來啓動該服務,因爲你可以得到多發廣播此起彼伏。

0

編寫代碼,在OnRecieve()方法內的PackReciever數據庫中添加數據,因爲那是您接收推送通知的地方。

0

不要在接收器中調用活動。相反,使用IntentService來下載所有包。 IntentService在完成其工作後自動完成。

覆蓋其onHandleIntent()方法並下載包並保存到數據庫中。

相關問題