Main UI thread

 

 

public class BroadcastMain extends Activity {
    protected static final String TAG = "CM-BroadcastMain";

    Button send;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            Log.d(TAG, "onReceive() Thread id: "
                    + Thread.currentThread().getId());
            notifyResult();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Log.d(TAG, "onCreate() Thread id: " + Thread.currentThread().getId());

        IntentFilter filter = new IntentFilter();
        filter.addAction("org.crazyit.action.CRAZY_BROADCAST");
        this.registerReceiver(mReceiver, filter);

        send = (Button) findViewById(R.id.send);
        send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("org.crazyit.action.CRAZY_BROADCAST");
                Log.d(TAG, "sendBroadcast()");
                sendBroadcast(intent);
            }
        });

        new Thread() {
            @Override
            public void run() {
                toWait();
            }
        }.start();
    }

    private synchronized void toWait() {
        try {
            Log.d(TAG, "wait() thread id: " + Thread.currentThread().getId());
            Log.d(TAG, "wait()...");
            
            wait(20000);
        } catch (Exception e) {
            Log.d(TAG, "wait Exception");
            e.printStackTrace();
        }

        Log.d(TAG, "toWait() end");
    }

    public synchronized void notifyResult() {
        Log.d(TAG, "notifyResult() Thread id: " + Thread.currentThread().getId());
        notifyAll();
    }

    @Override
    protected void onDestroy() {
        this.unregisterReceiver(mReceiver);
        super.onDestroy();
    }
}

03-27 04:16:07.035 32393 32393 D CM-BroadcastMain: onCreate() Thread id: 1
03-27 04:16:07.035 32393   322 D CM-BroadcastMain: wait() thread id: 5485
03-27 04:16:07.035 32393   322 D CM-BroadcastMain: wait()...
//click "send broadcast"
03-27 04:16:10.535 32393 32393 D CM-BroadcastMain: sendBroadcast()
03-27 04:16:10.535 32393 32393 D CM-BroadcastMain: onReceive() Thread id: 1
03-27 04:16:10.535 32393 32393 D CM-BroadcastMain: notifyResult() Thread id: 1
03-27 04:16:10.535 32393   322 D CM-BroadcastMain: toWait() end

 

onRecevier() handleMessage()onServiceConnected() onServiceDisconnected()都是在主线程运行的。

posted @ 2015-03-18 18:43  牧 天  阅读(444)  评论(0)    收藏  举报