Java Android Home和Back按钮使我的应用程序崩溃
我是Android编程的初学者。在我的小模型应用程序中,MainActivity通过GPS抛出一个服务生成位置。 当位置由Android Studio的设备监视器生成时,该应用程序在虚拟设备(API 16)上运行良好。 但如果我按下HOME或BACK按钮,应用程序就会崩溃,我不知道为什么 你能帮我吗?请原谅我的英语不好 非常感谢 守则: MainActivity.java 包com.jacky.colbakJava Android Home和Back按钮使我的应用程序崩溃,java,android,Java,Android,我是Android编程的初学者。在我的小模型应用程序中,MainActivity通过GPS抛出一个服务生成位置。 当位置由Android Studio的设备监视器生成时,该应用程序在虚拟设备(API 16)上运行良好。 但如果我按下HOME或BACK按钮,应用程序就会崩溃,我不知道为什么 你能帮我吗?请原谅我的英语不好 非常感谢 守则: MainActivity.java 包com.jacky.colbak import android.app.Activity; import android.
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.TextView;
public class MainActivity extends Activity implements IServListener {
private GpsServ gpsServ;
private boolean bound = false;
private IServListener listener;
private TextView latitude = null;
private TextView longitude = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitude = (TextView)findViewById(R.id.vLat);
longitude = (TextView)findViewById(R.id.vLong);
}
@Override
protected void onStart() {
super.onStart();
// Bind to GpsServ service
Intent intent = new Intent(this, GpsServ.class);
startService(intent);
}
@Override
protected void onResume() {
super.onResume();
listener =(IServListener) this;
// bindService va mettre à jour bound et rentrer listener dans IServ
Intent intent = new Intent(this, GpsServ.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onPause() {
unbindService(mConnection);
super.onPause();
}
@Override
protected void onStop() {
// Unbind from the service
if (bound) {
unbindService(mConnection);
}
super.onStop();
}
protected void onDestroy() {
Intent intent = new Intent(this, GpsServ.class);
stopService(intent);
super.onDestroy();
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
GpsServ.LocalBinder binder = (GpsServ.LocalBinder) service;
gpsServ = binder.getService();
bound = true;
((IServ) gpsServ).addListener(listener);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
((IServ)gpsServ).delListener();
}
};
public void refresh() {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
// Mise à jour de l'UI
maj();
}
});
}
public void maj() {
String str = Location.convert(gpsServ.dLat, Location.FORMAT_SECONDS);
latitude.setText(str);
str= Location.convert(gpsServ.dLong, Location.FORMAT_SECONDS);
longitude.setText(str);
}
}
// Voici le code du service GpsServ.java
package com.jacky.colbak;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
public class GpsServ extends Service implements LocationListener, IServ {
private final IBinder binder = new LocalBinder();
private IServListener iServListener = null;
private LocationManager locMngr;
public double dLat, dLong;
@Override
public void onCreate() {
Toast.makeText(getBaseContext(), "Service créé ! ", Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
gpsJob();
}
}).run();
return START_STICKY;
}
private void gpsJob() {
locMngr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getBaseContext(), "LocationUpdates non créé (permissions refusées)! ", Toast.LENGTH_SHORT).show();
return;
}
locMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, (long) 10000, (float) 10.0, this);
Toast.makeText(getBaseContext(), "Service créé ! ", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
iServListener = null;
locMngr.removeUpdates(this);
locMngr = null;
super.onDestroy();
}
// Class used for the client Binder.
public class LocalBinder extends Binder {
GpsServ getService() {
// Return this instance of GpsServ service so clients can call public methods
return GpsServ.this;
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return binder;
}
// Implementation des fonctions de LocationListener et notification au(x) listeners
@Override
public void onLocationChanged(Location location) {
Toast.makeText(getBaseContext(), "Location Changed ", Toast.LENGTH_SHORT).show();
dLat = location.getLatitude();
dLong = location.getLongitude();
if(iServListener != null){
Toast.makeText(getBaseContext(), "Il y a un listener et on rafraichi ! ", Toast.LENGTH_SHORT).show();
iServListener.refresh();
}
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
// startActivity(intent);
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(getBaseContext(), "GpsServ is turned ON!! ", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
String msg = provider + " Status changed: " + status;
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
// Implementation de de IServ
// Ajout d'un listener issu d'une vue
public void addListener(IServListener listener) {
iServListener = listener;
}
//
// Suppression d'un listener
public void delListener() {
iServListener = null;
}
}
// Fichier ISev.java
package com.jacky.colbak;
/**
* Created by Jacky on 18/04/2016.
*/
public interface IServ {
public void addListener(IServListener listener);
public void delListener();
}
// Fichier IServListener.java
package com.jacky.colbak;
/**
* Created by Jacky on 14/04/2016.
*/
public interface IServListener {
public void refresh();
}
// File manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jacky.colbak">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".GpsServ"
android:enabled="true"
android:exported="true">
</service>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
// File activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.jacky.colbak.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Longitude"
android:id="@+id/txtLong"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="148dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/vLong"
android:layout_alignTop="@+id/txtLong"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="73dp"
android:layout_marginEnd="73dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Latitude"
android:id="@+id/tLat"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/vLat"
android:layout_alignTop="@+id/tLat"
android:layout_alignLeft="@+id/vLong"
android:layout_alignStart="@+id/vLong" />
</RelativeLayout>
导入android.app.Activity;
导入android.content.ComponentName;
导入android.content.Context;
导入android.content.Intent;
导入android.content.ServiceConnection;
导入android.location.location;
导入android.os.Bundle;
导入android.os.IBinder;
导入android.widget.TextView;
公共类MainActivity扩展活动实现IServListener{
私人GpsServ GpsServ;
私有布尔边界=false;
私有IServListener侦听器;
私有文本视图纬度=空;
私有文本视图经度=null;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
纬度=(TextView)findViewById(R.id.vLat);
经度=(TextView)findViewById(R.id.vLong);
}
@凌驾
受保护的void onStart(){
super.onStart();
//绑定到GpsServ服务
意向意向=新意向(此,GpsServ.class);
startService(意向);
}
@凌驾
受保护的void onResume(){
super.onResume();
listener=(IServListener)这个;
//bindService va mettreájour bound et renterr listener dans IServ
意向意向=新意向(此,GpsServ.class);
bindService(intent、mConnection、Context.BIND\u AUTO\u CREATE);
}
@凌驾
受保护的void onPause(){
解除绑定服务(mConnection);
super.onPause();
}
@凌驾
受保护的void onStop(){
//解除服务绑定
如果(绑定){
解除绑定服务(mConnection);
}
super.onStop();
}
受保护的空onDestroy(){
意向意向=新意向(此,GpsServ.class);
停止服务(意向);
super.ondestory();
}
/**定义服务绑定的回调,传递给bindService()*/
专用ServiceConnection mConnection=新ServiceConnection(){
@凌驾
服务连接上的公共无效(组件名称类名称,IBinder服务){
//我们已经绑定到LocalService,强制转换IBinder并获取LocalService实例
GpsServ.LocalBinder=(GpsServ.LocalBinder)服务;
gpsServ=binder.getService();
绑定=真;
((IServ)gpsServ.addListener(listener);
}
@凌驾
ServiceDisconnected上的公共无效(组件名称arg0){
绑定=假;
((IServ)gpsServ.delListener();
}
};
公共无效刷新(){
MainActivity.this.runOnUiThread(新的Runnable(){
公开募捐{
//这是我的生日
maj();
}
});
}
公共空间主要(){
String str=Location.convert(gpsServ.dLat,Location.FORMAT_秒);
纬度.setText(str);
str=Location.convert(gpsServ.dLong,Location.FORMAT_秒);
经度.setxt(str);
}
}
//服务GpsServ.java的代码
包com.jacky.colbak;
导入android.Manifest;
导入android.app.Service;
导入android.content.Context;
导入android.content.Intent;
导入android.content.pm.PackageManager;
导入android.location.location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.os.Binder;
导入android.os.Bundle;
导入android.os.IBinder;
导入android.provider.Settings;
导入android.support.v4.app.ActivityCompat;
导入android.widget.Toast;
公共类GpsServ扩展服务实现LocationListener、IServ{
专用最终IBinder绑定器=新的LocalBinder();
专用IServListener IServListener=null;
私人位置经理locMngr;
公共双德拉特,德隆;
@凌驾
public void onCreate(){
Toast.makeText(getBaseContext(),“Service cré!”,Toast.LENGTH_SHORT.show();
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
新线程(newrunnable()){
@凌驾
公开募捐{
gpsJob();
}
}).run();
返回开始时间;
}
私有void gpsJob(){
locMngr=(LocationManager)getSystemService(Context.LOCATION\u服务);
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予和&ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予){
Toast.makeText(getBaseContext(),“LocationUpdates non-créé(permissions refusées)!”,Toast.LENGTH_SHORT.show();
返回;
}
locMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER,(long)10000,(float)10.0,this);
Toast.makeText(getBaseContext(),“Service cré!”,Toast.LENGTH_SHORT.show();
}
@凌驾
公共空间{
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予和&ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予){
返回;
}
iServListener=null;
locMngr.RemoveUpdate(此);
locMngr=null;
super.ondestory();
}
//用于客户端绑定器的类。
公共类LocalBinder扩展了Binder{
GpsServ getService(){
//返回此GpsServ服务实例,以便客户端可以调用公共方法
返回GpsServ.this;
}
}
@凌驾
公共IBinder onBind(意向){
//TODO:将通信通道返回到服务。
//抛出新的UnsupportedOperationException(“尚未实现”);
返回活页夹;
}
//位置侦听器et通知au(x)侦听器的实现
@凌驾
更改了位置上的公共无效(L