2016-07-28 27 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是不錯的選擇!我試過你說的話!但它不工作!應用程序被殺後,再次沒有服務正在呼叫 –

相關問題