2016-07-28 68 views
0

我知道有很多代码与此相关!但我仍然面临问题 我GOOGLE了很多教程和文档,我能够运行服务,当我最小化应用程序!但它在应用程序关闭或终止时没有响应当应用程序被终止,服务不能在后台工作

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

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"/> 

我需要的,如果应用程序被关闭运行调用该服务!

UPDATE我使用了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); 

    }} 
+0

尝试传递'this'而不是'getBaseContext()' – Vucko

+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往往比反复轮询更好)。

如果您好奇,关于节约能源并让您的应用在Android Developers Backstage播客的电池寿命方面成为“良好的公民”的好话题。我想你应该能够在这里获得:https://www.acast.com/androiddevelopersbackstage/episode-44-power-on

编辑:如果您要上传的结果,你可以不喜欢以下将其发布到您的Web服务(再次使用C#/网络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)); 
     } 
    } 
+0

谢谢你的重播!但之前我也尝试过线程,但它不起作用 –

+0

其实我试图发送客户端的位置,即使应用程序没有打开!我认为在这种情况下线程可能会有帮助!你能否详细说明你的主意? –

+0

您可能会考虑使用广播接收器启动服务器并接收boot_complete广播,以便您的服务在电话开始时启动(除非希望客户端将其明确地打开)。 (这里的“陷阱”是用户必须至少启动了一次该应用程序,否则广播接收机将永远不会被触发)。 – EJoshuaS

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运行,但其上运行的应用程序的主线程。

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

+0

ServiceIntent是不错的选择!我试过你说的话!但它不工作!应用程序被杀后,再次没有服务正在呼叫 –

相关问题