2016-10-24 12 views
1

私はこのサービスを持っている場合、私はサービスからブロードキャストしたいので、getCoordinates()メソッドを作成する必要があります。私はgetCoordinates()メソッドを持っていると言うことができます。これは、アクティビティを呼び出すためのアクセス可能なメソッドを作成する最も良い方法ですか?その呼びかけは、それを消費したい活動にどのようになるでしょうか。サービスがクラッシュしないようにしていない場合は、何らかのチェックが必要です。私の現在のコードは以下の通りです。どうもありがとうございました。アクティビティから開始されたサービスで定義されたメソッドを実行し、その結果を返すにはどうすればよいですか?

@SuppressWarnings("MissingPermission") 
public class GPSService extends Service { 

    private LocationListener listener; 
    private LocationManager locationManager; 


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

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     listener= new LocationListener() { 
      @Override 
      public void onLocationChanged(Location location) { 
       //To transfer the data to the main activity I use broadcast receiver in the main activity, using an intent filter location_update 
       Intent intentSendLocationMainActivity = new Intent("location_update"); 
       Log.d("Location-update",location.getLongitude()+" "+location.getLongitude()); 
       intentSendLocationMainActivity.putExtra("coordinates",location.getLongitude()+" "+location.getLongitude()); 
       //I need to differentiate here if the app is killed or not to send the location to main activity or to a server 
       sendBroadcast(intentSendLocationMainActivity); 
      } 

      @Override 
      public void onStatusChanged(String s, int i, Bundle bundle) { 

      } 

      @Override 
      public void onProviderEnabled(String s) { 

      } 

      @Override 
      public void onProviderDisabled(String s) { 
       Intent activateGPSIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       activateGPSIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       startActivity(activateGPSIntent); 

      } 
     }; 
     locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); 
     //noinspection MissingPermission, listen for updates every 3 seconds 
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.d("ClearFromRecentService", "Service Started"); 
     return START_STICKY; 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Log.d("ClearFromRecentService", "Service Destroyed, Removing update location listener"); 
     //unregistering the listener 
     /*if(locationManager != null){ 
      locationManager.removeUpdates(listener); 
     }*/ 

    } 

    public void onTaskRemoved(Intent rootIntent) { 
     Log.e("ClearFromRecentService", "END"); 
     //here you can call a background network request to post you location to server when app is killed 
     Toast.makeText(getApplicationContext(), "Warning: App killed", Toast.LENGTH_LONG).show(); 
     //stopSelf(); //call this method to stop the service 
    } 

    public void getCoordinate(){ 
     //return coordinates to the user 
    } 
} 
+0

いつでもどこでも利用できるメソッドを作成しますか? –

+1

はい....それは目標です....サービスは "getCoordinates()"というメソッドを持ち、アプリケーション全体から消費されます。 – Juan

+0

getCoordinate()の静的定義方法は簡単です –

答えて

1

上のサービスからバインド解除することを忘れないでください)方法:あなたはどこにでもそれを呼び出すことができます

public static void getCoordinate(){ 
    //return coordinates to the user 
} 

このsoluctionとし、常に。

注:getCoordinates()をvoidと定義しても何も返しません。

+1

私はこれを確かにしようとしています...それはそれを行うのに最適な方法です...私はそれがクラスレベルのメソッドでもインスタンスから呼び出すことができますか? – Juan

+0

はい、あなたはGPSServiceクラスのistanceから呼び出すことができますが、正しい方法はsintax: 'GPSService.getCoordinate();' **です。例を見たり、静的メソッドの使用法、それが概念で非常に単純であっても** –

+0

この質問の一番上の答えの最初のフレーズを読んでください:http:// stackoverflow。経験値のある静的メソッドを使用するjava-questions/2671496/java _ 1つの経験則:Objがまだ構築されていなくても、このメソッドを呼び出すことは意味がありますか?もしそうなら、それは間違いなく静的でなければなりません._ –

0

サービスでは、バインダーを拡張するクラスを作成し、このクラスの内部にサービス自体へのポインタを返す関数を作成します。また、あなたのバインダークラスの同じTIPEのメンバ変数を作成し、あなたが親切GPSServieの変数を追加する必要があなたの活動では、あなたのサービス

private final IBinder mBinder = new GPSBinder(); 

public class GPSBinder extends Binder { 
    public GPSService getService() { 
     return GPSService.this; 
    } 
} 

@Override 
public IBinder onBind(Intent intent) { 
    return mBinder; 
} 

内... onBind()でこのすべてを、このオブジェクトを返し、バインドおそらくあなたのonResume()でのサービス、およびへの結合が行われたときに通知されますServiceConnectionオブジェクトを追加し、あなたがあなたのサービスのインスタンスを取得するために使用できるバインダーのインスタンスを取得します

GPSService mService; 

bindService(intent, mConnection, Context.BIND_AUTO_CREATE); // Put this in onResume() 

private ServiceConnection mConnection = new ServiceConnection() { 
    @Override 
    public void onServiceConnected(ComponentName className, IBinder service) { 
     // We've bound to LocalService, cast the IBinder and get LocalService instance 
     GPSService.GPSBinder binder = (GPSService.GPSBinder)service; 
     myService = binder.getService(); 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName arg0) { 
     mService = null; 
    } 
}; 

最後にgetCoordinate()を呼び出す必要があるときは、サービスvariaどのように静的メソッドBLE

if (myService!=null) 
    myService.getCoordinate(); // YEAH!!!!! 

あなたは(getCoordinatesを定義することができonPause()

+0

事は私が必要に応じてこれを消費する必要がある活動の上に私は断片である3つのタブがあるということです。私がフラグメントに入った場合、アクティビティのonPause()にバインドしていない場合、サービスのインスタンスを取得できますか?それを明確にするために、私は 'getGPSServiceInstance()'というメソッドを持っています。アクティビティにバインドします - >アクティビティはgetterメソッドから返される変数にアクティビティを格納します - >アクティビティputs一時停止 - >アクティビティに含まれているタブの1つ(フラグメント)がgetGPSを使用してgpsインスタンスを取得しようとします。 – Juan

+0

@Juanあなたのニーズに合ったものならば、アクティビティのすべてのロジックをフラグメント内に置くことができます。あなたは 'getActivity()。bindService(...);'を呼び出します。同時に複数のアクティビティやフラグメントからサービスにバインドすることもできます。 – Merlevede

関連する問題