gpt4 book ai didi

java - 无法从服务调用共享首选项

转载 作者:行者123 更新时间:2023-11-29 04:40:56 26 4
gpt4 key购买 nike

您好,我正在尝试在 select_Visitor 方法中从绑定(bind)服务调用共享首选项。

服务方式

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


SharedPreferences mySharedPreferences = getSharedPreferences("preferences", Activity.MODE_PRIVATE);
String Profild = mySharedPreferences.getString("ProfileId", "Not defined");


Log.d("Inside : ", "select_Visitor - service - Method");
Log.d("Inside : ", Profild);

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

}

错误

    FATAL EXCEPTION: main
FATAL EXCEPTION: main
Process: zupportdesk.desk.zupport.chatsystem, PID: 14117
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:171)
at zupportdesk.desk.zupport.chatsystem.Services.SignalRService.select_Visitor(SignalRService.java:106)
at zupportdesk.desk.zupport.chatsystem.ChatsTab.incomming_item_clicked(ChatsTab.java:97)
at zupportdesk.desk.zupport.chatsystem.Data.IncommingChatsViewHolders.onClick(IncommingChatsViewHolders.java:54)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21155)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

全方位服务

/**
* 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){


SharedPreferences mySharedPreferences = getSharedPreferences("preferences", Activity.MODE_PRIVATE);
String Profild = mySharedPreferences.getString("ProfileId", "Not defined");


Log.d("Inside : ", "select_Visitor - service - Method");
Log.d("Inside : ", Profild);

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", "", 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());
}
});

}

}

Activity 调用方法 - (incomming_item_clicked)

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

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

}

最佳答案

private SignalRService mService = new SignalRService();

要启动服务,请使用 IntentstartService(),而不是 new

使用 new 实例化的

Service 没有设置任何你想要 Service 的东西,比如用作 上下文

关于java - 无法从服务调用共享首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39224785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com