只提供一种方式即服务通信的最佳方式?

时间:2016-07-02 10:59:13

标签: android service

从活动到服务的单向通信,服务无限期地运行,直到活动命令它停止。

1 个答案:

答案 0 :(得分:0)

您可以使用广播接收器在服务和活动之间进行通信

您的服务应该是这样的: -

public class MyService extends Service {

private static final String TAG = "com.example.ServiceExample";

@Override
  public void onCreate() {
    Log.i(TAG, "Service onCreate");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


    //SendBroadCast to Activity
   Intent intent = new Intent("my-event");
   intent.putExtra("message", "data");
   sendBroadcast(intent);
     return Service.START_STICKY;
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    Log.i(TAG, "Service onBind");
    return null;
}

@Override
  public void onDestroy() {
    Log.i(TAG, "Service onDestroy");
}
 }

您的活动应该是这样的: -

public class BindingActivity extends Activity {


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

@Override
protected void onStart() {
    super.onStart();

}

@Override
protected void onStop() {
    super.onStop();

}

/** Called when a button is clicked (the button in the layout file attaches to
  * this method with the android:onClick attribute) */
public void onButtonClick(View v) {

}

   private BroadcastReceiver mMessageReceiver = new BroadcastReceiver()       {
 @Override
 public void onReceive(Context context, Intent intent) {
  // Extract data included in the Intent
  String message = intent.getStringExtra("message");
  Log.d("receiver", "Got message: " + message);
 }
 };

  @Override
  public void onResume() {
  super.onResume();

 // Register mMessageReceiver to receive messages.
 registerReceiver(mMessageReceiver,
  new IntentFilter("my-event"));
  }

@Override
 protected void onPause() {
    // Unregister since the activity is not visible
    unregisterReceiver(mMessageReceiver);
      super.onPause();
            } }

              }