如何在没有用户交互的情况下自动更新连续运行的Android应用

Bob*_*eld 7 android auto-update google-play

我们在Google Play商店中有一个应用程序,它在前台不断运行.它运行的设备不受我们的控制,并且没有root.它们运行在Android 4.2或4.4上.

我们的目标是让应用程序更新到我们通过Play商店发布的最新版本,而无需用户交互.重启设备将是唯一可接受的"交互"选项.

我们发现正在运行的应用程序在运行时不会自动更新,即使打开了"自动更新"也是如此.

实现目标的方法是什么?

小智 -1

使用警报管理器安排更新,然后使用创建类并扩展服务或 IntentService 类。检查是否有互联网连接,如果有,请继续更新,如下所示:检查此链接Android 服务 - 教程通过这种方式,即使不使用服务显示您的活动,您也可以进行更新。

创建警报管理器:

 Calendar cal = Calendar.getInstance();

Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);

AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
Run Code Online (Sandbox Code Playgroud)

对于服务:

    public class DownloadService extends IntentService {

  private int result = Activity.RESULT_CANCELED;
  public static final String URL = "urlpath";
  public static final String FILENAME = "filename";
  public static final String FILEPATH = "filepath";
  public static final String RESULT = "result";
  public static final String NOTIFICATION = "com.vogella.android.service.receiver";

  public DownloadService() {
    super("DownloadService");
  }

  // will be called asynchronously by Android
  @Override
  protected void onHandleIntent(Intent intent) {
    String urlPath = intent.getStringExtra(URL);
    String fileName = intent.getStringExtra(FILENAME);
    File output = new File(Environment.getExternalStorageDirectory(),
        fileName);
    if (output.exists()) {
      output.delete();
    }

    InputStream stream = null;
    FileOutputStream fos = null;
    try {

      URL url = new URL(urlPath);
      stream = url.openConnection().getInputStream();
      InputStreamReader reader = new InputStreamReader(stream);
      fos = new FileOutputStream(output.getPath());
      int next = -1;
      while ((next = reader.read()) != -1) {
        fos.write(next);
      }
      // successfully finished
      result = Activity.RESULT_OK;

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (stream != null) {
        try {
          stream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    publishResults(output.getAbsolutePath(), result);
  }

  private void publishResults(String outputPath, int result) {
    Intent intent = new Intent(NOTIFICATION);
    intent.putExtra(FILEPATH, outputPath);
    intent.putExtra(RESULT, result);
    sendBroadcast(intent);
  }
} 
Run Code Online (Sandbox Code Playgroud)