2016-08-05 89 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()方法并下载包并保存到数据库中。

相关问题