无法运行后台服务 [英] Cant run background service

查看:91
本文介绍了无法运行后台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图每次在后台服务中使用LocationListener类接收用户的当前位置,然后将其与数据库中存储的某些数据进行比较.但是当我尝试这样做时,我就错了

I am trying to use LocationListener class in a background service to receive the current location of user every time and then comparing it with some data stored in my database. but I am gettin error, when I am trying to do that

    package com.example.alert;

   import android.app.Service;
   import android.content.Context;
   import android.content.Intent;
   import android.location.Location;
   import android.location.LocationListener;
  import android.location.LocationManager;
  import android.media.MediaPlayer;
  import android.os.Bundle;
 import android.os.IBinder;
 import android.widget.Toast;

 public class service extends Service{
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

public void onCreate() {
    Toast.makeText(this, "Background Service Created", Toast.LENGTH_LONG).show();



}

public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();


}

public void onStart(Intent intent, int startid) {

    Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
    Intent myIntent=new Intent(service.this,CurrentLocation.class);
    startActivity(myIntent);
    }
}

这是我的日志

11-10 04:54:54.819: E/AndroidRuntime(768): FATAL EXCEPTION: main
11-10 04:54:54.819: E/AndroidRuntime(768): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.alert/com.example.alert.service}: java.lang.NullPointerException
  11-10 04:54:54.819: E/AndroidRuntime(768):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
  11-10 04:54:54.819: E/AndroidRuntime(768):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-10 04:54:54.819: E/AndroidRuntime(768):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-10 04:54:54.819: E/AndroidRuntime(768):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-10 04:54:54.819: E/AndroidRuntime(768):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-10 04:54:54.819: E/AndroidRuntime(768):  at android.os.Looper.loop(Looper.java:137)
11-10 04:54:54.819: E/AndroidRuntime(768):  at android.app.ActivityThread.main(ActivityThread.java:4745)
11-10 04:54:54.819: E/AndroidRuntime(768):  at java.lang.reflect.Method.invokeNative(Native Method)
11-10 04:54:54.819: E/AndroidRuntime(768):  at java.lang.reflect.Method.invoke(Method.java:511)
11-10 04:54:54.819: E/AndroidRuntime(768):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-10 04:54:54.819: E/AndroidRuntime(768):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-10 04:54:54.819: E/AndroidRuntime(768):  at dalvik.system.NativeStart.main(Native Method)
11-10 04:54:54.819: E/AndroidRuntime(768): Caused by: java.lang.NullPointerException
11-10 04:54:54.819: E/AndroidRuntime(768):  at android.content.ContextWrapper.getSystemService(ContextWrapper.java:416)
11-10 04:54:54.819: E/AndroidRuntime(768):  at com.example.alert.service.<init>(service.java:15)
11-10 04:54:54.819: E/AndroidRuntime(768):  at java.lang.Class.newInstanceImpl(Native Method)
11-10 04:54:54.819: E/AndroidRuntime(768):  at java.lang.Class.newInstance(Class.java:1319)

这是位置侦听器的其余代码

Here's the rest of the code of location listener

    package com.example.alert;

   import android.app.Activity;
  import android.content.Context;
  import android.location.Location;
  import android.location.LocationListener;
  import android.location.LocationManager;
  import android.os.Bundle;
 import android.widget.Toast;

 public class CurrentLocation extends Activity {
LocationManager lm ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    /* Use the LocationManager class to obtain GPS locations */
    LocationListener ll = new MyLocationListener();
    //lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
    lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);

}



/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{

    public void onLocationChanged(Location loc)
    {
        if(loc!=null)
        {
            double x;
            String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
            Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();    
            //for loop, alerters retrieving one by one
            //x= calcDistance(loc.getLatitude(),loc.getLongitude(),,);
            //if(x<1)
            // distance < 1, retrieve data from DB and trigger 
        }
    }


    public void onProviderDisabled(String provider)
    {
        Toast.makeText( getApplicationContext(),"Gps Disabled - @From :Alert Me",Toast.LENGTH_SHORT ).show();
    }


    public void onProviderEnabled(String provider)
    {
        Toast.makeText( getApplicationContext(),"Gps Enabled - @From :Alert Me",Toast.LENGTH_SHORT).show();
    }


    public void onStatusChanged(String provider, int status, Bundle extras)
    {

    }

}/* End of Class MyLocationListener */

public double calcDistance(double latA, double longA, double latB, double longB) {

    double theDistance = (Math.sin(Math.toRadians(latA)) *  Math.sin(Math.toRadians(latB)) + Math.cos(Math.toRadians(latA)) * Math.cos(Math.toRadians(latB)) * Math.cos(Math.toRadians(longA - longB)));
    return new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09*1.6093);
}


}

清单文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alert"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Instructions" android:label="Instructions"></activity>
    <activity android:name=".AboutApp" android:label="About ALERT ME!"></activity>

    <activity android:name=".ViewAlerters" android:label="Alerters Active"></activity> 
    <activity android:name=".AddAlerter" android:label="Add an Alerter"></activity>
    <activity android:name=".EditAlerter" android:label="Edit an alerter"></activity> 
    <activity android:name=".AddLocation" android:label="Add Location to Alerter"></activity>
    <activity android:name=".AddTrigger" android:label="Add trigger to Alerter"></activity>


    <activity android:name=".SilVib" android:label="Silent/Vibrate Trigger"></activity>
    <activity android:name=".CallMode" android:label="Call Mode Trigger"></activity>
    <activity android:name=".service"></activity>
    <activity android:name=".Status_Notify"></activity>
    <activity android:name=".Notifier"></activity>    
    <activity android:name=".Message"></activity>
    <activity android:name=".Message_sent"></activity>
    <activity android:name=".StoringEntire"></activity>
    <activity android:name=".CurrentLocation"></activity>


    <uses-library android:name="com.google.android.maps"/>
<service
    android:enabled="true"
 android:name=".service"/>
      </application>
 <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_SERVICE"/>


</manifest>

推荐答案

LogCat指出:

Caused by: java.lang.NullPointerException
    at android.content.ContextWrapper.getSystemService(ContextWrapper.java:416)
    at com.example.alert.service.<init>(service.java:15)

通过将这段代码移到 onCreate()中,只需等待Context的初始化:

Simply wait for the Context to be initialized by moving this code into onCreate():

public class service extends Service {
    LocationManager lm;

    @Override
    public void onCreate() {
        // This line needs an existing context
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Toast.makeText(this, "Background Service Created", Toast.LENGTH_LONG).show();
    }

    // etc

这篇关于无法运行后台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆