Skip to content

Instantly share code, notes, and snippets.

@thinkAmi
Last active February 20, 2018 07:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkAmi/6258565 to your computer and use it in GitHub Desktop.
Save thinkAmi/6258565 to your computer and use it in GitHub Desktop.
RubotoでAsyncTask + ProgressDialog のサンプル
# ver 0.1
# バックグラウンドへ回った時でもProgressDialogが動作するバージョン
# ただし、端末を回転させると、うまく動作しない
require 'ruboto/widget'
ruboto_import_widgets :Button, :LinearLayout, :TextView
java_import 'android.os.AsyncTask'
java_import 'java.lang.Thread' # Thread.sleepを使いたいため追加
# Progressバーまわり
java_import 'android.app.ProgressDialog'
java_import 'android.content.DialogInterface'
java_import 'android.util.Log'
class AsyncTaskProgressDialogActivity
def onCreate(bundle)
super
self.content_view =
linear_layout orientation: :vertical do
@status = text_view text: 'before', text_size: 48
button text: 'start', on_click_listener: proc { run_async_task }
end
end
def run_async_task
task = MyAsyncTask.new(self, @status)
task.execute ''
end
end
class MyAsyncTask < AsyncTask
def initialize(activity, text_view)
# カッコ重要。無しだと、エラーになる
super()
@activity = activity
@text_view = text_view
end
def onPreExecute
show_dialog
end
def doInBackground(params)
# 例外を捕捉しないとonCancelledが呼ばれない等が発生することに注意
begin
(0..9).each do |i|
return false if isCancelled
Thread.sleep(1000)
publishProgress((i + 1) * 10)
end
rescue
end
true
end
def onProgressUpdate(values)
@dialog.setProgress(values.first)
end
def onCancelled
dismiss_dialog
@text_view.text = 'cancel'
end
def onPostExecute(result)
dismiss_dialog
@text_view.text = 'after'
end
def show_dialog
@dialog = ProgressDialog.new(@activity)
@dialog.setTitle('Please wait')
@dialog.setMessage('Loading data...')
@dialog.setProgressStyle(ProgressDialog::STYLE_HORIZONTAL)
@dialog.setCancelable(true)
@dialog.setIndeterminate(false)
@dialog.setMax(100)
@dialog.setProgress(0)
# 戻るボタンを押したとき等の処理:これを記載しないと、キャンセルボタン以外でキャンセルした時に、正しくキャンセルが動作しない
@dialog.setOnCancelListener(proc { cancel_progress_dialog })
# ProgressDialogのCancelボタンを追加して押したときの処理
@dialog.setButton(DialogInterface::BUTTON_NEGATIVE, "cancel", proc { cancel_progress_dialog })
@dialog.show
end
def dismiss_dialog
@dialog.dismiss
end
def cancel_progress_dialog
@dialog.cancel
cancel(true)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment