仅启动一次后台服务并在任务完成后停止

Starting a background service for only once and stop once the task is completed

我在我的 activity 中使用自动完成文本视图,并且我编写了一个服务以从同一 activity 中的服务器获取数据,完成服务后我启用了该自动完成文本视图,因为当用户开始在该文本视图中输入时,我从服务器开始获取的数据得到过滤,到这里的所有事情都工作正常但每次我来到相同 activity 我的服务开始执行我只想要我的服务只接到一次电话,一旦我的数据来自服务器,用户就可以从自动完成文本视图中搜索。

我的活动代码

@Override
 protected void onStart() {



    if(CarproApp.getInstance().namesList != null) {
    //enable textfield if you have already fetched the data from server :)
        debitornameET.setEnabled(true);
    }else{
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MyService.MY_ACTION);
        registerReceiver(myReceiver, intentFilter);
        //Start our own service

    }

    Intent intent = new Intent(CustomerAccountActivity.this,
            MyService.class);
    //intent.putExtra("INIT_DATA", "Data passed from Activity to Service in startService");
    startService(intent);
    super.onStart();
}

@Override
protected void onStop() {
    unregisterReceiver(myReceiver);
    super.onStop();
}

private class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        namelist = arg1.getStringArrayListExtra("listnames");
        System.out.println("PRINTING" + namelist);
        debitornameET.setEnabled(true);
        Toast.makeText(getApplicationContext(), "BackGround Task   Completed", Toast.LENGTH_SHORT).show();
        CarproApp.getInstance().namesList = namelist;

    }

   debitornameET.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            runOnUiThread(new Runnable() {
                public void run() {

                    //  MyWebRequestService.listVal; 
                    debitorcodeET.setText("");
                    debitorCode = "";
                    Collections.sort(namelist);//here i am getting null when i came back to same activity
                    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line,namelist);
                    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    debitornameET.setThreshold(1);
                    debitornameET.setAdapter(dataAdapter);


                }
            });
        }

Service.Class

 public class MyService extends Service {

    final public static String MY_ACTION = "MY_ACTION";
    //String initData;
    private SendHttpRequest reqService;
    public static ArrayList<String> servicelist;  

    @Override
    public IBinder onBind(Intent arg0) {

        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        servicelist = new ArrayList<String>();
    //  initData = intent.getStringExtra("INIT_DATA");

        new AsynchCall().execute();

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


    class AsynchCall extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... params) {
            String qryService = "SELECT DEBITOR_NAME FROM DEBITORS ";
            reqService = new SendHttpRequest(qryService);
            try {
                reqService.ExecuteQuery();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {

                e.printStackTrace();
            }

            for(int i=0;i<reqService.getRowCount();i++)
            {
                servicelist.add(reqService.getRow(i)[1]);
                System.out.println("TEXTVIEWDATAAAAAAAAa" + reqService.getRow(i)[1]);
            }
            Intent intent = new Intent();
            intent.setAction(MY_ACTION);
            intent.putStringArrayListExtra("listnames", servicelist);
            sendBroadcast(intent);
            return null;
        }

    }
}

** CarproApp Class**

        public class CarproApp extends Application {

        private static CarproApp sInstance;
        public ArrayList<String> namesList;

        public static CarproApp getInstance() {
            return sInstance;
        }

        public void onCreate() {
            super.onCreate();
            sInstance = this;


        }



    }

由于来自服务器的数据太大,我不想将其存储在本地数据库中。我的代码正在运行,但每次我来到 activity 时,服务调用都会被执行,这是我不想要的。请指导我

利用应用程序 class :) 应用程序 class 在应用程序的整个生命周期中执行一次 :) 这意味着应用程序 class 的 onCreate 在您启动时被调用应用程序和 onDestroy 在您终止应用程序时被调用 :)

所以应用程序 class 在您的应用程序的整个生命周期中都是持久的 :) 我相信这就是您所需要的 :)

在您的应用程序 class 的 OnCreate() 中调用您的服务 :) 一旦您获得数据,将其保存在应用程序 class 的 属性 中 :) 所以无论何时您回来Activity 从 Application class 的 属性 中读取数据 :)

您可以执行以下操作:)

public class yourApplicationName extends Application{ 
     private static yourApplicationName sInstance;
     public ArrayList<String> namesList;

     public static yourApplicationName getInstance() {
        return sInstance;
    }

    public void onCreate() {
        super.onCreate();
        sInstance = this;
    }
}

为了将此应用程序 class 用作您的应用程序 class,您必须在 AndroidManifest.xml 中指定它:)

<application
    android:name=".yourApplicationName"

在你的

私有 class MyReceiver 扩展 BroadcastReceiver {

@Override
public void onReceive(Context arg0, Intent arg1) {
    namelist = arg1.getStringArrayListExtra("listnames");
    System.out.println("PRINTING" + namelist);
    debitornameET.setEnabled(true);
    Toast.makeText(getApplicationContext(), "BackGround Task         Completed", Toast.LENGTH_SHORT).show();
    yourApplicationName.getInstance().namesList = nameList;
}

debitornameET.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        runOnUiThread(new Runnable() {
            public void run() {

                //  MyWebRequestService.listVal; 
                debitorcodeET.setText("");
                debitorCode = "";
                Collections.sort(CarproApp.getInstance().namesList);//here i am getting null when i came back to same activity, abhi nai aayega error :P
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line,CarproApp.getInstance().namesList);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                debitornameET.setThreshold(1);
                debitornameET.setAdapter(dataAdapter);


            }
        });
    }

要在您返回 MainActivity 时启用您的文本字段 :) 只需检查 Application 实例 属性 是否为空 :)

  @Override
  protected void onStart() {
       if(yourApplicationName.getInstance().namesList != null) {
            //enable textfield if you have already fetched the data from server :)
            debitornameET.setEnabled(true);
       }
       else{
            myReceiver = new MyReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(MyService.MY_ACTION);
            registerReceiver(myReceiver, intentFilter);

            //you dont have to call service very time buddy :D call only once enough :)
            Intent intent = new Intent(CustomerAccountActivity.this,
        MyService.class);
            //intent.putExtra("INIT_DATA", "Data passed from Activity to Service in startService");
            startService(intent);
       }
  }

希望我能帮上点忙 :) 快乐的编码伙伴 :)