我是Android编程的初学者。在我的小模型应用程序中,MainActivity通过GPS引发服务生成位置。 当Location由Android Studio的Device Monitor生成时,此应用程序在虚拟设备(API 16)上运行良好。 但是,如果我按下HOME或BACK按钮,应用程序崩溃,我不知道为什么?
你可以帮帮我吗?请原谅我可怜的英文!非常感谢
代码: MainActivity.java 包com.jacky.colbak;
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>