Android Java服务多次启动

时间:2017-07-26 09:49:09

标签: java android service handler

当我登录我的应用程序并在关闭应用程序或注销时停止此服务时,我只想startService一次。我希望我的服务工作2分钟,为此我使用Handler

这是我的服务:

public class Sendrer extends Service {

    public static boolean running = false;
    private Timer timer = new Timer();
    private SendPhotoTask asyncSender;
    private Context context;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    public static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        sp = getSharedPreferences("pfref", Activity.MODE_PRIVATE);
        editor = sp.edit();
        Gson gson = new Gson();
        List<File> productFromShared = new ArrayList<>();
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
        String jsonPreferences = sharedPref.getString("TAG", "");

        Type type = new TypeToken<List<File>>() {
        }.getType();
        productFromShared = gson.fromJson(jsonPreferences, type);
        MainActivity.photoListSend = null;
        MainActivity.photoListSend = new ArrayList<>();
        if (productFromShared != null)
            MainActivity.photoListSend.addAll(productFromShared);
        Log.e("tworzenie serwisu ", "tworzenie");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Dziełanie serwisu ", "Dziełanie");

        if (!running) {
            running = true;
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    asyncSender = new SendPhotoTask();
                    asyncSender.execute();
                }
            }, 1000 * 60 * 2);
        }

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        if (running) {
            timer.cancel();
            asyncSender = new SendPhotoTask();
            asyncSender.cancel(true);
            running = false;
        }
        Log.e("service ", "nie działa");
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    class SendPhotoTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            running = true;
            if (MainActivity.photoListSend != null) {
                if (!MainActivity.photoListSend.isEmpty())
                    if (NetworkUtil.isNetworkAvailable(context)) {
                        if (MainActivity.photoListSend.size() > 0) {
                            MainActivity.isSend = true;
                            running = true;
                            InputStream responseInputStream = null;
                            Log.e("start wysłania ", "start");
                            try {
                                if (MainActivity.photoListSend.get(0).isFile()) {
                                    responseInputStream = HttpConnectionsUtil.sendPhotoRequest(getApplicationContext(), true, MainActivity.photoListSend.get(0).getName());
                                    if (responseInputStream != null) {
                                        String input = convertStreamToString(responseInputStream);
                                        if (input.equals("empty"))
                                            return "BAD";
                                        else {
                                            try {
                                                int tt = ResponseParser.getType(input);
                                                Log.e("TaG", tt + " ");

                                                if (tt == 0) {
                                                    return null;
                                                } else if (tt == -1) {
                                                    return null;
                                                }
                                            } catch (UnknownAnswerName e) {
                                                e.printStackTrace();
                                                return null;
                                            }
                                        }
                                    }

                                } else {
                                    return "BAD";
                                }

                            } catch (IOException e) {
                                e.printStackTrace();
                                return null;
                            }
//                    Log.e("Wysyłanie zdjęcia ", convertStreamToString(responseInputStream));
                            if (responseInputStream != null)
                                return convertStreamToString(responseInputStream);
                        }
                    }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (NetworkUtil.isNetworkAvailable(context)) {
                if (sp.getBoolean("workOffLine", false)) {
                    editor.putBoolean("workOffLine", false);
                    editor.commit();
                    isConnect.setVisibility(View.VISIBLE);
                    imgIsSend.setVisibility(View.VISIBLE);
                    imgIsNet.setVisibility(View.GONE);
                }
            }
            if (s != null) {
                if (!MainActivity.photoListSend.isEmpty()) {
                    if (MainActivity.photoListSend.size() > 0) {
                        File file = MainActivity.photoListSend.get(0);
                        if (file.exists())
                            file.delete();
                        MainActivity.photoListSend.remove(0);
                        Gson gson = new Gson();
                        String jsonCurProduct;
                        synchronized (context) {
                            jsonCurProduct = gson.toJson(MainActivity.photoListSend);
                        }
                        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPref.edit();
                        editor.putString("TAG", jsonCurProduct);
                        editor.apply();
                        File imagesFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                        assert imagesFolder != null;
                    }
                }

            }
            if (s == null) {
                MainActivity.isSend = false;
            }
            if (!MainActivity.photoListSend.isEmpty()) {
                if (NetworkUtil.isNetworkAvailable(context)) {
                    if (MainActivity.photoListSend.size() > 0) {
                        asyncSender = new SendPhotoTask();
                        asyncSender.execute();
                        Log.e("Wysyłanie kolejnego ", "zdjecia");
                    } else {
                        context.stopService(new Intent(context, Sendrer.class));
                        asyncSender.cancel(true);
                        context.startService(new Intent(context, Sendrer.class));
                    }

                } else {
                    context.stopService(new Intent(context, Sendrer.class));
                    asyncSender.cancel(true);
                    context.startService(new Intent(context, Sendrer.class));
                }
            } else {
                MainActivity.isSend = false;
                context.stopService(new Intent(context, Sendrer.class));
                asyncSender.cancel(true);
                context.startService(new Intent(context, Sendrer.class));
            }
            running = false;
        }
    }
}

有时我会多次启动服务......而且我希望该服务每5分钟运行一次

1 个答案:

答案 0 :(得分:1)

请参阅此链接以获取更多帮助 https://developer.android.com/guide/components/services.html

我认为您在服务中发送的照片比您应该使用IntentService而不是服务。任务完成后, IntentService 将被销毁。

在服务中 onStartCommand()每次启动服务时都会调用,如果您不希望运行服务的时间超过返回 START_NOT_STICKY

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_NOT_STICKY;
}

如果您的任务已完成,则调用onDestroy()方法 stopSelf()。 stopSelf方法停止服务。

 @Override
public void onDestroy() {
    super.onDestroy();
    stopSelf();
}