Service中的bindService,unbindService的使用及使用示例

     通过startService()和stopService()启动关闭服务。适用于服务和访问者之间没有交互的情况,如果服务和访问者之间需要方法调用或者传递参数,则需要使用bindService和unbindService()方法启动关闭服务于。

  采用Cotext.bindService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onBind()方法,这个时候访问者和服务会绑定在一起。如果访问者要与服务进行通信,那么,onBind()必须防护Ibinder对象,如果访问者退出了,系统会先调用服务的onUnbind()方法,接着调用onDestroy()方法,如果调用bindService()方法前服务已经被绑定,多次调用bindService()方法并不会导致多次创建服务及绑定。如果访问者希望与正在绑定的服务解除绑定,可以调用unbindService()方法,调用该方法也会导致系统调用服务的onUnbind()-->onDestroy()方法。


使用示例:(输入学号对应输出其名字)

界面文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="学号" />

    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/studentno"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查询"
        android:id="@+id/button"
        />
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        />
</LinearLayout>

后台服务:

package com.example.studentquery;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class StudentService extends Service{

	private String[] names = {"张飞","赵云","关羽"};
	private IBinder binder = new StudentBinder();
	public String query(int no){
		if(no>0 && no<4){
			return names[no-1];
		}
		return null;
	}
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return binder;
	}
	
	private class StudentBinder extends Binder implements IStudent{
		public String queryStudent(int no){
			return query(no);
		}
	}
}

访问者:

package com.example.studentquery;

import android.support.v7.app.ActionBarActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

	private EditText studentno;
	private ServiceConnection conn = new StudentServiceConnection();
	private IStudent iStudent;
	private TextView textName;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		studentno = (EditText) this.findViewById(R.id.studentno);
		Button button = (Button) this.findViewById(R.id.button);
		textName = (TextView) this.findViewById(R.id.name);
		button.setOnClickListener(new ButtonClickListener());
		
		Intent service = new Intent(this,StudentService.class);
		bindService(service, conn, BIND_AUTO_CREATE);
	}
	
	private class StudentServiceConnection implements ServiceConnection{

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			iStudent = (IStudent) (service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			iStudent = null;
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(conn);
	}
	
	private final class ButtonClickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			String no = studentno.getText().toString();
			String name = iStudent.queryStudent(Integer.valueOf(no));
			textName.setText(name);
		}
	}
}

通过接口访问私有方法:

package com.example.studentquery;

public interface IStudent {
    public String queryStudent(int no);
}

最后注意Service需要在清单文件中进行配置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是一个简单的示例,演示如何使用服务来播放音乐并在活动显示进度。在这个示例,我们使用MediaPlayer类来播放音乐,使用Handler类来更新UI元素。 1. 创建一个名为MusicService的服务类。 ```java public class MusicService extends Service implements MediaPlayer.OnCompletionListener { private MediaPlayer mediaPlayer; private Handler mHandler = new Handler(); @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); mediaPlayer = MediaPlayer.create(this, R.raw.music); mediaPlayer.setOnCompletionListener(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { mediaPlayer.start(); return START_NOT_STICKY; } @Override public void onDestroy() { super.onDestroy(); mediaPlayer.release(); } @Override public void onCompletion(MediaPlayer mp) { stopSelf(); } public int getDuration() { return mediaPlayer.getDuration(); } public int getCurrentPosition() { return mediaPlayer.getCurrentPosition(); } public void seekTo(int position) { mediaPlayer.seekTo(position); } } ``` 2. 在Activity启动服务并绑定它。 ```java public class MainActivity extends AppCompatActivity { private MusicService musicService; private boolean isBound = false; private SeekBar seekBar; private TextView currentTimeTextView; private TextView durationTextView; private Runnable mRunnable = new Runnable() { @Override public void run() { if (isBound) { int currentPosition = musicService.getCurrentPosition(); seekBar.setProgress(currentPosition); String currentTime = millisecondsToString(currentPosition); currentTimeTextView.setText(currentTime); mHandler.postDelayed(this, 1000); } } }; private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { MusicService.LocalBinder binder = (MusicService.LocalBinder) service; musicService = binder.getService(); isBound = true; int duration = musicService.getDuration(); seekBar.setMax(duration); String durationString = millisecondsToString(duration); durationTextView.setText(durationString); mHandler.postDelayed(mRunnable, 1000); } @Override public void onServiceDisconnected(ComponentName name) { isBound = false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); seekBar = findViewById(R.id.seekBar); currentTimeTextView = findViewById(R.id.currentTimeTextView); durationTextView = findViewById(R.id.durationTextView); Intent intent = new Intent(this, MusicService.class); startService(intent); bindService(intent, mServiceConnection, BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); unbindService(mServiceConnection); } private String millisecondsToString(int milliseconds) { int seconds = milliseconds / 1000; int minutes = seconds / 60; seconds = seconds % 60; return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds); } } ``` 3. 在Activity的布局文件添加一个SeekBar和两个TextView,用于显示音乐的进度。 ```xml <SeekBar android:id="@+id/seekBar" android:layout_width="match_parent" android:layout_height="wrap_content" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/currentTimeTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="00:00" /> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <TextView android:id="@+id/durationTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="00:00" /> </LinearLayout> ``` 这个例子,我们使用服务来播放音乐,并在Activity显示进度。我们还使用Handler来定期更新UI元素。当Activity被销毁时,我们解除服务的绑定。 ### 回答2: 要使用service实现音乐播放并在activity显示进度,首先需要创建一个service来处理音乐播放的逻辑。下面是实现该功能的步骤: 1. 创建一个MusicService的类,继承自Service,并实现音乐播放的逻辑。在其实例化一个MediaPlayer对象,用于控制音乐的播放、暂停等操作。 2. 在MusicService,定义一个Binder内部类,继承自Binder,并实现获取MusicService实例的方法,以便在activity进行绑定和获取MusicService对象。 3. 在MusicService,添加一个方法用于获取音乐播放的进度(例如getCurrentPosition()),并定义一个Handler对象,用于更新进度数据。 4. 在MusicService的onStartCommand()方法,开始播放音乐,并使用Handler定时更新进度数据。 5. 在activity,创建一个MediaPlayer对象和一个ServiceConnection对象,用于绑定MusicService。 6. 在activity,实现ServiceConnection接口的方法,在其获取MusicService对象,并调用MusicService的方法获取音乐进度。 7. 在activity使用一个TextView来显示音乐的进度,通过Handler不断更新TextView的文本。 8. 在activity的onStart()方法使用bindService()方法绑定MusicService,并传入ServiceConnection对象。 9. 在activity的onStop()方法使用unbindService()方法解绑MusicService。 通过以上步骤实现的代码逻辑,可以实现在activity显示音乐播放的进度。通过绑定MusicService,我们可以获取到音乐播放的进度,并在activity动态更新显示。同时,使用Handler定时获取进度数据,保证了进度的准确性和实时性。 ### 回答3: 要实现在Activity显示音乐播放的进度,可以使用Service来管理音乐播放,并通过与Activity进行通信来更新进度。 首先,在Activity创建一个ServiceConnection,用于与Service进行绑定和通信。在Activity的onCreate方法,通过bindService方法绑定Service,并将ServiceConnection传入,以便进行通信。 在Service,创建一个MediaPlayer对象用于播放音乐。在Service的onCreate方法,初始化MediaPlayer对象并设置音乐文件等参数。在Service的onStartCommand方法,启动MediaPlayer对象并开始播放音乐。 为了让Activity能够获取到音乐播放的进度,我们可以在Service创建一个Handler对象,并在MediaPlayer的onPrepared方法使用该Handler对象发送消息,将当前音乐播放的进度发送给Activity。 在Activity,创建一个Handler对象,并重写Handler的handleMessage方法,在handleMessage方法获取到音乐播放的进度,并更新到UI界面上的进度条或其他控件。 通过ServiceConnection的onServiceConnected方法,在Activity与Service成功绑定后,可以通过Binder对象提供的方法获取到Service的Handler对象,并将Activity的Handler对象传递给Service的Handler对象。 在Service,通过Activity传递的Handler对象,将音乐播放的进度发送到Activity。在Activity的Handler对象,通过接收到的消息更新UI界面上的进度。 通过上述步骤,就可以实现在Activity显示音乐播放的进度了。使用Service来管理音乐播放可以使音乐在后台不被打断,并且可以与其他组件进行通信,方便控制音乐的播放、暂停等操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值