如何在活动和服务android上运行应用程序?
如何将应用程序同时作为活动和服务运行。我找了很多,但找不到解决办法。谁能告诉我怎么做。我已经试过了,但它在android 3.0及以上版本上不起作用 我需要这段代码作为应用程序和后台服务运行。可能吗 这是我的密码:如何在活动和服务android上运行应用程序?,android,service,Android,Service,如何将应用程序同时作为活动和服务运行。我找了很多,但找不到解决办法。谁能告诉我怎么做。我已经试过了,但它在android 3.0及以上版本上不起作用 我需要这段代码作为应用程序和后台服务运行。可能吗 这是我的密码: public class gps extends Activity implements LocationListener { LocationManager manager; String closestStation; @Override pr
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();
}
}
}
公共类gps扩展活动实现LocationListener{
地点经理;
字符串关闭站;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
Calendar cur_cal=Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
当前添加(日历分钟,15);
Log.d(“测试”,“日历设置时间:+cur_cal.getTime());
意向意向=新意向(gps.this,gps\u back\u process.class);
PendingEvent pintent=PendingEvent.getService(gps.this,0,
意图,0);
AlarmManager alarm_manager=(AlarmManager)getSystemService(Context.alarm_服务);
alarm_manager.setRepeating(AlarmManager.RTC_唤醒,
cur_cal.getTimeInMillis(),1000*60*15,pintent);
alarm_manager.set(AlarmManager.RTC,cur_cal.getTimeInMillis(),
针状物);
Log.d(“测试”、“报警管理器设置”);
Toast.makeText(这是“gps\u back\u process.onCreate()”,
Toast.LENGTH_LONG).show();
}
意向意向=新意向(“android.location.GPS_ENABLED_CHANGE”);
intent.putExtra(“已启用”,真);
本.发送广播(意图);
String provider=Settings.Secure.getString(getContentResolver(),Settings.Secure.LOCATION\u PROVIDERS\u允许);
如果(!provider.contains(“gps”){//如果gps被禁用
最终意图=新意图();
poke.setClassName(“com.android.settings”、“com.android.settings.widget.SettingsAppWidgetProvider”);
poke.addCategory(意向、类别和备选方案);
setData(Uri.parse(“3”);
这个。发送广播(poke);
}
{
//初始化位置管理器
manager=(LocationManager)getSystemService(Context.LOCATION\u服务);
//检查是否启用了GPS
//如果没有,请向用户敬酒
如果(!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)),则为else{
//从位置管理器获取位置提供程序
//空条件搜索所有提供程序并返回最佳提供程序
字符串providerName=manager.getBestProvider(新条件(),true);
位置=manager.getLastKnownLocation(providerName);
TextView tv=(TextView)findViewById(R.id.locationResults);
如果(位置!=null){
tv.setText(location.getLatitude()+“latitude”,+location.getLatitude()+经度);
}否则
{
tv.setText(“未找到最后一个已知位置。正在等待更新位置…”);
}
manager.requestLocationUpdates(providerName,1000*60*30,1,this);
}
}
}
@凌驾
已更改位置上的公共无效(位置){
TextView tv=(TextView)findViewById(R.id.locationResults);
如果(位置!=null){
tv.setText(location.getLatitude()+“latitude”,+location.getLatitude()+经度);
//我添加了这一行
追加数据(location.getLatitude();
}否则{
tv.setText(“获取gps网络ID时出现问题:+”);
}
}
@凌驾
公共无效onProviderDisabled(字符串arg0){}
@凌驾
公共无效onProviderEnabled(字符串arg0){}
@凌驾
public void onStatusChanged(字符串arg0,int arg1,Bundle arg2){}
//找到最近的捷运局
公共字符串findClosestBart(位置loc){
双纬度=loc.getLatitude();
double lon=loc.getLongitude();
双光标=0;
双游标长度=0;
double shortestDistSoFar=double.POSITIVE_∞;
双凝乳器;
字符串curStat=null;
字符串closestStat=null;
//把所有的车站都分类
//使用API编写某种for循环。
curDist=Math.sqrt(((lat-curStatLat)*(lat-curStatLat))+
((lon-curStatLon)*(lon-curStatLon));
if(curDist
一个类不能既是活动
又是服务
,但Android应用程序当然可以同时包含这两个类。如果您需要在这两个系统中运行相同的代码,只需将该公共代码抽象为一个公共类,然后从活动中调用该代码