将服务价值传递给活动

时间:2015-07-10 16:17:24

标签: android

我有服务类,可以获取GPS位置和速度带。我能够在另一个活动中显示Toast中的值,但我无法在TextView中显示。我的ServiceActivity类不包含xml,而我的MainActivity类包含xml。我想在ServiceActivity TextView中显示MainActivity值。

MyService.java

public class MyService extends Service
{ 
 private LocationManager locManager;
 private LocationListener locListener = new myLocationListener();
 static final Double EARTH_RADIUS = 6371.00;

 private boolean gps_enabled = false;
 private boolean network_enabled = false;

 private Handler handler = new Handler();
 Thread t;

   @Override
   public IBinder onBind(Intent intent) {return null;}
   @Override
   public void onCreate() {}
   @Override
   public void onDestroy() {}
   @Override
   public void onStart(Intent intent, int startid) {}   
   @Override
 public int onStartCommand(Intent intent, int flags, int startId){

 Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT).show();

 final Runnable r = new Runnable()
 {   public void run() 
     {
   Log.v("Debug", "Hello");
   location();
   handler.postDelayed(this, 5000);
     }
 };
  handler.postDelayed(r, 5000);  
       return START_STICKY; 
 }

   public void location(){
 locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

 try{
 gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
 }
 catch(Exception ex){}
 try{
 network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);    
 }
 catch(Exception ex){}
 Log.v("Debug", "in on create.. 2");   
 if (gps_enabled) {
 locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locListener);
 Log.v("Debug", "Enabled..");
 }
 if (network_enabled) {
 locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locListener);
 Log.v("Debug", "Disabled..");
 }
 Log.v("Debug", "in on create..3");
 }   

   private class myLocationListener implements LocationListener
   {
      double lat_old=0.0;
      double lon_old=0.0;
      double lat_new;
      double lon_new;
      double time=10;
      double speed=0.0;
      @Override
 public void onLocationChanged(Location location) {   
 Log.v("Debug", "in onLocation changed..");   
 if(location!=null){    
 locManager.removeUpdates(locListener);    
 //String Speed = "Device Speed: " +location.getSpeed();
 lat_new=location.getLongitude();
 lon_new =location.getLatitude();
 String longitude = "Longitude: " +location.getLongitude();
 String latitude = "Latitude: " +location.getLatitude();    
 double distance =CalculationByDistance(lat_new, lon_new, lat_old, lon_old);    
 speed = distance/time;     


 /*Intent intent = new Intent(MyService.this, MainActivity.class);
 String DD = String.valueOf(distance);

 intent.putExtra(USERNAME, DD);
 intent.putExtra(EMAIL,email);
 startActivity(intent);
 */
 Intent intent = new Intent("YourAction");
 Bundle bundle = new Bundle();
 //bundle.put... // put extras you want to pass with broadcast. This is optional
bundle.putString("valueName", "The value you want in the activity");
// bundle.putDouble("doubleName", speed);
 intent.putExtras(bundle);
 LocalBroadcastManager.getInstance(MyService.this).sendBroadcast(intent);

 Toast.makeText(getApplicationContext(), longitude+"\n"+latitude+"\nDistance is: "
   +distance+"\nSpeed is: "+speed , Toast.LENGTH_SHORT).show();
 lat_old=lat_new;
 lon_old=lon_new;
 }
 }
 @Override
 public void onProviderDisabled(String provider) {}
 @Override
 public void onProviderEnabled(String provider) {}
 @Override
 public void onStatusChanged(String provider, int status, Bundle extras) {}    
   }   

   public double CalculationByDistance(double lat1, double lon1, double lat2, double lon2) {
  double Radius = EARTH_RADIUS;
  double dLat = Math.toRadians(lat2-lat1);  
  double dLon = Math.toRadians(lon2-lon1);  
  double a = Math.sin(dLat/2) * Math.sin(dLat/2) +  
  Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *  
  Math.sin(dLon/2) * Math.sin(dLon/2);  
  double c = 2 * Math.asin(Math.sqrt(a));  
  return Radius * c;
   }   
}

DeviceMovingSpeed.java

 public class DeviceMovingSpeed extends Activity {
    TextView out;
    private MyBroadcastReceiver myReceiver;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        out = (TextView)findViewById(R.id.ss);
    }

    @Override
    public void onResume(){
         super.onResume();
        myReceiver = new MyBroadcastReceiver();
        final IntentFilter intentFilter = new IntentFilter("YourAction");
        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
    }

    @Override
    public void onPause(){
        if(myReceiver != null)
            LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
        myReceiver = null;
    }


    public class MyBroadcastReceiver extends BroadcastReceiver {

            @Override
            public void onReceive(Context context, Intent intent) {
                 // Here you have the received broadcast 
                 // And if you added extras to the intent get them here too
                 // this needs some null checks
                 Bundle b = intent.getExtras();
                 String yourValue = b.getString("valueName");

                 out.setText(yourValue);

                 Toast.makeText(getApplicationContext(), yourValue, Toast.LENGTH_SHORT).show();
                // double someDouble = b.getDouble("doubleName");
                 ///do something with someDouble
            }
    }





}

清单文件

  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.xyz"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
 <uses-permission android:name="android.permission.VIBRATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".DeviceMovingSpeed"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true" >
            <intent-filter>
                <action android:name="com.example.gpstesting.MyService" >
                </action>
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>

LogCat显示此结果....

07-13 14:21:26.169: D/ActivityThread(3310): setTargetHeapConcurrentStart:2097152
07-13 14:21:26.909: D/libEGL(3310): loaded /system/lib/egl/libEGL_adreno200.so
07-13 14:21:26.949: D/libEGL(3310): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
07-13 14:21:26.949: D/libEGL(3310): loaded /system/lib/egl/libGLESv2_adreno200.so
07-13 14:21:26.969: I/Adreno200-EGL(3310): <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.107_msm8625_JB_REL_2.0.3_CL3357771_release_AU (CL3357771)
07-13 14:21:26.969: I/Adreno200-EGL(3310): Build Date: 02/25/13 Mon
07-13 14:21:26.969: I/Adreno200-EGL(3310): Local Branch: 
07-13 14:21:26.969: I/Adreno200-EGL(3310): Remote Branch: quic/jb_rel_2.0.3
07-13 14:21:26.969: I/Adreno200-EGL(3310): Local Patches: NONE
07-13 14:21:26.969: I/Adreno200-EGL(3310): Reconstruct Branch: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.107 +  NOTHING
07-13 14:21:27.069: D/OpenGLRenderer(3310): Enabling debug mode 0

我无法从MyService.java获取值到DeviceMovingSpeed.java

3 个答案:

答案 0 :(得分:2)

我确信几乎没有办法,但我会做一个本地广播。以下是它的要点:

在您的服务中:

Intent intent = new Intent("YourAction");
Bundle bundle = new Bundle();
bundle.put... // put extras you want to pass with broadcast. This is optional
bundle.putString("valueName", "The value you want in the activity");
bundle.putDouble("doubleName", someDouble);
intent.putExtras(bundle)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

然后,在您的活动中:

private MyBroadcastReceiver myReceiver;

@Override
public void onResume(){
    myReceiver = new MyReceiver();
    final IntentFilter intentFilter = new IntentFilter("YourAction");
    LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}

@Override
public void onPause(){
    if(myReceiver != null)
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
    myReceiver = null;
}

public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
             // Here you have the received broadcast 
             // And if you added extras to the intent get them here too
             // this needs some null checks
             Bundle b = intent.getExtras();
             String yourValue = b.getString("valueName");
             someTextView.setText(yourValue);
             double someDouble = b.getDouble("doubleName");
             ///do something with someDouble
        }
}

答案 1 :(得分:0)

使用Intents发送数据:

Intent YOURINTENT = new Intent(context, SOMECLASS.class); YOURINTENT.putExtra("YOURPACKAGE.SOME_IDENTIFIER", "THE_VALUE_GOES_HERE"); context.startActivity(YOURINTENT );

然后在活动中:

Intent YOURINTENT = getIntent(); String example = YOURINTENT.getStringExtra("YOURPACKAGE.SOME_IDENTIFIER");

答案 2 :(得分:0)

在你的putExtra中你的意图是你自己添加意图. intent.putExtras(intent); 您应该在putExtras中添加bundle而不是intent对象。 所以修改你的代码如下。

     Intent intent = new Intent("YourAction");
     Bundle bundle = new Bundle();
     bundle.putString("valueName", "The value you want in the activity");
     bundle.putDouble("doubleName", distance);
     intent.putExtras(bundle);

你也错过了onResume的超级实现。将它添加为你简历的第一行。

     super.onResume();

您正在广播中初始化TextView不要在Oncreate中启动文本视图

 TextView out = (TextView)findViewById(R.id.ss);
相关问题