我想在用户位置发生变化时通知用户。我通过" FusedLocationApi.requestLocationUpdates "来监控用户的位置。
只要应用程序存在,一切正常。
但是当我轻扫/杀死该应用时,我不再收到任何通知。即使我杀了/轻扫应用程序,我该怎么做才能继续收到通知?
@Override
public void onHandleIntent(Intent intent){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
locationRequest = new LocationRequest();
locationRequest.setInterval(2000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Override
public void onConnected(Bundle bundle) {
try{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
} catch (SecurityException ex){ex.printStackTrace();}
}
@Override
public void onLocationChanged(Location location) {
this.location = location;
handleLocationUpdate();
}
private void handleLocationUpdate(){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(BackGroundService.this);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle(String.format(Locale.getDefault(),
"Lat:%.2f Long:%.2f", location.getLatitude(), location.getLongitude()));
mBuilder.setContentText("Hi, This is Android Notification Detail!");
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
//startForeground(1, mBuilder.build());
}
答案 0 :(得分:2)
这将尝试通过刷出来保存您的服务免于杀戮。正如一些自定义rom杀死你的应用程序甚至你使用它
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
从任务中移除?好的,我会再次启动它
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent myIntent = new Intent(this, NotificationService.class);
startService(myIntent)
}
被摧毁?
@Override
public void onDestroy() {
super.onDestroy();
//startService(new Intent(getApplicationContext(), NotificationService.class));
Intent myIntent = new Intent(this, NotificationService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.HOUR, 6);
alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
答案 1 :(得分:1)
您需要使用android服务或intentservice,具体取决于您想要做什么。然后,即使用户已经开始使用另一个应用程序,您也可以在背景幕中运行。
我认为您需要使用服务,因为您希望它继续在后台运行。 Intentservice只运行到操作结束。
她的一些阅读材料:
IntentService
,
Services
,
IntentService vs Serviceenter code here