Android 后台服务不工作
在这里,我为获取当前GPS位置和显示创建了后台服务。但当我尝试上面的代码时,我得到了以下错误。但问题是,当我在Android选项卡上尝试时,它工作正常,但当我在Huwavi选项卡上尝试时,它给出了愚蠢的错误Android 后台服务不工作,android,Android,在这里,我为获取当前GPS位置和显示创建了后台服务。但当我尝试上面的代码时,我得到了以下错误。但问题是,当我在Android选项卡上尝试时,它工作正常,但当我在Huwavi选项卡上尝试时,它给出了愚蠢的错误 public class MyService extends BackgroundService implements LocationListener { private final static String TAG = MyService.class.getS
public class MyService extends BackgroundService implements LocationListener {
private final static String TAG = MyService.class.getSimpleName();
private String mHelloTo = "World";
private LocationManager locationManager;
private String provider;
Context context;
String username;
CommentsDataSource datasource;
@Override
public void onCreate() {
context = getApplicationContext();
datasource = new CommentsDataSource(context);
datasource.open();
mHelloTo = datasource.getComment_1();
}
@Override
public void onDestroy() {
//datasource.close();
}
protected JSONObject doWork() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
int level=0;
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
if (location != null) {
Log.i("Provider", provider + " has been selected.");
onLocationChanged(location);
}
JSONObject result = new JSONObject();
try {
String msg = "Kasun " + mHelloTo + " - its currently "
+ "3.456789";
result.put("Message", msg);
Log.d(TAG, msg);
} catch (JSONException e) {
}
return result;
}
public void onLocationChanged(Location location) {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
}
}
请使用此服务: 格拉德尔 启动服务 服务等级
公共类ServiceLocation扩展服务实现
GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener,
位置侦听器{
私有静态最终字符串通知\u通道\u ID=“我的通知\u位置”;
私有静态最终长时间\u间隔\u获取\u位置=1000*5;//1分钟
私有静态最终长距离最小距离更改用于更新=7;//米
私有处理程序handlerSendLocation;
私有上下文;
私人GoogleapClient MGoogleapClient;
私人位置请求mLocationRequest;
专用最终静态int连接\u故障\u解决\u请求=5000;
位置数据;
@凌驾
public void onCreate(){
super.onCreate();
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
//创建LocationRequest对象
mLocationRequest=LocationRequest.create()
.setPriority(定位请求。优先级高精度)
.setInterval(时间间隔获取位置)//3秒,以毫秒为单位
.SetFastTestInterval(时间间隔获取位置);//1秒,以毫秒为单位
mContext=这个;
NotificationCompat.Builder=新建NotificationCompat.Builder(此为通知通道ID)
.正在进行(错误)
.setSmallIcon(R.drawable.ic_通知)
.setColor(getResources().getColor(R.color.fontColorDarkGray))
.setPriority(通知.PRIORITY_MIN);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.O){
NotificationManager NotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION\u服务);
NotificationChannel NotificationChannel=新的NotificationChannel(通知通道ID,
通知(通道ID、通知管理器。重要性较低);
notificationChannel.setDescription(通知通道ID);
notificationChannel.setSound(null,null);
notificationManager.createNotificationChannel(notificationChannel);
startForeground(1,builder.build());
}
}
@凌驾
公共IBinder onBind(意图arg0){
返回null;
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
Log.w(“服务更新位置”,“BGS>已启动”);
if(handlerSendLocation==null){
handlerSendLocation=新处理程序();
handlerSendLocation.post(runnableSendLocation);
Log.w(“服务发送位置”,“BGS>handlerSendLocation已初始化”);
}否则{
Log.w(“服务发送位置”,“BGS>handlerSendLocation已初始化”);
}
返回开始时间;
}
private Runnable runnableSendLocation=new Runnable(){
@凌驾
公开募捐{
//你可以找到位置
//位置数据
Log.w(“==>UpdateLocation>Location Updated”);
if(handlerSendLocation!=null&&runnableSendLocation!=null)
handlerSendLocation.postDelayed(runnableSendLocation,时间间隔获取位置);
}
};
@凌驾
未连接的公共无效(@Nullable Bundle){
if(ActivityCompat.checkSelfPermission(mContext、Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予&&
ActivityCompat.checkSelfPermission(mContext、Manifest.permission.ACCESS\u位置)!=PackageManager.permission\u已授予){
回来
}
Location Location=LocationServices.FusedLocationApi.getLastLocation(mgoogleapClient);
LocationServices.FusedLocationApi.RequestLocationUpdate(mgoogleapClient、mlLocationRequest、this);
}
@凌驾
公共空间连接暂停(int i){
}
@凌驾
public void onconnection失败(@NonNull ConnectionResult ConnectionResult){
if(connectionResult.hasResolution()&&mContext活动实例){
试一试{
活动活动=(活动)mContext;
connectionResult.StartResult解决方案(活动、连接失败、解决请求);
}捕获(例外e){
e、 printStackTrace();
}
}否则{
Log.i(“,”位置服务连接失败,代码为“+connectionResult.getErrorCode());
}
}
@凌驾
已更改位置上的公共无效(位置){
Log.w(“==>UpdateLocation已停止”);
stopSelf();
super.ondestory();
}
}
AndroidManifest.XML
您能在代码中标记第84行吗?我没有看到您在context.registerReceiver(this.batteryForeceiver,newintentFilter(Intent.ACTION\u BATTERY\u CHANGED))中使用的任何batterInfoReceiver声明;第84行:双纬度=location.getLatitude();Double longitude=location.getLongitude();所以locationManager.getLastKnownLocation(provider)返回Null,但它在Samsung tab中工作正常,但在Huwawi tab中工作不正常。为什么会这样请参见文档。。。如果提供程序当前被禁用,它将返回null。。。
12-26 14:41:04.651: I/BackgroundService(5356): Exception occurred during doWork()
12-26 14:41:04.651: I/BackgroundService(5356): java.lang.NullPointerException
12-26 14:41:04.651: I/BackgroundService(5356): at org.apache.cordova.example.MyService.doWork(MyService.java:84)
12-26 14:41:04.651: I/BackgroundService(5356): at com.red_folder.phonegap.plugin.backgroundservice.BackgroundService.doWorkWrapper(BackgroundService.java:390)
implementation 'com.google.android.gms:play-services:12.0.1'
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(MainActivity.this, new Intent(MainActivity.this, ServiceLocation.class));
} else {
startService(new Intent(MainActivity.this, ServiceLocation.class));
}
public class ServiceLocation extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String NOTIFICATION_CHANNEL_ID = "my_notification_location";
private static final long TIME_INTERVAL_GET_LOCATION = 1000 * 5; // 1 Minute
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 7; // meters
private Handler handlerSendLocation;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 5000;
Location locationData;
@Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(TIME_INTERVAL_GET_LOCATION) // 3 seconds, in milliseconds
.setFastestInterval(TIME_INTERVAL_GET_LOCATION); // 1 second, in milliseconds
mContext = this;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setOngoing(false)
.setSmallIcon(R.drawable.ic_notification)
.setColor(getResources().getColor(R.color.fontColorDarkGray))
.setPriority(Notification.PRIORITY_MIN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_LOW);
notificationChannel.setDescription(NOTIFICATION_CHANNEL_ID);
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
startForeground(1, builder.build());
}
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("Service Update Location", "BGS > Started");
if (handlerSendLocation == null) {
handlerSendLocation = new Handler();
handlerSendLocation.post(runnableSendLocation);
Log.w("Service Send Location", "BGS > handlerSendLocation Initialized");
} else {
Log.w("Service Send Location", "BGS > handlerSendLocation Already Initialized");
}
return START_STICKY;
}
private Runnable runnableSendLocation = new Runnable() {
@Override
public void run() {
// You can get Location
//locationData
Log.w("==>UpdateLocation<==", "" + String.format("%.6f", locationData.getLatitude()) + "," +
String.format("%.6f", locationData.getLongitude()));
Log.w("Service Send Location", "BGS >> Location Updated");
if (handlerSendLocation != null && runnableSendLocation != null)
handlerSendLocation.postDelayed(runnableSendLocation, TIME_INTERVAL_GET_LOCATION);
}
};
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution() && mContext instanceof Activity) {
try {
Activity activity = (Activity) mContext;
connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.i("", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
Log.w("==>UpdateLocation<==", "" + String.format("%.6f", location.getLatitude()) + "," + String.format("%.6f", location.getLongitude()));
locationData = location;
}
@Override
public void onDestroy() {
if (handlerSendLocation != null)
handlerSendLocation.removeCallbacks(runnableSendLocation);
Log.w("Service Update Info", "BGS > Stopped");
stopSelf();
super.onDestroy();
}
}
<service
android:name=".ServiceLocation"
android:enabled="true"
android:exported="true" />