如何运行服务的方法完全一个后台进程? [英] How to run a background process in service method completely?
本文介绍了如何运行服务的方法完全一个后台进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨任何机构可以告诉我如何在服务,而不活动的运行此code,我在一个活动做到了这一点code,但我不希望它是我需要它是一个服务的应用程序刚刚才在服务显示它谢谢你,我已经尝试过,但在30分钟我的活动显示了一次。
这是我的code:
公共类GPS扩展活动实现LocationListener的{
LocationManager经理;
字符串closestStation;
@覆盖
保护无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
{
日历cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis的());
cur_cal.add(Calendar.MINUTE,15);
Log.d(测试,日历设置时间:+ cur_cal.getTime());
意向意图=新的意图(gps.this,gps_back_process.class);
PendingIntent pintent = PendingIntent.getService(gps.this,0,
意图,0);
AlarmManager alarm_manager =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm_manager.setRepeating(AlarmManager.RTC_WAKEUP,
cur_cal.getTimeInMillis(),1000 * 60 * 15,pintent);
alarm_manager.set(AlarmManager.RTC,cur_cal.getTimeInMillis(),
pintent);
Log.d(测试,报警经理集);
Toast.makeText(这一点,gps_back_process.onCreate(),
Toast.LENGTH_LONG).show();
}
意向意图=新的意图(android.location.GPS_ENABLED_CHANGE);
intent.putExtra(已启用,真正的);
this.sendBroadcast(意向);
字符串商= Settings.Secure.getString(getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
如果(!provider.contains(GPS)){//如果GPS被禁用
最终意图捅=新意图();
poke.setClassName(com.android.settings,com.android.settings.widget.SettingsAppWidgetProvider);
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse(3));
this.sendBroadcast(捅);
}
{
//初始化位置经理
经理=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//检查是否GPS被启用
//如果没有,用敬酒通知用户
如果(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)!);其他 {
//从位置管理位置提供
//空搜索条件在所有供应商和返回的佼佼者
字符串的providerName = manager.getBestProvider(新标准(),TRUE);
位置位置= manager.getLastKnownLocation(的providerName);
TextView的电视=(TextView中)findViewById(R.id.locationResults);
如果(位置!= NULL){
tv.setText(location.getLatitude()+纬度,+ location.getLongitude()+经度);
} 其他
{
tv.setText(未找到最后的已知位置等待更新的位置......。);
}
manager.requestLocationUpdates(的providerName,1000 * 60 * 30,1,本);
}
}
}
@覆盖
公共无效onLocationChanged(位置定位){
TextView的电视=(TextView中)findViewById(R.id.locationResults);
如果(位置!= NULL){
tv.setText(location.getLatitude()+纬度,+ location.getLongitude()+经度);
//我已经加入这一行
appendData(location.getLatitude()+纬度,+ location.getLongitude()+经度);
} 其他 {
tv.setText(问题越来越GPS网络ID:+);
}
}
@覆盖
公共无效onProviderDisabled(字符串为arg0){}
@覆盖
公共无效onProviderEnabled(字符串为arg0){}
@覆盖
公共无效onStatusChanged(字符串为arg0,INT ARG1,捆绑ARG2){}
//寻找最近的巴特站
公共字符串findClosestBart(位置LOC){
双纬度= loc.getLatitude();
双LON = loc.getLongitude();
双curStatLat = 0;
双curStatLon = 0;
双shortestDistSoFar = Double.POSITIVE_INFINITY;
双curDist;
字符串curStat = NULL;
字符串closestStat = NULL;
//排序通过所有的站
//写某种循环使用的API。
curDist =的Math.sqrt(((LAT - curStatLat)*(纬度 - curStatLat))+
((LON - curStatLon)*(经度 - curStatLon)));
如果(curDist< shortestDistSoFar){
closestStat = curStat;
}
返回closestStat;
}
//方法在文件中写入
公共无效appendData(字符串文本)
{
文件数据文件=新的文件(Environment.getExternalStorageDirectory()+/GpsData.txt);
如果(!dataFile.exists())
{
尝试
{
dataFile.createNewFile();
}
赶上(IOException异常E)
{
// TODO自动生成的catch块
e.printStackTrace();
}
}
尝试
{
// BufferedWriter将性能,真正的设置附加到文件标志
BufferedWriter将BUF =新的BufferedWriter(新的FileWriter(数据文件,真));
SimpleDateFormat的SDF =新的SimpleDateFormat(HH:MM,DD / MM / YYYY);
字符串currentDateandTime = sdf.format(新日期());
//文字+ =,+ currentDateandTime;
buf.append(文字+,+ currentDateandTime);
buf.newLine();
buf.close();
}
赶上(IOException异常E)
{
// TODO自动生成的catch块
e.printStackTrace();
}
}
}
解决方案
1.extends而不是Activity类和
服务类
2.把你的code到的OnCreate()
3.添加服务到manefest。
4.call服务的活动,一旦像
意图的服务=新的意图(背景下,localService.class);
context.startService(服务);
按照本教程。
Hi can any body show me how to run this code in service without activity, i have done this code in an activity but i dont want it to be an application i need it to be in a service only just to display it on service thank you i have tried but my activity displaying for once in 30 mins.
this is my code:
public class gps extends Activity implements LocationListener {
LocationManager manager;
String closestStation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
cur_cal.add(Calendar.MINUTE, 15);
Log.d("Testing", "Calender Set time:" + cur_cal.getTime());
Intent intent = new Intent(gps.this, gps_back_process.class);
PendingIntent pintent = PendingIntent.getService(gps.this, 0,
intent, 0);
AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm_manager.setRepeating(AlarmManager.RTC_WAKEUP,
cur_cal.getTimeInMillis(), 1000 * 60 * 15, pintent);
alarm_manager.set(AlarmManager.RTC, cur_cal.getTimeInMillis(),
pintent);
Log.d("Testing", "alarm manager set");
Toast.makeText(this, "gps_back_process.onCreate()",
Toast.LENGTH_LONG).show();
}
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else
{
tv.setText("Last known location not found. Waiting for updated location...");
}
manager.requestLocationUpdates(providerName, 1000*60*30 , 1 , this);
}
}
}
@Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
// I have added this line
appendData ( location.getLatitude() + " latitude, " + location.getLongitude() + " longitude" );
} else {
tv.setText("Problem getting gps NETWORK ID : " + "");
}
}
@Override
public void onProviderDisabled(String arg0) {}
@Override
public void onProviderEnabled(String arg0) {}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
// method to write in file
public void appendData(String text)
{
File dataFile = new File(Environment.getExternalStorageDirectory() + "/GpsData.txt");
if (!dataFile.exists())
{
try
{
dataFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm, dd/MM/yyyy");
String currentDateandTime = sdf.format(new Date());
// text+=","+currentDateandTime;
buf.append(text + "," + currentDateandTime);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
解决方案
1.extends service class instead of Activity class and
2. put your code into oncreate()
3.add your service into manefest.
4.call service from activity once like
Intent service = new Intent(context, localService.class);
context.startService(service);
follow this tutorial.
这篇关于如何运行服务的方法完全一个后台进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文