您的位置:首页 > 移动开发 > Android开发

Android 利用广播调用服务中的方法

2014-05-08 17:12 411 查看
大家都知道,在Activity中时不能直接调用服务(Service)中的方法的。如果需要调用服务中的方法,可以考虑两种方法:

第一种:采用Service绑定Activity的形式,调用服务中的方法。

第二种:通过发送广播的形式,调用服务中的方法。

本文采用的是第二种。

源代码:

activity_main:

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <Button 
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="调用服务的方法"
        android:layout_centerInParent="true"
        android:onClick="call"/>
</RelativeLayout>


MainActivity:

package com.servicedemo4;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

/**
 * 通过发送广播的形式,调用服务中的方法。
 *
 */
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        /**
         * 开启 MyService服务
         */
        Intent intent = new Intent(this,MyService.class);
        startService(intent);
    }
    
    /**
     * 点击按钮发送广播
     * @param view
     */
    public void call(View view) {
        Intent intent = new Intent();
        intent.setAction("com.servicedemo4");
        sendBroadcast(intent);
    }
}


MyService:

注意需要在Manifest,xml文件中注册该服务。

package com.servicedemo4;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
	private MyReceiver receiver;
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		/**
		 * 利用代码的形式,来注册广播***。
		 */
		receiver = new MyReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.servicedemo4");
		registerReceiver(receiver, filter);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		/**
		 * 当该服务销毁的时候,销毁掉注册的广播
		 */
		unregisterReceiver(receiver);
		receiver = null;
	}
	
	/**
	 * 服务中的一个方法
	 */
	public void callInService() {
		Toast.makeText(this, "我是服务中的方法", Toast.LENGTH_SHORT).show();
	}

	/**
	 * 广播***,收到广播后调用服务中的方法。
	 * @author Administrator
	 *
	 */
	private class MyReceiver extends BroadcastReceiver {

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

	}
}


源代码下载:

点击下载源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: