使用 pubnub 制作 android 应用程序以发送 GPS 信息,但应用程序崩溃且未显示任何错误
Making android application using pubnub to send GPS information but app crashes and shows no errors
我正在制作一个应用程序,它通过 pubnub 服务器向订阅同一频道的用户发送实时消息。我让它工作,以便我可以在设备之间发送字符串,但现在我想发送 GPS 信息。用户将输入一个字符串 "GPS" ,这将触发一个方法来发送位置信息而不是该字符串。我在这部分遇到了问题,因为没有显示任何错误,但是当我尝试打开它时应用程序崩溃了。我试过调试,但我能弄清楚出了什么问题。在我跨过 oncreate 方法之后,调试器将我从我的 activity 中带出并进入 java class 中嵌入的其他 java 文件。非常感谢任何帮助或反馈,谢谢!
我在 logcat 中发现的一些错误:
亚行:
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.access0(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.access0(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
。然后,将您的 class 声明更改为:
public class MainActivity extends ActionBarActivity implements LocationListener
我正在制作一个应用程序,它通过 pubnub 服务器向订阅同一频道的用户发送实时消息。我让它工作,以便我可以在设备之间发送字符串,但现在我想发送 GPS 信息。用户将输入一个字符串 "GPS" ,这将触发一个方法来发送位置信息而不是该字符串。我在这部分遇到了问题,因为没有显示任何错误,但是当我尝试打开它时应用程序崩溃了。我试过调试,但我能弄清楚出了什么问题。在我跨过 oncreate 方法之后,调试器将我从我的 activity 中带出并进入 java class 中嵌入的其他 java 文件。非常感谢任何帮助或反馈,谢谢!
我在 logcat 中发现的一些错误:
亚行:
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.access0(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.access0(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
。然后,将您的 class 声明更改为:
public class MainActivity extends ActionBarActivity implements LocationListener