android service and broadcast

1. MyService

public class MyService extends Service {
	private final static String TAG = "main";
	public final static String SEND_OK_MESSAGE = "send.ok.message";  
	public final static String SEND_CANCLE_MESSAGE = "send.cancle.message";
	private Context mContext;
	
	private int count;
	private MyBinder binder=new MyBinder();
	private Thread thread;
	private boolean quit;

	@Override
	public IBinder onBind(Intent arg0) {
		if(mContext!=null){
			Toast.makeText(mContext, "绑定成功", Toast.LENGTH_LONG).show();	
		}
		return binder;
	} 
	
	public boolean onUnbind(Intent intent) {
		if(mContext!=null){
			Toast.makeText(mContext, "解除绑定", Toast.LENGTH_LONG).show();	
		}
		return true;
	}	
	
	public void onCreate(){
		super.onCreate();
		thread=new Thread(new Runnable() {
			@Override
			public void run() {
				while(!quit){
					try{
						Thread.sleep(1000);
					}catch(InterruptedException e){
						e.printStackTrace();
					}
					count++;
				}
			} 
		});
		thread.start();
	}	
         //启动服务时,注册一个广播	
	public void onStart(Intent intent, int startId) {
		IntentFilter myFilter = new IntentFilter(); 
		myFilter.addAction(SEND_OK_MESSAGE); 
		myFilter.addAction(SEND_CANCLE_MESSAGE); 
		this.registerReceiver(myBroadCast, myFilter); 
		super.onStart(intent, startId); 
	}
	
	private BroadcastReceiver myBroadCast = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			//广播接收到消息
			mContext = context;
			String action = intent.getAction();  
			if (action.equals(SEND_OK_MESSAGE)) { 
				Toast.makeText(context, "接收到了一条广播为" + SEND_OK_MESSAGE, Toast.LENGTH_LONG).show(); 
			}else if(action.equals(SEND_CANCLE_MESSAGE)) { 
				Toast.makeText(context, "接收到了一条广播为" + SEND_CANCLE_MESSAGE, Toast.LENGTH_LONG).show(); 
			}
		} 
	};
	
	class MyBinder extends Binder{ 
		public int getCount(){
			return count;
		}
	}	
	
}

2. MyBootReceiver

public class MyBootReceiver extends BroadcastReceiver {
	static final String BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED"; 
	
	@Override
	public void onReceive(Context context, Intent intent) {
		//扩展一个广播类,用于开机就启动服务
		if (intent.getAction().equals(BOOT_COMPLETED)) {
			Log.i("MyBootReceiver", "yzf, onReceive, startService");
			Intent i = new Intent(context, MyService.class);
			context.startService(i); 
		}
	} 
}

3. MainActivity

public class MainActivity extends Activity implements OnClickListener {
	
	private Button btnOk;
	private Button btnCancel;
	private Intent intent; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Log.i("MainActivity", "yzf, onCreate");
		
		btnOk = (Button) findViewById(R.id.btn_ok);
		btnCancel = (Button) findViewById(R.id.btn_cancel);
		
		btnOk.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		//启动服务
		intent = new Intent(this, MyService.class); 
		startService(intent);
	}

	//用以发送广播
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		Intent vIntent;
		switch(arg0.getId()){
		case R.id.btn_ok:
			vIntent = new Intent("send.ok.message");
			sendBroadcast(vIntent); 
			break;
		case R.id.btn_cancel:
			vIntent = new Intent("send.cancle.message");
			sendBroadcast(vIntent);
			break;
		}
	}
	
    public void onDestroy(){  
        super.onDestroy();  
  
        if(intent != null){  
            stopService(intent);  
        } 
    } 	

}

4. 服务与广播的XML注册

        <service android:name=".MyService">
            <intent-filter>
                <action android:name="cn.m15.xys.MyService"></action>  
            </intent-filter> 
			<intent-filter>
			    <action android:name="send.ok.message" /> 
			    <action android:name="send.cancle.message" /> 
			</intent-filter>
        </service>
        
        <receiver android:name=".MyBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
            </intent-filter>
        </receiver>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
To enable communication between a remote Activity and the Service, we can make use of the Android Bound Service framework. This framework allows for a client application to bind to a service and interact with it via an interface. In this case, we can create a simple interface that defines the methods we want to expose to the client application (e.g. post update). We can then implement this interface in the Service class and expose it to the client application by returning it from the onBind() method. Here's an example of what the Service and Activity classes might look like: Service Class: ``` public class UpdateService extends Service { private IBinder binder = new UpdateBinder(); @Override public IBinder onBind(Intent intent) { return binder; } public void postUpdate(String message) { // Code to post the update to the social media application } private class UpdateBinder extends Binder implements IUpdateService { @Override public void postUpdate(String message) { UpdateService.this.postUpdate(message); } } public interface IUpdateService { void postUpdate(String message); } } ``` Activity Class: ``` public class MainActivity extends AppCompatActivity { private UpdateService.IUpdateService updateService; private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { updateService = (UpdateService.IUpdateService) service; } @Override public void onServiceDisconnected(ComponentName name) { updateService = null; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(this, UpdateService.class); bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); } public void onClickPostUpdate(View view) { if (updateService != null) { updateService.postUpdate("New update message"); } } @Override protected void onDestroy() { super.onDestroy(); unbindService(serviceConnection); } } ``` In this example, the Activity binds to the Service in the onCreate() method using an Intent. The ServiceConnection object is used to receive a reference to the IUpdateService interface, which can then be used to call the postUpdate() method. When the Activity is destroyed, it unbinds from the Service to release any resources held by the connection. Note that this is just a simple example and there are many ways to implement communication between a Service and Activity in Android. Depending on the requirements of your particular application, you may need to use other components such as BroadcastReceivers or ContentProviders.

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值