У меня запущена служба, которая будет получать местоположение с сервера каждые 30 секунд.Теперь, когда я не получаю никаких данных с сервера, я хочу отобразить всплывающее диалоговое окно с надписью «Поездка не запущена».И после нажатия на диалоговое окно, хотите завершить деятельность, а также остановить службу.Как я могу добиться этого?
Мой класс обслуживания ниже:
public class BackgroundService extends Service {
private boolean isRunning;
private Context context;
private Thread backgroundThread = null;
ArrayList<String> mArrLatitude = null;
ArrayList<String> mArrLongitude = null;
ArrayList<String> mArrTime = null;
ArrayList<String> mArrAddress = null;
ScheduledExecutorService scheduleTaskExecutor = null;
// private Handler mHandler = new Handler();
private Runnable runnable = new Runnable() {
@Override
public void run() {
getLocationOnline();
}
};
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
this.context = this;
this.isRunning = false;
mArrLatitude = new ArrayList<>();
mArrLongitude = new ArrayList<>();
mArrTime = new ArrayList<>();
mArrAddress = new ArrayList<>();
scheduleTaskExecutor = Executors.newSingleThreadScheduledExecutor();
scheduleTaskExecutor.scheduleAtFixedRate(runnable, 0, 15, TimeUnit.SECONDS);
Log.d("Testing", "Service is started");
createNotification();
}
@Override
public void onDestroy() {
super.onDestroy();
scheduleTaskExecutor.shutdownNow();
runnable = null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
runnable.run();
return START_REDELIVER_INTENT;
}
private void createNotification()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "my_channel_01";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_phone_android_black_24dp)
.setContentTitle("IPL tracker is in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
private void getLocationOnline(){
Log.d("Testing", "inside the getLocationOnline "+Constants.BASE_URL+Constants.GET_STUDENT_SERVICE+"35004"+Constants.GET_CURR_TRIP);
JsonArrayRequest jsonObjReq = new JsonArrayRequest(Constants.BASE_URL+Constants.GET_STUDENT_SERVICE+"35004"+Constants.GET_CURR_TRIP,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// showResponse(response, "Showing POST request response...");
try
{
mArrLatitude.clear();
mArrLongitude.clear();
mArrTime.clear();
mArrAddress.clear();
if(response.length() == 0)
{
Log.d("Testing", "JSON Array is 0 ");
// progressDialog.cancel();
Toast.makeText(getApplicationContext(),"Trip is stopped or not started yet", Toast.LENGTH_LONG).show();
// stopSelf();
scheduleTaskExecutor.shutdownNow();
runnable = null;
}
else
{
Log.d("Testing", "666 ");
int len = response.length();
for (int i = 0; i < len; i++)
{
JSONObject address = (JSONObject) response.get(i);
String lat = "";
String longt = "";
String currtime = "";
String loc_addr = "";
lat = address.getString("latitude");
longt = address.getString("longitude");
currtime = address.getString("currtime");
loc_addr = address.getString("locationAddress");
mArrLatitude.add(lat);
mArrLongitude.add(longt);
mArrAddress.add(loc_addr);
mArrTime.add(currtime);
}
Log.d("Testing", "users det:: "+mArrLatitude.size());
Intent i = new Intent("carLocationService");
i.putStringArrayListExtra("lat",mArrLatitude);
i.putStringArrayListExtra("longi",mArrLongitude);
i.putStringArrayListExtra("time",mArrAddress);
i.putStringArrayListExtra("addr",mArrTime);
sendBroadcast(i);
}
}
catch (JSONException e)
{
Log.d("Testing", "JSOn Excep::: "+e.toString());
//progressDialog.cancel();
}
Log.d("Testing", response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Testing", "Volley Error::: "+error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("user-key",Constants.m_spAhlan.getString("key",""));
return params;
}
};
AppController.getInstance().addToRequestQueue(jsonObjReq, "JSON_OBJECT_POST_REQUEST_TAG");
}
}
Я хочу написать логику в следующем фрагменте кода:
if(response.length() == 0){
}
Ищемответ.
Спасибо, Ариндам.