我在我的应用程序中使用服务,该服务工作正常。但是当我关闭应用程序(按主页按钮)并再次打开应用程序时,会创建多个服务实例。
我想要的是,当我关闭应用程序时,服务也必须关闭,当我恢复应用程序时,服务必须启动。
但现在,当我关闭并打开应用程序时,它正在创建两个相同服务的实例。
服务
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;
private Context context;
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 boolean onUnbind(Intent intent) {
Log.d("Unbounding", "SignalRservice Service unbound");
return super.onUnbind(intent);
}
@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);
// mHubProxy.invoke("getselectedVisitors", ProfileId, CompanyID, profileToken);
mHubProxy.invoke("getOtherActiveChat", ProfileId, CompanyID, profileToken);
}
public void select_Active_Visitor(String visitor_id, String ProfileId, String CompanyID, String DisplayName, String profileToken, String startTime){
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("https://MY URL/", "", 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("getVisitorResponse-data", String.valueOf(eventParameters[0]));
Log.d("getVisitorResponse-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("IncomingChat_data", String.valueOf(eventParameters[0]));
IncommingFragment.receivedincommingchats(eventParameters[0]);
}
});
Subscription subscription3 = proxy.subscribe("getOtherActiveChats");
subscription3.addReceivedHandler(new Action<JsonElement[]>(){
public void run(JsonElement[] eventParameters) throws Exception {
Log.d("getOtherChats - data", String.valueOf(eventParameters[0]));
OtherFragment.getOtherActiveChats(eventParameters[0]);
}
});
Subscription subscription4 = proxy.subscribe("removeChatQueue");
subscription4.addReceivedHandler(new Action<JsonElement[]>(){
public void run(JsonElement[] eventParameters) throws Exception {
Log.d("removeChatQueue - data", String.valueOf(eventParameters[0]));
IncommingFragment.removeVisitor(String.valueOf(eventParameters[0]));
}
});
Subscription subscription6 = proxy.subscribe("StartTransfer");
subscription6.addReceivedHandler(new Action<JsonElement[]>(){
public void run(JsonElement[] eventParameters) throws Exception {
Log.d("Transfer_visitorID", String.valueOf(eventParameters[0]));
Log.d("Transfer_receivername", String.valueOf(eventParameters[1]));
Log.d("Transfer_receiverID", String.valueOf(eventParameters[2]));
}
});
/*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());
}
});
}
}
活动
public class ChatsTab extends AppCompatActivity {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
ProgressDialog pDialog;
private TabLayout tabLayout;
private ViewPager viewPager;
public static SignalRService mService = new SignalRService();
private boolean mBound;
private HelpLiveo mHelpLiveo;
private ApplicationEnvironmentURL applicationEnvironment;
public static String ProfileId;
public static String profileToken;
public static String CompanyID;
public String DisplayName;
private Context context;
public String BASEURL;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chats_tab);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
applicationEnvironment = new ApplicationEnvironmentURL(this.context);
context = this.getApplicationContext();
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");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
if(!isMyServiceRunning(SignalRService.class)) {
Intent intent = new Intent();
intent.setClass(this, SignalRService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
setCannedResponsesURL(ProfileId, CompanyID);
new getAllcannedResponse().execute(profileToken);
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id){
case R.id.home:
Toast.makeText(getApplicationContext(),"Home",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.settings:
Intent intent_settings = new Intent(getApplication(), Settings.class);
startActivity(intent_settings);
break;
case R.id.canned_responses:
Intent intent2 = new Intent(getApplication(), CannedResponses.class);
startActivity(intent2);
// Toast.makeText(getApplicationContext(),"canned responses",Toast.LENGTH_SHORT).show();
break;
case R.id.Operators:
Intent intent = new Intent(getApplication(), Operators.class);
startActivity(intent);
drawerLayout.closeDrawers();
break;
case R.id.logout:
finish();
}
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView)header.findViewById(R.id.tv_email);
tv_email.setText(DisplayName);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
@Override
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
}
@Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
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() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
Log.d("Activity : ", "bound disconnecting - status - " + mBound);
}
mService.onDestroy();
}
/**********************************************************************************************/
}
答案 0 :(得分:0)
在您的主要活动中创建一个方法
private boolean isMyServiceRunning(Class<?> SignalRService) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (SignalRService.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
并在Main Activity oncreate方法中进行检查
if(isMyServiceRunning(SignalRService.class)== true){
// do nothing
}else{
// Start your service
}
希望它能解决你的问题。