Androidで定期的に処理を実行する

今回はアプリが起動している時のみ定期的に処理を実行したいので、Lifecycle.Event.ON_START のタイミングで処理を開始する。
下記のような感じ。

public class Xxxx implements LifecycleObserver {

    private final Handler handler = new Handler();
    private Runnable runnable;

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppStart() {
        runnable = new Runnable() {
            @Override
            public void run() {
                // do something.

                // 3秒ごとに実行
                handler.postDelayed(this, 3000);
            }
        };
        handler.post(runnable);

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onAppStop() {
        handler.removeCallbacks(runnable);
    }

AndroidのWebViewで、Webページ内のjavascript実行時にJSON形式の値を渡す

レイアウトにWebViewを追加。

<WebView
    android:id="@+id/webView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scrollbarStyle="insideOverlay"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent">
</WebView>

Java側でWebViewの取得、ひとまずアプリ内のローカルのhtmlを読み込む。

・・・
    private WebView webView;
・・・
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        webView = findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.setInitialScale(1);
        webView.loadUrl("file:///android_asset/index.html");

JSONを引数に渡して、javascriptを実行する。

        Gson gson = new Gson();
        Map<String, Object> data = new HashMap<>();
        data.put("data1", "XXXXXXX");
        data.put("data2", 10000);
        String script = "sampleFunc1(" + gson.toJson(data) + ")";
        webView.evaluateJavascript(script, null);

Android でリソースのテキスト取得でリソースIDではなく、キー(文字列)指定で取得

Android で strings.xml に定義したテキストを取得するなら、通常以下のような感じになります。

getString(R.string.msg_xxxx);

 
この msg_xxxx を文字列として指定して動的に取得したいときは以下のような感じです。

    public static String getByName(Context context, String key) {
        int strId = context.getResources().getIdentifier(key, "string", context.getPackageName());
        if (strId <= 0) {
            return "";
        }
        return res.getString(strId);
    }

Activity で呼ぶなら以下のようになります。

    Xxxx.getByName(this, "msg_xxxx");

Spring Boot で定期的にバッチ処理を実行する

定期的に一時ファイルを削除するとか、データを更新するとか、バッチ処理を実行する。

スケジューリングを有効にする。

@SpringBootApplication
@EnableScheduling
public class Application {

実際に実行したい処理は下記のような感じ。

@Component
public class XxxxTasks {

    @Scheduled(cron = "0 * * * * *")
    public void xxxxTask() {

これは毎分0秒に実行する例です。
このように cron で書く以外にも、
前の処理から5秒遅延させる
@Scheduled(fixedDelay=5000)
とか、5秒間隔で実行させるとか、
@Scheduled(fixedRate=5000)
初回の待機時間を設定するとか、
@Scheduled(initialDelay=1000, fixedRate=5000)
できるようです。

スケジューリングのデフォルトスレッドプールサイズが1のため、複数のタスクを同時実行させる場合は、スレッドプールのサイズを変更する必要があるようです。

Android で BLE の状態(有効・無効)をチェック

Android で Bluetooth との通信を行う前に、Bluetooth が有効にされているかをチェックする。

BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null) {
    // TODO: 端末がBLEに対応していない時の処理
} else if (!bluetoothAdapter.isEnabled()) {
    // TODO: 端末でBLEが有効にされていない時の処理
}