在没有刷新的情况下调用服务中的方法

时间:2016-08-30 07:46:20

标签: java android service

我有一个recyclerview和一个bondservice运行。当在recyclerview上单击某个项目时,我想在服务中调用该方法。我试过但不工作

当从Recyclerview点击某个项目时,将调用点击项目事件( onClick(视图视图))上的视图持有者。从那里我想从我的共享首选项中获取一些值,然后调用服务中的方法。

当我尝试将服务中的sharedpreferences的值提取到 select_Visitor 时,方法为null。 (但这些值在共享首选项中可用)。还有其他方法可以做到这一点。

这就是我尝试的方式。

服务类

var data :any;
  constructor(public location: Location,public config:Config,public router: Router, public http: Http, fbld: FormBuilder,public toastr: ToastsManager) {

    console.log(this.config.header);

活动类

/**
 * Created by baman on 8/19/16.
 */
public class SignalRService extends Service {
    private HubConnection mHubConnection;
    private HubProxy mHubProxy;
    private Handler mHandler; // to display Toast message
    private final LocalBinder mBinder = new LocalBinder();
    public Boolean is_service_connected = false;
    public  String ProfileId;
    public  String profileToken;
    public  String CompanyID;
    public  String DisplayName;


    public SignalRService() {
        mHubConnection = new HubConnection("chatHub");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("service", "Inside oncreate  - service");

        SharedPreferences prefs = getSharedPreferences("zupportdesk", MODE_PRIVATE);
        ProfileId = prefs.getString("ProfileId", "Not defined");
        profileToken = prefs.getString("profileToken", "Not defined");
        CompanyID = prefs.getString("companyId", "Not defined");
        DisplayName = prefs.getString("DisplayName", "Not defined");
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("service", "service start  - service");
        int result = super.onStartCommand(intent, flags, startId);
        startSignalR();
        return result;
    }

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

    @Override
    public IBinder onBind(Intent intent) {
        // Return the communication channel to the service.
        Log.d("service", "onBind  - service");
        startSignalR();
        return (IBinder) mBinder;
    }

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        public SignalRService getService() {
            // Return this instance of SignalRService so clients can call public methods
            return SignalRService.this;
        }
    }

    /**
     * method for clients (activities)
     */
    private void getIncommingcht(){
        Log.d("Inside : ", "getIncommingcht - service - Method");
        mHubProxy.invoke("addOperatorsToGroup", ProfileId, CompanyID, "true", profileToken);
        mHubProxy.invoke("GetIncomingChatQueue",ProfileId, profileToken);
    }

    public void select_Visitor(String visitor_id, String ProfileId, String CompanyID, String DisplayName, String profileToken, String startTime){

        Log.d("Inside : ", "select_Visitor - service - Method");
        String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

        mHubProxy.invoke("selectVisitor", visitor_id, ProfileId, CompanyID, DisplayName, timeStamp, profileToken, startTime);

    }

    private void startSignalR() {
        // Create a new console logger
        Logger logger = new Logger() {
            @Override
            public void log(String message, LogLevel level) {
                Log.d("Log Message : ", message);
            }
        };
        // Connect to the server
        HubConnection conn = new HubConnection("My URL Here", "", true, logger);
        // Create the hub proxy
        HubProxy proxy = conn.createHubProxy("chatHub");
        mHubProxy = proxy;
        Subscription subscription = proxy.subscribe("getVisitorResponse");
        subscription.addReceivedHandler(new Action<JsonElement[]>(){
            public void run(JsonElement[] eventParameters) throws Exception {
                    Log.d("eventParameters - data", String.valueOf(eventParameters[0]));
                    Log.d("eventParameters - time", String.valueOf(eventParameters[1]));
                IncommingFragment.getVisitorResponse(eventParameters[0]);
            }
        });

        Subscription subscription1 = proxy.subscribe("recieveIncomingChat");
        subscription1.addReceivedHandler(new Action<JsonElement[]>(){
            public void run(JsonElement[] eventParameters) throws Exception {
                Log.d("eventParameters - data", String.valueOf(eventParameters[0]));
                IncommingFragment.receivedincommingchats(eventParameters[0]);
            }
        });

//        proxy.subscribe(new Object() {
//            @SuppressWarnings("unused")
//            public void recieveIncomingChat(RecieveIncomingchats recieveIncomingchats) {
//                MainFragment.receivedincommingchats(recieveIncomingchats);
//                Log.d("hit:", "Hit on receive Incoming chats");
//            }
//
//            @SuppressWarnings("unused")
//            public void serviceStatus(boolean temp){
//                Log.d("service_status", "status called");
//            }
//        });

        // Subscribe to the error event
        conn.error(new ErrorCallback() {
            @Override
            public void onError(Throwable error) {
                error.printStackTrace();
            }
        });

        // Subscribe to the connected event
        conn.connected(new Runnable() {

            @Override
            public void run() {
                System.out.println("CONNECTED");
                is_service_connected = true;
                getIncommingcht();
            }
        });

        // Subscribe to the closed event
        conn.closed(new Runnable() {

            @Override
            public void run() {
                System.out.println("DISCONNECTED");
            }
        });

        // Start the connection
        conn.start().done(new Action<Void>() {
            @Override
            public void run(Void obj) throws Exception {
                System.out.println("Done Connecting!");
            }
        });

        // Subscribe to the received event
        conn.received(new MessageReceivedHandler() {
            @Override
            public void onMessageReceived(JsonElement json) {
                System.out.println("RAW received message: " + json.toString());
            }
        });

    }

}

ViewHolder

public class ChatsTab extends AppCompatActivity {
    private static ChatsTab instance;


    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    private SignalRService mService = new SignalRService();
    private boolean mBound = false;
    private HelpLiveo mHelpLiveo;

    public  String ProfileId;
    public  String profileToken;
    public  String CompanyID;
    public  String DisplayName;


    public ChatsTab getInstance() {
        if(instance==null){
            setInstance(this);
        }
        return instance;
    }

    public static void setInstance(ChatsTab instance) {
        ChatsTab.instance = instance;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chats_tab);
        setInstance(this);


        SharedPreferences prefs = getSharedPreferences("zupportdesk", MODE_PRIVATE);

        String ProfileId = prefs.getString("ProfileId", "Not defined");
        String profileToken = prefs.getString("profileToken", "Not defined");
        String CompanyID = prefs.getString("companyId", "Not defined");
        String DisplayName = prefs.getString("DisplayName", "Not defined");


        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);


        if(!mBound) {
            Intent intent = new Intent();
            intent.setClass(this, SignalRService.class);
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        }
    }



    public void incomming_item_clicked(String visitor_id, String Starttime){
        Log.d("Inside : ", "incomming_item_clicked - Activity - ChatTabs");
        mService.select_Visitor(visitor_id, ProfileId, CompanyID, DisplayName, profileToken, Starttime);
    }


    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new IncommingFragment(), "Incoming");
        adapter.addFragment(new ActiveFragment(), "Active");
        adapter.addFragment(new OtherFragment(), "Other");
        viewPager.setAdapter(adapter);
    }


    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }



    /********************************* Service Methods ********************************************/

    private final ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            Log.d("Activity : ", "Inside service connected - Activity ");
            // We've bound to SignalRService, cast the IBinder and get SignalRService instance
            SignalRService.LocalBinder binder = (SignalRService.LocalBinder) service;
            mService = binder.getService();
            mBound = true;
            Log.d("Activity : ", "bound status - " + mBound);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mService=null;
            mBound = false;
            Log.d("Activity : ", "bound disconnected - status - " + mBound);
        }
    };


    @Override
    protected void onStop() {
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;

            Log.d("Activity : ", "bound disconnecting - status - " + mBound);

            //Kill the app
            super.onStop();
            System.exit(0);
        } super.onStop();
    }

    /**********************************************************************************************/

}

0 个答案:

没有答案