bindService给我假

时间:2019-05-10 17:24:43

标签: android sockets android-intent

绑定服务总是在我的项目的一部分中返回false ...我有2个需要连接到服务以推断某些数据的类,第一个类没有问题地连接,而第二个类可以工作具有相同的socketService,并且应该以不起作用的相同方式进行连接,bindService始终返回false。

这是我上课时遇到的问题:

@Override
    public void onData(ScanDataCollection scanDataCollection) {
        // Process the scanned data in a background thread using AsyncTask
        new AsyncDataUpdate().execute(scanDataCollection);
        Intent mIntent = new Intent(this,SocketService.class);

        bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
    }

这是所有类:

package com.app.test;

import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentTransaction;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;


import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;


import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.StrictMode;


import android.support.v7.app.AppCompatActivity;


import android.util.Log;


import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;


import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKManager.EMDKListener;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.ProfileManager;
import com.symbol.emdk.barcode.BarcodeManager;
import com.symbol.emdk.barcode.ScanDataCollection;
import com.symbol.emdk.barcode.Scanner;
import com.symbol.emdk.barcode.Scanner.DataListener;
import com.symbol.emdk.barcode.Scanner.StatusListener;
import com.symbol.emdk.barcode.ScannerConfig;
import com.symbol.emdk.barcode.ScannerException;
import com.symbol.emdk.barcode.ScannerInfo;
import com.symbol.emdk.barcode.ScannerResults;
import com.symbol.emdk.barcode.StatusData;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.lang.Object;

import com.app.test.SocketService.*;


public class Barcode extends AppCompatActivity implements EMDKListener, StatusListener, DataListener, DialogoEdit.ExampleDialogListener {
    private static ArrayList<String> aBarcode;
    public String cJson;
    private Button mIndietroBtn;
    private String profileName = "farma";
    private ProfileManager profileManager = null;
    private EMDKManager emdkManager = null;
    private String cDati;
    boolean mBounded;
    private Handler handler;
    private String TAG = "BARCODE ";
    private String cProdotto;
    private ImageButton mButtonMenu;
    private String cPopup;
    //private TextView textBarcode;
    // public static Barcode myTabLayout;
    private String lblScanString;
    private ImageButton btnAdd;
    private ImageButton imgRem;
    private ImageButton imgEdit;
    private ImageButton imgProd;
    private String txtMinsan;
    private String cServerMsg = "";
    final Context context = this;
    private TextView view;
    private static ArrayList<String> aProdotto;
    private static final String CHECK_ROTAZIONE = "rotazione";
    private static final String STATE_ITEMS = "items";
    private static ArrayAdapter<String> lblScanData;
    private String triggerString = "SOFT";
    Map<String, String> map = new HashMap<String, String>();
    private BarcodeManager barcodeManager = null;
    private TextView textViewStatus = null;
    private Scanner scanner = null;
    private Spinner spinnerScannerDevices = null;
    private TextView outputNome;
    private String outputMinsan;
    private List<String> listaM = new ArrayList<>();
    public SocketService s;
    private List<ScannerInfo> deviceList = null;
    private ArrayAdapter<String> arrayAdapter;
    public String cChiave;
    private TextView rigaProd = null;
    private String result;
    private String test;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        getSupportActionBar().hide();
        setContentView(R.layout.barcode);
        EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
        if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
            Log.i("Status: ", "EMDKManager object request failed!");
        }

        Bundle bundle = this.getIntent().getExtras();
        cChiave = bundle.getString("cerca");
        cJson = bundle.getString("Json");
        bundle.putString("Json", cJson);
        outputNome = findViewById(R.id.textBarcode);
        rigaProd = findViewById(R.id.lblScanData);
        arrayAdapter = new ArrayAdapter(this, R.layout.rowbarcode, R.id.lblScanData, listaM);
        ListView lv = findViewById(R.id.listaProd);
        lv.setAdapter(arrayAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String riga = (String) parent.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(), riga, Toast.LENGTH_SHORT).show();
            }
        });
        Handler handler = new ResultBarcode();
        MyThread thr = new MyThread(handler);
        thr.start();


        btnAdd = this.findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnCliccato();
            }
        });
        aBarcode = new ArrayList<String>();
        LinearLayout bgProd = (LinearLayout) findViewById(R.id.barcode);
        bgProd.setBackgroundColor(Color.parseColor(TabLogin.bgColor));

        // cambiando il background perdiamo il corner radius, quindi dobbiamo rimetterlo
        GradientDrawable gd = new GradientDrawable();
        gd.setColor(Color.parseColor(TabLogin.tvBgColor));
        gd.setCornerRadius(7);
        gd.setStroke(1, Color.parseColor("#C0C0C0"));

        TextView outputPezzi = findViewById(R.id.testo_pz);
        outputPezzi.setText(map.get("C111"));
        outputPezzi.setTextColor(Color.parseColor(TabLogin.tvFgColor));

        addScanButtonListener();

        mButtonMenu = TabLogin.myTabLayout.findViewById(R.id.altro);
        mButtonMenu.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final PopupMenu dropDownMenu = new PopupMenu(Barcode.this, mButtonMenu);
                dropDownMenu.getMenuInflater()
                        .inflate(R.menu.barcode_nav, dropDownMenu.getMenu());
                dropDownMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        int id = item.getItemId();
                        switch (id) {
                            case R.id.modGiac:

                                break;
                            case R.id.spOrd:

                                break;
                            case R.id.rInt:

                                break;
                            case R.id.vendita:

                                break;
                            case R.id.scProd:

                                break;
                            case R.id.delProd:
                                SvuotaElenco();
                                break;
                            case R.id.exit:

                                Chiudi();
                                break;

                        }
                        return Barcode.super.onMenuItemSelected(id, item);
                    }
                });

                dropDownMenu.show(); //showing popup menu

            }

        });

        mIndietroBtn = TabLogin.myTabLayout.findViewById(R.id.resultback_tit);
        mIndietroBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(Barcode.this, TabLogin.class);
                Bundle bundle = new Bundle();
                bundle.putString("Json", cJson);
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                i.putExtras(bundle);
                startActivity(i);
                finish();

            }
        });

        IntentFilter filter = new IntentFilter();
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        filter.addAction(getResources().getString(R.string.dw_action));
        registerReceiver(myBroadcastReceiver, filter);

        imgRem = findViewById(R.id.imgRem);
        imgRem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(Barcode.this, "test", Toast.LENGTH_SHORT).show();
            }
        });
        imgEdit = findViewById(R.id.imgEdit);
        imgEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(Barcode.this, "test", Toast.LENGTH_SHORT).show();
            }
        });
        imgProd = findViewById(R.id.imgPz);
        imgProd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(Barcode.this, "test", Toast.LENGTH_SHORT).show();
            }
        });


    }

    // Listener for scan button that uses soft scan to scan barcodes through app
    private void addScanButtonListener() {
        Button scanButton = (Button) findViewById(R.id.buttonStartScan);
        // On Touch listener for scan button that scans barcodes when pressed
        // and stops
        // scanning when the button is released
        scanButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // Scan Button Press Event
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    try {
                        // Enable Soft scan
                        scanner.triggerType = Scanner.TriggerType.SOFT_ONCE;
                        // cancel any pending reads before reading barcodes
                        if (scanner.isReadPending())
                            scanner.cancelRead();
                        // Puts the device in a state where it can scan barcodes
                        scanner.read();
                    } catch (ScannerException e) {
                        e.printStackTrace();
                    }
                    // Scan Button Release Event
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    try {
                        // cancel any pending reads before reading barcodes
                        if (scanner.isReadPending())
                            scanner.cancelRead();
                    } catch (ScannerException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });
    }

    public void btnCliccato() {

        FragmentTransaction ft = getFragmentManager().beginTransaction();
        Fragment prev = getFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);

        DialogFragment dialogFragment = new DialogoEdit();
        dialogFragment.show(ft, "dialog");
    }

    @Override
    public void applyTexts(String txtMinsan) {
        PutCampi(txtMinsan);
    }


    private class ResultBarcode extends Handler {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            if (bundle.containsKey("riceprod")) {
                String value = bundle.getString("riceprod");
                outputNome.setText(value);
            }
        }
    }

    ServiceConnection mConnection = new ServiceConnection() {


        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBounded = false;
            Log.i("BARCODE","DISCONNESSO");

        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            /*SocketService.LocalBinder myBinder = (SocketService.LocalBinder) service;
            s = myBinder.getService();*/
            mBounded = true;
            LocalBinder mLocalBinder = (LocalBinder)service;
            s = mLocalBinder.getServerInstance();
            Log.i("BARCODE","CONNESSO");
        }
    };

    @Override
    public void onData(ScanDataCollection scanDataCollection) {
        // Process the scanned data in a background thread using AsyncTask
        new AsyncDataUpdate().execute(scanDataCollection);
        Intent mIntent = new Intent(this,SocketService.class);
        Log.i("vari test Int","" + mIntent);
        //startService(mIntent);
        Log.i("vari test mConn",""+mConnection);
        Log.i("vari test mBin",""+Context.BIND_AUTO_CREATE);
        bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
        Log.i("BARCODE CONNECTION   ",""+bindService(mIntent, mConnection, BIND_AUTO_CREATE));
    }

    @Override
    public void onOpened(EMDKManager emdkManager) {
        this.emdkManager = emdkManager;

        try {
            initializeScanner();
        } catch (ScannerException e) {
            e.printStackTrace();
        }

        Toast.makeText(Barcode.this, "Press Hard Scan Button to start scanning...", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClosed() {
        if (this.emdkManager != null) {
            this.emdkManager.release();
            this.emdkManager = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }
    }


    @Override
    public void onStatus(StatusData statusData) {
        // Process the scan status event on the background thread using AsyncTask
        new AsyncStatusUpdate().execute(statusData);
    }

    private class AsyncDataUpdate extends AsyncTask<ScanDataCollection, Void, String> {

        @Override
        protected String doInBackground(ScanDataCollection... params) {

            String barcodeData = "";

            ScanDataCollection scanDataCollection = params[0];

            if ((scanDataCollection != null) && (scanDataCollection.getResult() == ScannerResults.SUCCESS)) {
                ArrayList<ScanDataCollection.ScanData> scanDatas = scanDataCollection.getScanData();

                for (ScanDataCollection.ScanData data : scanDatas) {
                    barcodeData = data.getData();
                    Log.i("status string: ", barcodeData);

                    ScanDataCollection.LabelType labelType = data.getLabelType();

                }
            }

            return barcodeData;
        }

        @Override
        protected void onPostExecute(String result) {
            String risultato = PutCampi(result);
            Log.i("Risultato ", risultato);
        }
    }

    public String PutCampi(String barcode) {

        //prodotto
        JSONArray aProdotto = new JSONArray();
        try {
            aProdotto.put("");
            aProdotto.put(barcode);
            aProdotto.put("1");
            //System.out.println("info aProdotto"+cChiave);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //campi
        JSONArray aCampi = new JSONArray();
        try {

            aCampi.put("C111");
            aCampi.put("C134");
            aCampi.put("C116");
            aCampi.put("C141");
            aCampi.put("Prezzi2");
            aCampi.put("Prezzi21");

        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONArray aDati = new JSONArray();
        try {

            aDati.put(aProdotto);

            //archivio
            aDati.put("");

            aDati.put(aCampi);
            //Log.i("aDati",""+aDati);

        } catch (Exception e) {
            e.printStackTrace();
        }

        cDati = "riceprod: " + aDati.toString();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                long endTime = System.currentTimeMillis() + 10000;
                Log.i("Dati in barcode ", cDati);

                try {
                    s.sendMessage(cDati);
                    while (cServerMsg.isEmpty()) {
                        cServerMsg = s.line;
                        Log.i("Dati in cServer: ", cServerMsg);
                        cPopup = "Nessun prodotto trovato";


                        if (endTime < System.currentTimeMillis()) {
                            cServerMsg = "[]";
                            Log.i("Dati in cServer: ", cServerMsg);
                            cPopup = "Non è stato possibile completare l'operazione. Si prega riprovare più tardi.";
                        }
                        Log.i("cServerMsg", "" + cServerMsg);
                        if (cServerMsg.equals("[]")) {

                            Toast.makeText(Barcode.this, cPopup, Toast.LENGTH_LONG).show();

                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            }, 500); // durata del timeout


        return cServerMsg;
    }

    private class AsyncStatusUpdate extends AsyncTask<StatusData, Void, String> {

        @Override
        protected String doInBackground(StatusData... params) {
            String statusStr = "";

            StatusData statusData = params[0];
            StatusData.ScannerStates state = statusData.getState();

            switch (state) {
                case IDLE:
                    statusStr = "The scanner enabled and its idle";
                    // Start an async scan
                    /*try {
                        // An attempt to use the scanner continuously and rapidly (with a delay < 100 ms between scans)
                        // may cause the scanner to pause momentarily before resuming the scanning.
                        // Hence add some delay (>= 100ms) before submitting the next read.
                        try {
                            Thread.sleep(100);
                            scanner.read();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                       // scanner.read();
                    } catch (ScannerException e) {
                        statusStr = e.getMessage();
                    }*/

                    break;
                case SCANNING:
                    statusStr = "Scanning...";
                    break;
                case WAITING:
                    statusStr = "Waiting for trigger press...";
                    break;
                case DISABLED:
                    statusStr = "SCanner is not enabled";
                    break;
                default:
                    break;
            }

            return statusStr;
        }


        @Override
        protected void onPostExecute(String result) {
            Log.i("Status", result);
        }
    }

    private void initializeScanner() throws ScannerException {
        if (scanner == null) {

            // Get a reference to the barcode Manager object
            barcodeManager = (BarcodeManager) this.emdkManager.getInstance(EMDKManager.FEATURE_TYPE.BARCODE);



            // Select the default scanner as defined on the device
            scanner = barcodeManager.getDevice(BarcodeManager.DeviceIdentifier.DEFAULT);

            // Add Data and Status Listeners
            scanner.addDataListener(this);
            scanner.addStatusListener(this);

            // Select Trigger mode
            scanner.triggerType = Scanner.TriggerType.HARD;
            scanner.enable();
            try {
                ScannerConfig config = scanner.getConfig();
                config.decoderParams.code39.enabled = true;
                scanner.setConfig(config);
            } catch (ScannerException e) {
                e.printStackTrace();
            }

            // start an asynchronous scan.
            scanner.read();
        }
    }

    private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //System.out.println("info su decodedData : " + action);
            if (action.equals(getResources().getString(R.string.dw_action))) {
                //displayScanResult(intent);
            }
        }
    };

    private void GetProdotto(String result) {


    }

    private void Chiudi() {

        Intent i = new Intent(Barcode.this, Scollega.class);
        startActivity(i);
    }

    private void SvuotaElenco() {

        arrayAdapter.clear();

    }


    private void GeneraVendita() {

    }

    private void ModiGiac() {

    }

    private void GeneraSpunta() {

    }

    private void OrdineInterno() {

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (mBounded) {
            unbindService(mConnection);
            mBounded = false;
        }

        try {
            if (scanner != null) {
                scanner.disable();
                scanner = null;
            }
        } catch (ScannerException e) {
            e.printStackTrace();
        }
    }
}

你有什么主意吗?

0 个答案:

没有答案