Android Service サンプル(Vibrator)
FragmentからVibratorを実行したが、Activityを終了すると、バイブレーションも終了してしまうため、サービスに処理を移行し動き続けるようにする。
https://github.com/pppiroto/KaigiUtil/tree/8d52606b8d69f2dd689888a186dda50ae530bdff
1.サービス
Fragmentでやっていた処理を、サービスに持ってくる
package info.typea.kaigiutil; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.Vibrator; import android.widget.Toast; public class SleepDefenderService extends Service { private Vibrator vibrator; public SleepDefenderService() { } @Override public IBinder onBind(Intent intent) { throw null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { vibrator = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE); if (!vibrator.hasVibrator()) { Toast.makeText(this, "no vibrator.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "start vibe as service", Toast.LENGTH_SHORT).show(); long pattern[] = {1000, 100}; int repeatIndex = 0; // 繰り返し開始位置 -1の場合繰り返しなし vibrator.vibrate(pattern, repeatIndex); } return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); vibrator.cancel(); Toast.makeText(this, "stop vibe as service", Toast.LENGTH_SHORT).show(); } }
1.1 AndroidManifest.xml の application エントリーの子要素に、以下を追加
<service android:name=".SleepDefenderService" android:enabled="true" android:exported="true"></service>
2.Fragment
Vibratorを操作していた、Fragmentを、サービスの呼び出しと停止に変更
package info.typea.kaigiutil; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SleepDefenderFragment extends Fragment implements View.OnClickListener { private static final String ARG_MSG = "message"; public SleepDefenderFragment() { } public static SleepDefenderFragment newInstance(String message) { SleepDefenderFragment fragment = new SleepDefenderFragment(); Bundle args = new Bundle(); args.putString(ARG_MSG, message); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); return inflater.inflate(R.layout.fragment_sleep_defender, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.btn_vib_start).setOnClickListener(this); view.findViewById(R.id.btn_vib_stop).setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(this.getContext(), SleepDefenderService.class); switch(v.getId()) { case R.id.btn_vib_start: this.getContext().startService(intent); break; case R.id.btn_vib_stop: this.getContext().stopService(intent); break; } } }