Android service向activity发送信息

package com.example.imgswitch;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
    XabService service;
    private Button send_broadcast_button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter intentFilter = new IntentFilter();
        send_broadcast_button = (Button) this.findViewById(R.id.send_broadcast_button);
        send_broadcast_button.setOnClickListener(this);
        intentFilter.addAction("cn.abel.action.broadcast");
        this.registerReceiver(new MyBroadcastReciver(), intentFilter);
    }

    private class MyBroadcastReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("cn.abel.action.broadcast")) {
                String author = intent.getStringExtra("author");
                // 在控制台显示接收到的广播内容
                System.out.println("author==>" + author);
                // 在android端显示接收到的广播内容
                Toast.makeText(MainActivity.this, author, 1).show();
                // 在结束时可取消广播
                //MainActivity.this.unregisterReceiver(this);
            }
        }

    }

    @Override
    public void onClick(View v) {
        service = new XabService(this);
        service.init();
    }
}

上面是activity中接受和注册监听器以及调用service的代码

下面是service端发送信息

package com.example.imgswitch;

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

public class XabService extends Service {
    Context context;

    public XabService(Context context) {
        this.context = context;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void init(){
Intent intent
= new Intent(); intent.setAction("cn.abel.action.broadcast"); intent.putExtra("author", "Abel"); context.sendBroadcast(intent); } }

 

转载于:https://www.cnblogs.com/xab97/archive/2013/05/21/3091833.html

你可能感兴趣的:(Android service向activity发送信息)