2017-09-08 27 views
0

ActivityクラスからJobServiceに緯度と経度の値を取得したいと思います。どうやってやるの?私はputExtrasなどでIntentを使ってみました(以下のコードを見てください)が、それは正しくできませんでした。ActivityからJobServiceにデータを渡す

MainActivity.class

protected void createLocationRequest(Bundle bundle) { 

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationCallback() { 
     @Override 
     public void onLocationResult(final LocationResult locationResult) { 
      Log.i("onLocationResult", locationResult + ""); 
      latitude = locationResult.getLastLocation().getLatitude() + ""; 
      longitude = locationResult.getLastLocation().getLongitude() + ""; 
      Log.e("onLocationResult lat", latitude); 
      Log.e("onLocationResult Lon", longitude); 
      //I need to send latitude and longitude value to jobService? 
      //how to do that? 

     //tried using intent but didn't seem to work 
      //Intent mIntent = new Intent(); 
      //mIntent.putExtra("lat", latitude); 
      //mIntent.putExtra("lon", longitude); 
     } 
    }, null); 
} 

MyJobServiceクラス

public class MyJobService extends JobService { 

    @Override 
    public boolean onStartJob(JobParameters jobParameters) { 
     //I need to get latitude and longitude value here from mainActivity 
     return true; 
    } 
} 

答えて

0

JobInfoオブジェクトを作成する場合は、setExtras()を使用してPersistableBundleのextrasを渡します。

ComponentName componentName = new ComponentName(context, MyJobService.class); 

PersistableBundle bundle = new PersistableBundle(); 
bundle.putLong("lat", lat); 
bundle.putLong("lon", lon); 

JobInfo jobInfo = new JobInfo.Builder(0, componentName) 
     .setExtras(bundle) 
     .build(); 

次に、あなたのJobServiceにあなたは

@Override 
public boolean onStartJob(JobParameters params) { 
    params.getExtras().getLong("lat"); 
    params.getExtras().getLong("lon"); 
} 
でそれらを取得することができます
1

あなたが共有設定で、これらのデータを格納することができ、かつonStartJob()メソッドを使用すると、そこからの緯度、長いデータにアクセスすることができます呼び出します。

サービスの実行時に、最新のロケーションの緯度の長い値で共有設定値を更新し、最新の緯度を長くすることもできます。

関連する問題