我正在制作一个应用程序,通过pubnub服务器向订阅同一频道的用户发送实时消息。我有它的工作,这样我就可以从一个设备发送字符串到另一个设备,但现在我想发送GPS信息。用户将输入一个字符串"GPS",这将触发一种方法,然后发送位置信息,而不是该字符串。我在这个部分遇到了问题,因为没有显示错误,但当我试图打开它时,应用程序崩溃了。我尝试过调试,但我能找出问题所在。在我完成oncreate方法之后,调试器会将我从活动中转移到嵌入在java中的其他java类文件中。如有任何帮助或反馈,我们将不胜感激,谢谢!
我在logcat中发现了一些错误:
ADB:
ddms: null
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:182)
at com.android.ddmlib.JdwpPacket.movePacket(JdwpPacket.java:235)
at com.android.ddmlib.Debugger.sendAndConsume(Debugger.java:347)
at com.android.ddmlib.Client.forwardPacketToDebugger(Client.java:698)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:344)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
设备LogCat:
03-20 15:44:56.780 15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ Function: selinux_android_load_priority [0], There is no sepolicy file
03-20 15:44:56.780 15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ Function: selinux_android_load_priority [1], There is no sepolicy version file
03-20 15:44:56.780 15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ Function: selinux_android_load_priority , loading version is VE=SEPF_SAMSUNG-SGH-I257_4.2.2_0025
03-20 15:44:56.780 15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ selinux_android_seapp_context_reload: seapp_contexts file is loaded from /seapp_contexts
java.lang.RuntimeException: Unable to resume activity {com.example.kunalpatel.pubsub/com.example.kunalpatel.pubsub.MainActivity}: java.lang.ClassCastException: com.example.kunalpatel.pubsub.MainActivity cannot be cast to android.location.LocationListener
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2835)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2864)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.access$700(ActivityThread.java:152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.example.kunalpatel.pubsub.MainActivity cannot be cast to android.location.LocationListener
at com.example.kunalpatel.pubsub.MainActivity.onResume(MainActivity.java:221)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1202)
at android.app.Activity.performResume(Activity.java:5404)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2825)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2864)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.access$700(ActivityThread.java:152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.pubnub.api.Callback;
import com.pubnub.api.Pubnub;
import com.pubnub.api.PubnubError;
import com.pubnub.api.PubnubException;
public class MainActivity extends ActionBarActivity {
//Button to subscribe to user specified pubnub channel
private Button channelSubscribeButton;
private EditText subscribeChannelEditText;
private TextView messageLogTextView;
//Button to send message to other devices subscribed on same channel
private Button sendMessageButton;
private EditText sendMessageEditText;
private LocationManager locationManager;
private String provider;
private double lat;
private double lon;
private double accuracy;
private MainActivity activity;
//-------------------------Access PubNub API-------------------------//
//pubnub publish and subscribe keys
Pubnub pubnub = new Pubnub("pub-c-", "sub-c");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Subscribing and sending messages
channelSubscribeButton = (Button) findViewById(R.id.subscribe_button);
subscribeChannelEditText = (EditText) findViewById(R.id.channel_name);
messageLogTextView = (TextView) findViewById(R.id.message_log_text_view);
sendMessageButton = (Button) findViewById(R.id.send_message_button);
sendMessageEditText = (EditText) findViewById(R.id.message_edit_text);
activity = this;
//Get location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Define criteria for how to select the location provider --> use default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
//Prints GPS provider if there is or isn't one
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
//messageLogTextView.append("GPS Information Not Available");
}
}
@Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onChannelButtonClick(View view) {
//Get the user inputted text in
String subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
String yourSubscribeChannel = "Subscribed to the " + subscribeChannel + " Channel";
Toast.makeText(this, yourSubscribeChannel, Toast.LENGTH_SHORT).show();
try {
pubnub.subscribe(subscribeChannel, new Callback() {
@Override
public void connectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : CONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
@Override
public void disconnectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : DISCONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
public void reconnectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : RECONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
//Updates textview with message
@Override
public void successCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());
updateTextView(message.toString() + "n");
}
@Override
public void errorCallback(String channel, PubnubError error) {
Log.d("PUBNUB", "SUBSCRIBE : ERROR on channel " + channel
+ " : " + error.toString());
}
}
);
} catch (PubnubException e) {
Log.d("PUBNUB", e.toString());
}
}
public void updateTextView(final String message) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try{
messageLogTextView.append(message);
} catch(Exception ex) {
Log.d("pubnub", ex.getMessage());
}
messageLogTextView.setMovementMethod(new ScrollingMovementMethod());
}
});
}
public void onSendMessageButtonClick(View view, Location location) {
String messageToSend = String.valueOf(sendMessageEditText.getText());
Callback callback = new Callback() {
public void successCallback(String channel, Object response) {
}
public void errorCallback(String channel, PubnubError error) {
Log.d("PUBNUB", error.toString());
}
};
String subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
pubnub.publish(subscribeChannel, messageToSend, callback);
//if the user input string is equal to "GPS" then initialize the onLocationChanged method
//if not, print to the string to the log textview
if(messageToSend.equals("GPS")) {
//Print to the textview log the onLocationChanged
onLocationChanged(location);
} else {
updateTextView("GPS cannot be retrieved");
}
}
@Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, (LocationListener) this);
}
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates((LocationListener) this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
//TODO Auto-generated method stub
}
//method to retrieve location information
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
float accuracy = (float) (location.getAccuracy());
double alt = (double) (location.getAltitude());
double speed = (double) (location.getSpeed());
double heading = (double) (location.getBearing());
messageLogTextView.append(String.valueOf(lat));
messageLogTextView.append(String.valueOf(lng));
messageLogTextView.append(String.valueOf(accuracy));
messageLogTextView.append(String.valueOf(alt));
messageLogTextView.append(String.valueOf(speed ));
messageLogTextView.append(String.valueOf(heading ));
}
}
您的错误是(在您提供的堆栈跟踪的中间):
Caused by: java.lang.ClassCastException: com.example.kunalpatel.pubsub.MainActivity cannot be cast to android.location.LocationListener
at com.example.kunalpatel.pubsub.MainActivity.onResume(MainActivity.java:221)
检查MainActivity.onResume
,结果发现您正在将MainActivity
转换为LocationListener
。如果您希望能够将MainActivity
传递给locationManager.requestLocationUpdates
,则需要实现LocationListener
。
要执行此操作,请首先查看文档中的LocationListener。有四种抽象方法,到目前为止您已经实现了其中的两种——onStatusChanged
和onLocationChanged
。您需要实现onProviderEnabled
和onProviderDisabled
。然后,将类声明更改为:
public class MainActivity extends ActionBarActivity implements LocationListener