Java Android Intent Service 只工作一次

标签 java android android-intent android-service

我想创建一个 Intent 服务,它在整个应用程序(在所有 Activity 中)中一直在一段时间内工作并执行任务。我使用处理程序。我在 Activity 中启动了一项服务。我看到一项服务只工作一次(执行任务),为什么? 这是我的服务:

public class SenderXML extends Service {

    public static boolean running = false;
    private Timer timer = new Timer();
    private SendXMLTask sendXMLTask;
    private Context context;

    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();
        Gson gson = new Gson();
        MainActivity.xmlList = null;
        MainActivity.xmlList = new ArrayList<>();
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
        List<String> productFromShared1 = new ArrayList<>();
        String jsonPreferences1 = sharedPref.getString("TAG1", "");

        Type type1 = new TypeToken<List<String>>() {
        }.getType();
        productFromShared1 = gson.fromJson(jsonPreferences1, type1);
        if (productFromShared1 != null)
            MainActivity.xmlList.addAll(productFromShared1);
        Log.e("tworzenie serwisu ", "tworzenie");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Dziełanie serwisu ", "Dziełanie");
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                Log.e("Dziełanie serwisu 1111", "Dziełanie 111");
                if (!MainActivity.xmlList.isEmpty()) {
                    if (NetworkUtil.isNetworkAvailable(context)) {
                        if (!running) {
                            sendXMLTask = new SendXMLTask();
                            sendXMLTask.execute();
                        }
                    }
                }
            }
        }, 1000 * 60 * 2);

        return super.onStartCommand(intent, flags, startId);
    }

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

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

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

        @Override
        protected String doInBackground(Void... voids) {
            Log.e("xml ", MainActivity.xmlList.size() +"");
            running = true;
            HttpClient httpclient = HttpClientUtil.getHttpClient(getApplicationContext());
            HttpPost httppost = new HttpPost(Util.getServerUrl(getApplicationContext()) + "/SetData");
            ArrayList<NameValuePair> namevaluepairs = new ArrayList<>(2);
            namevaluepairs.add(new BasicNameValuePair("token", String.valueOf(E_Gps.TOKEN)));
            namevaluepairs.add(new BasicNameValuePair("xml", MainActivity.xmlList.get(0)));
            if (MainActivity.xmlList.size() > 0) {
                MainActivity.btTransfer.setBackgroundColor(Color.YELLOW);
            }
            try {
                httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpResponse response = null;
            try {
                response = httpclient.execute(httppost);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            InputStream responseInputStream = null;
            try {
                responseInputStream = new BufferedInputStream(response.getEntity().getContent());
                try {
                    int tt = ResponseParser.getResponseType(responseInputStream);
                    if (tt == 0) {
                        return null;
                    }
                } catch (EmptyResponseException | UnknownAnswerName | XmlPullParserException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.e("xml", MainActivity.xmlList.get(0));
            Log.e("xml wys ", convertStreamToString(responseInputStream));
            return convertStreamToString(responseInputStream);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s != null) {
                MainActivity.xmlList.remove(0);
                Gson gson = new Gson();
                String jsonCurProduct = gson.toJson(MainActivity.xmlList);
                SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("TAG1", jsonCurProduct);
                editor.apply();
            }
            if (!MainActivity.xmlList.isEmpty()) {
                sendXMLTask = new SendXMLTask();
                sendXMLTask.execute();
            } else {
                MainActivity.btTransfer.setBackgroundColor(Color.GREEN);
            }
            running = false;
        }
    }
}

最佳答案

当您在 Activity 中调用 startService() 时,将创建 Service(如果它尚不存在)并且onStartCommand() 被调用。除非再次调用 startService(),否则不会再次调用 onStartCommand()

由于您在 onStartCommand() 中发布了一个 Runnable,因此您应该让您的 Runnable 重新发布以在一段时间后运行时间(如果您希望它连续运行)。

使用完毕后,请确保停止服务

关于Java Android Intent Service 只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41611357/

相关文章:

java - 如何以毫秒精度同步 2 个系统之间的时间?

java - 如何在 `gradle.build`中强制使用版本的特定jar?

Linux 中的 Java 进程状态

java - 在框架布局中显示 Activity

java - 移动设备与电脑之间的无线连接

android - butterknife 是运行时编译的吗?

android - Facebook Intent.ACTION_SEND 始终返回 0 作为 resultCode

java - Android - 从 Activity 中获取 list 元数据

android - 如何使用 Intent.ACTION_VIEW 查看文件夹的内容?

android - android中RTC和RTC_WAKEUP的区别