Android 保持应用程序在后台运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10494222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
keep application running in background
提问by akubabas
I want to keep my application running in background
I have an application that sends the user's location to our server
I have the following code:
我想让我的应用程序在后台运行
我有一个应用程序将用户的位置发送到我们的服务器
我有以下代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
updateWithNewLocation(null);
locationManager.requestLocationUpdates(provider, (10*60*1000), 10,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
public void updateWithNewLocation(Location location) {
if (location != null) {
Dbhelper helper = new Dbhelper(this);
final SQLiteDatabase db = helper.getWritableDatabase();
long time = System.currentTimeMillis();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
final String curTime = df.format(time);
final double lat = location.getLatitude();
final double lng = location.getLongitude();
final double alt = location.getAltitude();
System.out.println(lat);
System.out.println(lng);
System.out.println(alt);
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
db.close();
/*Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('121.2149012','-6.217837','0.0','2012-05-07 10:20:01')");
db.close();
}
}, 10*60*1000, 10*60*1000);*/
}
}
I want my applicatioin to be running in the background. I want it to launch automatically when the phone is turned on
我希望我的应用程序在后台运行。我希望它在手机开机时自动启动
回答by waqaslam
回答by avimak
Run your background logic in a Service
, and if you want to give a good UX experience (and to also have an higher priority) post a Notification
to status-bar (using NotificationManager
).
在 a 中运行您的后台逻辑Service
,如果您想提供良好的 UX 体验(并且还具有更高的优先级),请将 a 发布Notification
到状态栏(使用NotificationManager
)。
回答by Hassy31
You can keep your application running in the background using Service
您可以使用以下命令让您的应用程序在后台运行 Service
I hope this linkwill help you
我希望这个链接能帮助你
Please read the documentationfor further details
请阅读文档以获取更多详细信息
回答by ashokk
You should use a Service
and a BroadcastReceiver
你应该使用一个Service
和一个BroadcastReceiver
回答by Zubair Khaliq
GrabLocationDetails.java
GrabLocationDetails.java
Use this code as your GrabLocationDetails.java
使用此代码作为您的 GrabLocationDetails.java
public class GrabLocationDetails extends Service implements LocationListener {
double lat,lng;
private LocationManager locationManager;
private String provider;
boolean isGps;
private ArrayList<String> mList;
Context GLDContext;
public GrabLocationDetails(Context cont){
this.GLDContext=cont;
}
public GrabLocationDetails(){}
@Override
public void onCreate() {
super.onCreate();
mList = new ArrayList<String>();
isGps = false;
lat=0.0;
lng=0.0;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//super.onStart(intent, startId);
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
isGps = false;
ListAddItem(isGps);
SendBroadcast();
} else {
isGps = true;
Location location = locationManager.getLastKnownLocation(provider);
lat=(location.getLatitude());
lng=(location.getLongitude());
ListAddItem(true);
SendBroadcast();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
} catch (Exception e) {
ListAddItem(isGps);
SendBroadcast();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
//locationManager.removeUpdates(this);
}
public void SendBroadcast(){
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(CommandExecutionModule.LocationDetails);
broadcastIntent.putExtra("Data", mList);
sendBroadcast(broadcastIntent);
}
public void ListAddItem(boolean GPS) {
//if(!GPS)
//mList.add("0");
//else
//mList.add("1");
mList.add(Double.toString(lat));
mList.add(Double.toString(lng));
}
/**************************************************************************************************************/
@Override
public void onLocationChanged(Location location){
locationManager.requestLocationUpdates(provider, 400, 1, this);
mList.clear();
lat = (location.getLatitude());
lng = (location.getLongitude());
ListAddItem(isGps);
SendBroadcast();
locationManager.removeUpdates(this);
stopSelf();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
@Override
public void onProviderEnabled(String provider){
isGps=true;
}
@Override
public void onProviderDisabled(String provider){
isGps=false;
lat=0.0;
lng=0.0;
mList.clear();
ListAddItem(isGps);
//SendBroadcast();
}