如何从服务到活动获取数据

时间:2013-08-08 11:49:31

标签: android

在我的应用中,我有一项活动和服务...... 该服务将广播从GPS数据收集的消息...... 活动应接收广播消息并更新UI ...

我的代码

public class LocationPollerDemo extends Activity {
    private static final int PERIOD = 10000; // 30 minutes
    private PendingIntent pi = null;
    private AlarmManager mgr = null;
    private double lati;
    private double longi;
    private ServiceReceiver serviceReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mgr = (AlarmManager) getSystemService(ALARM_SERVICE);

        Intent i = new Intent(this, LocationPoller.class);

        i.putExtra(LocationPoller.EXTRA_INTENT, new Intent(this, ServiceReceiver.class));
        i.putExtra(LocationPoller.EXTRA_PROVIDER, LocationManager.GPS_PROVIDER);

        pi = PendingIntent.getBroadcast(this, 0, i, 0);
        mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);

        DebugLog.logTrace("On Create Demo");
        Toast.makeText(this, "Location polling every 30 minutes begun", Toast.LENGTH_LONG).show();
        serviceReceiver = new ServiceReceiver();
        IntentFilter filter = new IntentFilter("me");
        this.registerReceiver(serviceReceiver, filter);
    }

    class ServiceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            File log = new File(Environment.getExternalStorageDirectory(), "Location2.txt");
            DebugLog.logTrace(Environment.getExternalStorageDirectory().getAbsolutePath());

            try {
                BufferedWriter out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), log.exists()));

                out.write(new Date().toString());
                out.write(" : ");

                Bundle b = intent.getExtras();
                Location loc = (Location) b.get(LocationPoller.EXTRA_LOCATION);
                String msg;

                if (loc == null) {
                    loc = (Location) b.get(LocationPoller.EXTRA_LASTKNOWN);

                    if (loc == null) {
                        msg = intent.getStringExtra(LocationPoller.EXTRA_ERROR);
                    } else {
                        msg = "TIMEOUT, lastKnown=" + loc.toString();
                    }
                } else {
                    msg = loc.toString();
                }

                if (msg == null) {
                    msg = "Invalid broadcast received!";
                }

                out.write(msg);
                out.write("\n");
                out.close();
            } catch (IOException e) {
                Log.e(getClass().getName(), "Exception appending to log file", e);
                DebugLog.logException(e);
            }
        }
    }
}

当我使用此代码时,它无法正常工作...... 我在单独的文件中使用 ServiceReceiver 类工作正常.... 请告诉我...... !!

4 个答案:

答案 0 :(得分:37)

在我的服务类中,我写了这个

private static void sendMessageToActivity(Location l, String msg) {
    Intent intent = new Intent("GPSLocationUpdates");
    // You can also include some extra data.
    intent.putExtra("Status", msg);
    Bundle b = new Bundle();
    b.putParcelable("Location", l);
    intent.putExtra("Location", b);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

在活动方面,我们必须收到此广播消息

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            mMessageReceiver, new IntentFilter("GPSLocationUpdates"));

通过这种方式,您可以向活动发送消息。 这里 mMessageReceiver 是你将要执行的任何你想要的类......

在我的代码中我做了这个....

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("Status");
        Bundle b = intent.getBundleExtra("Location");
        lastKnownLoc = (Location) b.getParcelable("Location");
        if (lastKnownLoc != null) {
            tvLatitude.setText(String.valueOf(lastKnownLoc.getLatitude()));
            tvLongitude
                    .setText(String.valueOf(lastKnownLoc.getLongitude()));
            tvAccuracy.setText(String.valueOf(lastKnownLoc.getAccuracy()));
            tvTimestamp.setText((new Date(lastKnownLoc.getTime())
                    .toString()));
            tvProvider.setText(lastKnownLoc.getProvider());
        }
        tvStatus.setText(message);
        // Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
};

答案 1 :(得分:6)

获得它的好方法是使用Handler。 在您的活动中创建一个扩展Handler并覆盖handleMessage方法的内部类。

然后,在ServiceReceiver类中,创建一个处理程序变量和一个构造函数,如:

public ServiceReceiver(Handler handler){
   this.handler = handler;
}

因此,在您的活动中,创建自定义处理程序并将其传递给您的服务。因此,当您想要将某些数据添加到您的活动中时,可以将handler.sendMessage()放入您的服务中(它将调用您的innerClass的handleMessage。)

答案 2 :(得分:3)

如何将数据从IntentService发送到Activity?

  

如果服务仅用于一种方式,则无需绑定服务   通讯。对于这种情况,请使用IntentService + BroadcastReceiver   很容易

     

示例:

     

您有一个BackgroundService,   计算信号强度,并将数据每次发送回Activity   第二。活动将在GraphView中显示数据。

该怎么做?

enter image description here

从服务发送数据

public class TrackWifiService extends IntentService {

    public TrackWifiService() {
        super("wifiService");
    }

    protected void onHandleIntent(@Nullable Intent intent) {

        sendDataToActivity()
    }

   private void sendDataToActivity()
   {
        Intent sendLevel = new Intent();
        sendLevel.setAction("GET_SIGNAL_STRENGTH");
        sendLevel.putExtra( "LEVEL_DATA","Strength_Value");
        sendBroadcast(sendLevel);

   }


}

从服务接收数据
为此,您的Activity应该向BroadcastReceiver注册

public class TrackWifiActivity extends AppCompatActivity {

   WifiLevelReceiver receiver;

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.track_wifi_activity_layout);
      receiver = new WifiLevelReceiver();
      registerReceiver(receiver, new IntentFilter("GET_SIGNAL_STRENGTH"));  //<----Register
   }


   @Override
   public void onStop()
   {
       super.onStop();
       unregisterReceiver(receiver);           //<-- Unregister to avoid memoryleak
   }

   class WifiLevelReceiver extends BroadcastReceiver {

       @Override
       public void onReceive(Context context, Intent intent) {

           if(intent.getAction().equals("GET_SIGNAL_STRENGTH"))
           {
              int level = intent.getIntExtra("LEVEL_DATA",0);

              // Show it in GraphView
           }
       }

   }

}

注意:

如果要使用LocalBroadcastReceiver代替BroadcastReceiver。您只可以查看How to convert BroadCastReceiver to LocalBroadcastReceiver

相关链接

See Full project
What is an IntentService?
Difference between Bound and Unbound Services

答案 3 :(得分:1)

有三种明显的方法可以与services

进行通信
  
      
  1. 使用Intents。
  2.   
  3. 使用AIDL。
  4.   
  5. 使用服务对象本身(作为单身人士)。
  6.