2016-07-28 5 views
0

これに関連するコードがたくさんあります。しかし、私はまだ問題に直面している 私は多くのチュートリアルとドキュメントをgoogled、私はアプリケーションを最小限に抑えるときに私はサービスを実行することができる!アプリケーションが終了または終了したときに応答しないアプリが終了すると、サービスはバックグラウンドで機能しません

ここは私のコードです!これは私のサービスクラス

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); 

    }} 
+0

'getBaseContext()'の代わりに 'this'を渡してみてください – Vucko

+0

いいえ..動作しません! –

答えて

1

サービス内のバックグラウンドスレッドで何らかのループを実行しますか?あなたのコードは、アクションを繰り返すことを示すものではありません。何が本当に欲しいのは(C#構文を使用して)、次のようなものです: Android Service Stops When App Is Closed

ちなみに、私はここにあなたの目標を誤解されるかもしれないが、あなたはまた、プッシュを使用することができます。

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

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

は以下のスレッドも参照してください。ここで同じことを達成するための通知(例:GCM) (私が尋ねる理由は、GCMを使用すると、電力管理の観点から、繰り返しポーリングするよりも良い傾向があるということです)。

好奇心が強い方は、Android Developers Backstageのポッドキャストで、バッテリーの寿命を節約し、アプリを「良い市民」にするという良い話があります。あなたは結果をアップロードする場合、あなたは(再びC#/ウェブAPI構文を使用してWebサービスに投稿するには、以下のような何かを行うことができ:私はあなたがここにそれを得ることができるはずだと思う:https://www.acast.com/androiddevelopersbackstage/episode-44-power-on

編集しかし、あなたは同じように簡単にウェブAPIやNode.jsのか、何でも)を使用してJavaを使用することができます。

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ブロードキャストを受信して​​、電話機の起動時にサービスが開始されるようにすることもできます(クライアントが明示的にオンにしない限り)。 (ここでは、ユーザーは少なくとも1回はアプリを起動していなければならない、またはブロードキャストレシーバーが決して起動されないということです)。 – 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クラスを使用しているようです。ここでの主な欠点は、背景

Service実行されますが、それはアプリケーションのメインスレッド上で実行されます。

IntentServiceは別のワーカースレッドで実行されます。

+0

ServiceIntentは良いオプションです!私はあなたが言ったことを試みた!しかし、それは動作していない!再びアプリケーションが殺された後、サービスが呼び出されていない –

関連する問題