#android #auto-update #google-play
#Android #автоматическое обновление #google-play
Вопрос:
У нас есть приложение в магазине Google Play, которое постоянно работает на переднем плане. Устройства, на которых оно работает, находятся вне нашего контроля и не укоренены. Они работают на Android 4.2 или 4.4.
Наша цель — обновить приложение до последней версии, которую мы выпускаем через Play Store, без взаимодействия с пользователем. Перезапуск устройства был бы единственным приемлемым вариантом «взаимодействия».
Мы обнаруживаем, что запущенное приложение не обновляется автоматически при запуске, даже если включено «автоматическое обновление».
Каков способ достижения нашей цели?
Ответ №1:
Используйте диспетчер аварийных сигналов для планирования обновления, а затем используйте создать класс и расширить класс service или 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);
Для обслуживания:
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);
}
}
Комментарии:
1. Обратите внимание, что приведенный выше код является только примером .. из приведенной мной ссылки
2. При этом будут загружаться обновления, но когда / где происходит фактическая установка обновления приложения?