So I am trying to create an App in Android Studios which vibrates depending on how far you have traveled.
I want to be able to start the app, and start the service, then it run in the background and still vibrate after 500 meters traveled, whether the screen is on or off.
I also want to be able to update the UI on the distance traveled.
The main thing that i want to figure out first is how to get it to vibrate when the app is not the main focus.
I have tried a Service, but I have seen there are restrictions on API 29 onwards which could potentially be the cause? (https://developer.android.com/guide/components/activities/background-starts)
When I run it on my phone, as soon as i minimize the app, or turn the screen off, the vibrating stops.
I am hoping someone can point me in the right direction on how to achieve vibration even after i turn the screen off.
This is a simplified code of the vibration problem
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button start, stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = findViewById(R.id.start);
stop = findViewById(R.id.stop);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.equals(start)){
startService(new Intent(this, BackGroundService.class));
}else if (view.equals(stop)){
stopService(new Intent(this, BackGroundService.class));
}
}
}
and the service
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.VibrationEffect;
import android.os.Vibrator;
import org.jetbrains.annotations.Nullable;
public class BackGroundService extends Service {
private Vibrator vibrator;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
super.onStartCommand(intent,flags,startId);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VibrationEffect.createOneShot(30000, VibrationEffect.DEFAULT_AMPLITUDE));
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}