Android 安卓服务不是';t起动
我正在开发一个android应用程序来获取位置信息。我想让gps跟踪器在后台每5秒获取一次位置,并在屏幕上显示位置。当我在MainActivity中运行服务时,我的应用程序运行良好。然而,当我想在后台(服务中)使用GPS跟踪器时,它会杀死我的应用程序 以下是我的主要活动:Android 安卓服务不是';t起动,android,service,gps,Android,Service,Gps,我正在开发一个android应用程序来获取位置信息。我想让gps跟踪器在后台每5秒获取一次位置,并在屏幕上显示位置。当我在MainActivity中运行服务时,我的应用程序运行良好。然而,当我想在后台(服务中)使用GPS跟踪器时,它会杀死我的应用程序 以下是我的主要活动: import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButto
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button startButton;
GPSTracker gps;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
startButton = (Button) findViewById(R.id.startButton);
//gps = new GPSTracker(MainActivity.this);
intent = new Intent(this, GPSTracker.class);
//startService(intent);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent = new Intent(this, GPSTracker.class);
startService(intent);
/*if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(
getApplicationContext(),
"Your Location is -\nLat: " + latitude + "\nLong: "
+ longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}*/
}
});
}
@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);
}
}
我的GPSTracker服务:
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class GPSTracker extends Service implements LocationListener {
//private final Context context;
public static final String TAG = "com.timesavii.intent";
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker() {}
//public GPSTracker(Context context) {
//this.context = context;
//getLocation();
//}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand method called");
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0 ; i < 5 ; i++) {
getLocation();
if (canGetLocation()) {
double latitude = getLatitude();
double longitude = getLongitude();
Toast.makeText(
getApplicationContext(),
"Your Location is -\nLat: " + latitude + "\nLong: "
+ longitude, Toast.LENGTH_LONG).show();
} else {
showSettingsAlert();
}
long futureTime = System.currentTimeMillis() + 5000;
while(System.currentTimeMillis() < futureTime)
synchronized (this){
try {
wait(futureTime - System.currentTimeMillis());
}catch(Exception e){}
}
}
}
};
Thread myThread = new Thread(runnable);
myThread.start();
return Service.START_STICKY;
}
public Location getLocation() {
try {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled) {
if(location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if(locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if(location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if(location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getApplicationContext());
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getApplicationContext().startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
请提供一个不使用此类的选项。GPSTracker在很多方面都完全崩溃了。有关原因的解释,请参阅。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.timesavvi.locator">
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.INTERNET" />
<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"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".GPSTracker"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
01-25 15:52:07.170 2408-2408/? D/AndroidRuntime: CheckJNI is ON
01-25 15:52:07.200 2408-2408/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-25 15:52:07.200 2408-2408/? E/android.os.Debug: failed to load memtrack module: -2
01-25 15:52:07.220 2408-2408/? D/AndroidRuntime: Calling main entry com.android.commands.pm.Pm
01-25 15:52:07.250 1301-1329/? I/ActivityManager: Start proc com.android.defcontainer for service com.android.defcontainer/.DefaultContainerService: pid=2417 uid=10003 gids= {50003, 9997, 1028, 1015, 1023, 2001, 1035} abi=x86_64
01-25 15:52:07.280 2417-2426/? D/DefContainer: Copying 3@base.apk@classes.dex --instruction-set=x86_64 --instruction-set-features=default --runtime-arg -Xms64m --runtime-arg -Xmx512m
01-25 15:52:07.590 2434-2434/? W/dex2oat: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
01-25 15:52:10.280 2434-2434/? I/dex2oat: dex2oat took 2.830s (threads: 1)
01-25 15:52:10.280 1301-1329/? W/PackageManager: Code path for pkg :
01-25 15:52:10.280 1301-1329/? W/PackageManager: Resource path for pkg : com.locator changing from /data/app/com.locator-1 to /data/app/com.locator-3
01-25 15:52:10.370 1301-1329/? I/ActivityManager: Force stopping com.locator appid=10061 user=0: pkg removed
01-25 15:52:10.390 1301-1334/? I/InputReader: Reconfiguring input devices. changes=0x00000010
01-25 15:52:10.420 1301-1334/? I/InputReader: Reconfiguring input devices. changes=0x00000010
01-25 15:52:10.440 1301-1334/? I/InputReader: Reconfiguring input devices. changes=0x00000010
01-25 15:52:10.470 1540-1540/? I/art: Explicit concurrent mark sweep GC freed 5243(504KB) AllocSpace objects, 52(4MB) LOS objects, 31% free, 8MB/12MB, paused 0 total 100ms
01-25 15:52:10.480 1301-1313/? W/art: Suspending all threads took: 10ms
01-25 15:52:10.480 1301-1313/? I/art: Background sticky concurrent mark sweep GC freed 9218(782KB) AllocSpace objects, 6(96KB) LOS objects, 6% free, 11MB/11MB, paused 10ms total 90ms
01-25 15:52:10.480 1301-1329/? I/art: WaitForGcToComplete blocked for 40ms for cause Explicit
01-25 15:52:10.520 1781-1781/? D/ChimeraCfgMgr: Loading module com.google.android.gms.games from APK com.google.android.gms
01-25 15:52:10.540 1781-2436/? D/PackageBroadcastService: Received broadcast action=android.intent.action.PACKAGE_REMOVED and uri=com.locator
01-25 15:52:10.590 1600-1600/? E/NetworkScheduler.SchedulerReceiver: Invalid parameter app
01-25 15:52:10.590 1600-1600/? E/NetworkScheduler.SchedulerReceiver: Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
01-25 15:52:10.630 1781-2442/? D/PackageBroadcastService: Received broadcast action=android.intent.action.PACKAGE_ADDED and uri=com.locator
01-25 15:52:10.700 1781-1781/? D/ChimeraCfgMgr: Loading module com.google.android.gms.gass from APK com.google.android.gms
01-25 15:52:10.730 1781-1781/? D/AsyncTaskServiceImpl: Submit a task: k
01-25 15:52:10.770 1301-1301/? D/BackupManagerService: Received broadcast Intent { act=android.intent.action.PACKAGE_ADDED dat=package:com.locator flg=0x4000010 (has extras) }
01-25 15:52:10.770 1301-1301/? W/BackupManagerService: Removing schedule queue dupe of com.locator
01-25 15:52:10.820 1301-1318/? W/VoiceInteractionManagerService: no available voice recognition services found for user 0
01-25 15:52:10.840 1781-1781/? D/ChimeraCfgMgr: Loading module com.google.android.gms.gass from APK com.google.android.gms
01-25 15:52:10.890 1781-1781/? D/ChimeraCfgMgr: Loading module com.google.android.gms.vision from APK com.google.android.gms
01-25 15:52:10.900 1781-2447/? D/k: Processing package: com.locator
01-25 15:52:10.940 1781-2444/? I/PeopleContactsSync: triggerPendingContactsCleanup: no accounts
01-25 15:52:10.980 1781-2447/? D/GassUtils: Found app info for package com.locator:1. Hash: 607a580ba8b114d1bb81233a4f43c87943595c82273a2c0687ee3129357d1d28
01-25 15:52:10.980 1781-2447/? D/k: Found info for package com.locator in db.
01-25 15:52:11.050 1301-1644/? I/ActivityManager: Start proc com.svox.pico for broadcast com.svox.pico/.VoiceDataInstallerReceiver: pid=2449 uid=10041 gids={50041, 9997, 1028, 1015} abi=x86_64
01-25 15:52:11.080 957-957/? I/art: Explicit concurrent mark sweep GC freed 707(30KB) AllocSpace objects, 0(0B) LOS objects, 90% free, 110KB/1134KB, paused 0 total 40ms
01-25 15:52:11.100 957-957/? I/art: Explicit concurrent mark sweep GC freed 5(160B) AllocSpace objects, 0(0B) LOS objects, 90% free, 110KB/1134KB, paused 0 total 20ms
01-25 15:52:11.120 957-957/? I/art: Explicit concurrent mark sweep GC freed 4(112B) AllocSpace objects, 0(0B) LOS objects, 90% free, 110KB/1134KB, paused 0 total 0
01-25 15:52:11.140 1781-2444/? I/PeopleDatabaseHelper: cleanUpNonGplusAccounts done.
01-25 15:52:11.160 1781-2444/? I/PeopleContactsSync: triggerPendingContactsCleanup: no accounts
01-25 15:52:11.420 1781-1781/? D/ChimeraCfgMgr: Loading module com.google.android.gms.gass from APK com.google.android.gms
01-25 15:52:11.430 1781-1781/? D/AsyncTaskServiceImpl: Submit a task: k
01-25 15:52:11.440 1781-2465/? D/PackageBroadcastService: Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.locator
01-25 15:52:11.440 1781-2447/? D/k: Processing package: com.locator
01-25 15:52:11.440 1781-1781/? D/ChimeraCfgMgr: Loading module com.google.android.gms.vision from APK com.google.android.gms
01-25 15:52:11.460 1781-2447/? D/GassUtils: Found app info for package com.locator:1. Hash: 607a580ba8b114d1bb81233a4f43c87943595c82273a2c0687ee3129357d1d28
01-25 15:52:11.460 1781-2447/? D/k: Found info for package com.locator in db.
01-25 15:52:11.480 1600-1600/? E/NetworkScheduler.SchedulerReceiver: Invalid parameter app
01-25 15:52:11.480 1600-1600/? E/NetworkScheduler.SchedulerReceiver: Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
01-25 15:52:11.640 2408-2408/? D/AndroidRuntime: Shutting down VM
01-25 15:52:12.230 2473-2473/? D/AndroidRuntime: CheckJNI is ON
01-25 15:52:12.260 1781-1823/? I/Icing: Indexing 15DBDA826A510ED8E77488BBA6CDEF77984857D4 from com.google.android.gms
01-25 15:52:12.280 2473-2473/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-25 15:52:12.280 2473-2473/? E/android.os.Debug: failed to load memtrack module: -2
01-25 15:52:12.300 2473-2473/? D/AndroidRuntime: Calling main entry com.android.commands.am.Am
01-25 15:52:12.310 1301-1314/? I/ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.locator/.MainActivity} from uid 0 on display 0
01-25 15:52:12.320 2473-2473/? D/AndroidRuntime: Shutting down VM
01-25 15:52:12.320 2482-2482/? I/art: Not late-enabling -Xcheck:jni (already on)
01-25 15:52:12.760 1781-1823/? I/Icing: Indexing 15DBDA826A510ED8E77488BBA6CDEF77984857D4 from com.google.android.gms
01-25 15:52:12.760 1781-1823/? E/Icing: Not enough disk space for indexing
01-25 15:52:12.760 1781-1823/? I/Icing: Cannot sync untrimmable corpus: no sync
01-25 15:52:12.760 1781-1823/? I/Icing: Indexing done 15DBDA826A510ED8E77488BBA6CDEF77984857D4
01-25 15:52:12.760 1781-1823/? E/Icing: Aborting indexing of corpus apps
01-25 15:52:12.850 2482-2482/? D/Atlas: Validating map...
01-25 15:52:12.970 2482-2497/? I/OpenGLRenderer: Initialized EGL, version 1.4
01-25 15:52:13.000 2482-2497/? D/OpenGLRenderer: Enabling debug mode 0
01-25 15:52:13.020 2482-2497/? W/EGL_emulation: eglSurfaceAttrib not implemented
01-25 15:52:13.020 2482-2497/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f5ada586280, error=EGL_SUCCESS
01-25 15:52:13.430 1301-1324/? I/ActivityManager: Displayed
01-25 15:52:15.600 1301-2437/? W/DropBoxManagerService: Dropping: system_app_strictmode (10 > 0 bytes)
01-25 15:52:17.320 1301-1585/? I/ActivityManager: Killing 1557:com.android.printspooler/u0a42 (adj 15): empty #17
01-25 15:52:17.330 1301-1315/? W/libprocessgroup: failed to open /acct/uid_10042/pid_1557/cgroup.procs: No such file or directory
01-25 15:52:21.560 1301-1334/? I/InputReader: Reconfiguring input devices. changes=0x00000010
01-25 15:52:21.610 1301-1301/? D/BackupManagerService: Received broadcast Intent { act=android.intent.action.PACKAGE_CHANGED dat=package:com.google.android.gms flg=0x4000010 (has extras) }
01-25 15:52:21.610 1301-1301/? I/BackupManagerService: Unbinding ComponentInfo{com.google.android.gms/com.google.android.gms.backup.BackupTransportService}
01-25 15:52:21.620 1600-1600/? I/GCoreNlp: shouldConfirmNlp, NLP off. Ensuring opt-in disabled
01-25 15:52:21.630 1540-1540/? I/Launcher: Deferring update until onResume
01-25 15:52:21.670 1301-1301/? V/BackupManagerService: Connected to transport ComponentInfo{com.google.android.gms/com.google.android.gms.backup.BackupTransportService}
01-25 15:52:21.680 1301-1301/? V/BackupManagerService: Registering transport com.google.android.gms/.backup.BackupTransportService::com.google.android.gms/.backup.BackupTransportService = com.android.internal.backup.IBackupTransport$Stub$Proxy@8c7a28f
01-25 15:52:21.700 1600-1600/? W/GmsBackupAccountManager: Backup account not found in gmscore.
01-25 15:52:21.720 1781-2500/? D/PackageBroadcastService: Received broadcast action=android.intent.action.PACKAGE_CHANGED and uri=com.google.android.gms
01-25 15:52:21.750 1600-2501/? W/GmsBackupAccountManager: Backup account not found in gmscore.
01-25 15:52:21.770 1600-2501/? I/Backup: [BackupTransportMigratorService] Component name not found : com.google.android.backuptransport/com.google.android.backup.BackupTransportService
01-25 15:52:21.780 1600-2501/? I/Backup: [BackupTransportMigratorService] Component name not found : com.google.android.backup/com.google.android.backup.BackupTransportService
01-25 15:52:21.780 1600-2501/? I/Backup: [BackupTransportMigratorService] Successfully migrated to use GMS BackupTransportService!
01-25 15:52:22.850 1781-1823/? I/Icing: Indexing 15DBDA826A510ED8E77488BBA6CDEF77984857D4 from com.google.android.gms
01-25 15:58:37.660 1301-1318/? I/UsageStatsService: User[0] Flushing usage stats to disk