我是Android的新手,我在收到短信时尝试访问gps位置。 我这样称呼服务:
Intent findGPS = new Intent(context, MyService.class);
context.startService(findGPS);
我试图在服务类中打印吐司,以便知道它是否已经启动但是它没有打印吐司。任何人都可以建议我如何编写服务类来进行位置访问。
公共类MyService扩展了Service {
........
public void onCreate()
{
Log.e(TAG, "onCreate");
Toast.makeText(this,"Its Working !!!", Toast.LENGTH_LONG).show();
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
}
答案 0 :(得分:1)
服务会自动调用。
public class BReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
// call your service here
startService(new Intent(getapplicationcontext(),ImageDownloader .class));
} catch (Exception e) {
e.printStackTrace();
}
}
}
//创建一个java类并使用意向服务扩展它,因为它具有停止自我功能,因为服务在后台运行时耗尽电池,这就是为什么我建议你使用意向服务,完成任务后它会自动执行。
public class ImageDownloader extends IntentService {
public ImageDownloader() {
super("DownLoadImages");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
protected void onHandleIntent(Intent intent) {
// do your stuff here
}
}