Android studio でアプリ画面を閉じていても作動するタイマーアプリを作りたいです。
しかし、serviceの実装で悩んでいます。
以下のコードで、改善点があればご教授いただきたいです。
xml
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/count_text" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:layout_editor_absoluteX="55dp" tools:layout_editor_absoluteY="43dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Main.java
package com.example.tr;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private TextView countText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //テキストビュー this.countText = (TextView) findViewById(R.id.count_text); Intent intent = new Intent(this, MyService.class); startService(intent); }
}
MyService
package com.example.tr;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
private Timer mainTimer; //タイマー用 private TextView countText; //テキストビュー private int count = 0; //カウント private Handler mHandler = new Handler(); //UI Threadへのpost用ハンドラ private MainTimerTask mainTimerTask; public MyService() { } @Override public void onCreate() { } @Override public int onStartCommand(Intent intent, int flags, int startId) { this.mainTimerTask = new MainTimerTask(); //タイマースケジュール設定&開始 this.mainTimer.schedule(mainTimerTask, 1000, 500); //タイマーインスタンス生成 this.mainTimer = new Timer(); return START_STICKY; } @Override public IBinder onBind(Intent intent) { // We don't provide binding, so return null return null; } /** * タイマータスク派生クラス * run()に定周期で処理したい内容を記述 */ public class MainTimerTask extends TimerTask { @Override public void run() { //ここに定周期で実行したい処理を記述します mHandler.post(new Runnable() { public void run() { //実行間隔分を加算処理 count += 1; //画面にカウントを表示 countText.setText(String.valueOf(count)); } }); } }
}
あなたの回答
tips
プレビュー