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

时间:2016-04-20 06:36:05

标签: android service android-asynctask android-service autocompletetextview

我在我的活动中使用了一个自动完成的文本视图,我写了一个服务,在完成服务后从同一个活动中的服务器获取数据我启用了自动完成文本视图,因为当用户开始输入该文本视图时我从服务器启动得到的数据得到了过滤,到目前为止每件事都运行正常,但每次我来到同一个活动我的服务开始执行我只想让我的服务只接听一次,用户也可以从自动完成搜索我的数据来自服务器后的文本视图。

MyActivity代码

@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;


        }



    }

因为来自服务器的数据太大,我不希望它存储在本地数据库中。我的代码正在运行,但每次我来到活动时,服务调用都会被执行,这是我不想要的。请指导我

1 个答案:

答案 0 :(得分:-1)

使用Application类:)应用程序类在应用程序的整个生命周期中执行一次:)这意味着在启动应用程序时会调用onCreate of Application类,并在您杀死应用程序时调用onDestroy:)

所以Application类在你的应用程序的整个生命周期中都是持久的:)我相信你需要的东西:)

在应用程序类的OnCreate()中调用您的服务:)一旦获得数据将其保存在Application类的属性中:)所以每当您回到Activity时,都会从Application类的属性中读取数据:)

以下是你可以做的事情:)

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;
    }
}

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

<application
    android:name=".yourApplicationName"

并在你的

私有类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);
       }
  }

希望我在那里得到一点帮助:)快乐的编码伙伴:)