当应用程序终止时,服务无法在后台运行

时间:2016-07-28 19:19:30

标签: android service

我知道有很多与此相关的代码!但我仍然面临着问题 我搜索了许多教程和文档,当我最小化应用程序时,我能够运行服务!但是当应用程序关闭或终止时它没有响应

这是我的代码!这是我的服务类

public class MyService extends Service {

    final public static String ONE_TIME = "onetime";
    public static final String MyPREFERENCES = "MyPrefs";
    SharedPreferences sharedpreferences;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Toast.makeText(this, "ServiceClass.onStart()", Toast.LENGTH_LONG).show();
        Log.d("Testing", "Service got started");
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        //I need to call this every say-10 second
        final String URL = "http://nrna.org.np/nrna_app/app_user/set_location/" + sharedpreferences.getString("Save_user_app_id", null) + "/np";
        // if (isNetworkAvailable() == true) {
        RequestQueue queue = Volley.newRequestQueue(MyService.this);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, null, null);
// Add the request to the RequestQueue.
        queue.add(stringRequest);

        // Let it continue running until it is stopped.
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }

}

我从我的主要活动中调用了这项服务

// Method to start the service
    public void startService(Context context) {
        Intent intent = new Intent(MainActivity.this, MyService.class);
        PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10 * 1000, pintent);
        //startService(new Intent(getBaseContext(), MyService.class));
    }

我的清单文件

 <service android:name=".MyService"/>

如果应用已关闭,我需要运行!!

更新我使用过BroadCastReceiver!但不能再工作了。

public class BaseNotificationManager extends BroadcastReceiver {


    public static final String BaseAction = "Com.TST.BaseAction";
    public static final String FireService = "Com.TST.FireNotificationAction";


    private  static  final long timeFrame =  1000*10;  // 5 mints

    public BaseNotificationManager() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            /// add base alarm manager
            startBaseAlarmManager(context);

        }else  if (BaseAction.equals(intent.getAction())){
            //  StartYourService();
            intent = new Intent(context,MyService.class);
            PendingIntent pintent = PendingIntent.getService(context, 0, intent, 0);
            AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
            alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10 * 1000, pintent);

        }
    }       public  static  void startBaseAlarmManager (Context context){


        AlarmManager alarmMgr;
        PendingIntent alarmIntent;

        alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, BaseNotificationManager.class);
        intent.setAction(BaseAction);
        alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                5000,  timeFrame, alarmIntent);

    }}

2 个答案:

答案 0 :(得分:1)

您要做的是在服务的后台线程上运行某种循环。您的代码没有表明您希望重复操作。您真正想要的是以下内容(使用C#语法):

new Thread(obj =>
{
   while (true)
   {
      // Do actions that you want repeated (poll web site, etc.)

      // Sleep for awhile
      Thread.Sleep(10000);
    }
}

另见以下主题: Android Service Stops When App Is Closed

顺便说一下,我可能会误解你的目标,但你是否也可以使用推送通知(例如GCM)在这里完成同样的事情? (我问的原因是,从电源管理的角度来看,使用GCM往往比反复轮询更好。)

如果您有点好奇,那么就可以很好地谈论节约电力并让您的应用成为“好公民”#34;在Android Developers Backstage播客的电池寿命方面。我想你应该能够在这里得到它:https://www.acast.com/androiddevelopersbackstage/episode-44-power-on

修改:如果您要上传结果,可以执行以下操作将其发布到您的网络服务(再次使用C#/ Web API语法,但您可以轻松实现将Java与Web API或Node.js一起使用):

    public class Location
    {
        public double Latitude
        {
            get;
            set;
        }

        public double Longitude
        {
            get;
            set;
        }

        public Location(double latitude, double longitude)
        {
            this.Latitude = latitude;
            this.Longitude = longitude;
        }
    }

    // This call goes in your main thread
    private async void PostLocation(Location location)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("[your base address]");

            string json = JsonConvert.SerializeObject(location);
            HttpResponseMessage message = await client.PostAsync("controller/method", new StringContent(json));
        }
    }

答案 1 :(得分:1)

尝试

    public class MyService extends Service {
      @Override
        protected void onHandleIntent(Intent workIntent) {
            // Gets data from the incoming Intent
            String dataString = workIntent.getDataString();
            ...
            // Do work here, based on the contents of dataString
            ...
        }
}

您的应用程序似乎有GUI,您正在使用Service类。这里的主要缺点是

Service后台中运行,但它在应用程序主线程上运行。

IntentService在单独的工作线程上运行。