安卓 利用廣播調用服務方法 學習筆記

建立服務類

package com.tang.receiverService;

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 BoradService extends Service {
	private MyReceiver receiver;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
                //代碼建立一個廣播
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.tang.boardReceiver");
		receiver = new MyReceiver();
		registerReceiver(receiver, filter);
		super.onCreate();
	}
	private class MyReceiver extends BroadcastReceiver
	{
		public void onReceive(Context arg0, Intent arg1) {
			serviceMethod();
		}
	}
	
	private void serviceMethod()
	{
		Toast.makeText(getApplicationContext(), "服務裏面的方法", Toast.LENGTH_SHORT).show();
	}
}

##配置清單android

<service android:name=".BoradService"></service>

##廣播app

public void callMethod(View view)
	{
		Intent intent = new Intent();
		intent.setAction("com.tang.boardReceiver");
		sendBroadcast(intent);
	}
相關文章
相關標籤/搜索