Android通过广播接收者调用服务内方法

服务;

package com.pas.callmethod;

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 MyReciver receiver;
	
	@Override
	public void onCreate()
	{
		//采用代码方式注册广播接收者
		receiver=new MyReciver();
		IntentFilter filter=new IntentFilter();
		filter.addAction("com.pas.call");
		registerReceiver(receiver, filter);
		super.onCreate();
	}
	
	@Override
	public void onDestroy()
	{
		unregisterReceiver(receiver);
		receiver=null;
		super.onDestroy();
	}
	@Override
	public IBinder onBind(Intent arg0)
	{
		return null;
	}

	private void method_inservice()
	{
		Toast.makeText(getApplicationContext(), "我的服务的方法……", Toast.LENGTH_SHORT).show();
	}
	
	private class MyReciver extends BroadcastReceiver
	{

		@Override
		public void onReceive(Context arg0, Intent arg1)
		{
			System.out.println("内部接收者");
			method_inservice();
		}
		
	}
}



MAINAC:
package com.pas.callmethod;

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

public class MainActivity extends Activity
{

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Intent intent=new Intent(this,MyService.class);
		startService(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void call(View v)
	{
		//发送自定义广播
		Intent intent=new Intent();
		intent.setAction("com.pas.call");
		sendBroadcast(intent);
	}
}



你可能感兴趣的:(Android通过广播接收者调用服务内方法)