[go: nahoru, domu]

Skip to content

Commit

Permalink
添加 Subscribe 多线程接收事件的支持
Browse files Browse the repository at this point in the history
  • Loading branch information
zsy committed Mar 24, 2017
1 parent 5554909 commit db05176
Show file tree
Hide file tree
Showing 22 changed files with 344 additions and 97 deletions.
13 changes: 7 additions & 6 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.shizhefei.eventbus"
applicationId "com.shizhefei.eventbus.demo"
minSdkVersion 10
targetSdkVersion 25
versionCode 1
Expand All @@ -26,10 +26,11 @@ dependencies {
})
compile 'com.android.support:appcompat-v7:25.2.0'
testCompile 'junit:junit:4.12'
compile project(path: ':eventbus-api')
compile project(':eventbus-api')
compile project(':evenbus-annotation')
annotationProcessor project(':eventbus-compiler')

// compile 'com.xiaoenai:EventBus-Api:1.0.4'
// annotationProcessor 'com.xiaoenai:EventBus-Compiler:1.0.4'
// annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
// compile 'com.xiaoenai:EventBus-Api:1.0.0'
// compile 'com.xiaoenai:EventBus-Annotation:1.0.0'
// annotationProcessor 'com.xiaoenai:EventBus-Compiler:1.0.0'
// annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
}
4 changes: 2 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.shizhefei.eventbus">
package="com.shizhefei.eventbus.demo">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity android:name="com.shizhefei.eventbus.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/com/shizhefei/eventbus/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.shizhefei.eventbus.demo.R;

public class MainActivity extends AppCompatActivity {

@Override
Expand Down
64 changes: 48 additions & 16 deletions app/src/main/java/com/shizhefei/eventbus/ReceiverFragment.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,85 @@
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.shizhefei.eventbus.events.IAccountEvent;
import com.shizhefei.eventbus.demo.R;
import com.shizhefei.eventbus.events.IMessageEvent;

/**
* Created by LuckyJayce on 2017/3/20.
*/

public class ReceiverFragment extends Fragment implements IMessageEvent ,IAccountEvent {
public class ReceiverFragment extends Fragment implements IMessageEvent{
private TextView textView;
private StringBuilder stringBuilder = new StringBuilder();

private IMessageEvent iMessageEvent_main = new MyIMessageEvent();
private IMessageEvent iMessageEvent_posting = new MyIMessageEvent2();
private IMessageEvent iMessageEvent_background = new MyIMessageEvent3();
private IMessageEvent iMessageEvent_async = new MyIMessageEvent4();


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_receiver, container, false);
textView = (TextView) view.findViewById(R.id.textView);
EventBus.register(this);
EventBus.register(iMessageEvent_main);
EventBus.register(iMessageEvent_posting);
EventBus.register(iMessageEvent_background);
EventBus.register(iMessageEvent_async);
return view;
}

@Override
public void onDestroyView() {
super.onDestroyView();
EventBus.unregister(this);
EventBus.unregister(iMessageEvent_main);
EventBus.unregister(iMessageEvent_posting);
EventBus.unregister(iMessageEvent_background);
EventBus.unregister(iMessageEvent_async);
}

private StringBuilder stringBuilder = new StringBuilder();

@Override
public void onReceiverMessage(int messageId, String message) {
stringBuilder.insert(0,"messageId:"+messageId+" message:"+message+"\n");
textView.setText(stringBuilder);
}

@Override
public void logout() {
stringBuilder.insert(0,"正在执行登出操作\n");
textView.setText(stringBuilder);
}
@Subscribe(threadMode = Subscribe.MAIN)
private class MyIMessageEvent implements IMessageEvent {
@Override
public void onReceiverMessage(int messageId, String message) {
Log.d("aaaa","Subscribe.MAIN : "+Thread.currentThread().toString());
}
};

@Override
public void login() {
stringBuilder.insert(0,"正在登录中..\n");
textView.setText(stringBuilder);
}
@Subscribe(threadMode = Subscribe.POSTING)
private class MyIMessageEvent2 implements IMessageEvent {
@Override
public void onReceiverMessage(int messageId, String message) {
Log.d("aaaa","Subscribe.POSTING : "+Thread.currentThread().toString());
}
};

@Subscribe(threadMode = Subscribe.BACKGROUND)
private class MyIMessageEvent3 implements IMessageEvent {
@Override
public void onReceiverMessage(int messageId, String message) {
Log.d("aaaa","Subscribe.BACKGROUND : "+Thread.currentThread().toString());
}
};

@Subscribe(threadMode = Subscribe.ASYNC)
private class MyIMessageEvent4 implements IMessageEvent {
@Override
public void onReceiverMessage(int messageId, String message) {
Log.d("aaaa","Subscribe.ASYNC : "+Thread.currentThread().toString());
}
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import android.widget.Button;
import android.widget.EditText;

import com.shizhefei.eventbus.demo.R;
import com.shizhefei.eventbus.events.IAccountEvent;
import com.shizhefei.eventbus.events.IMessageEvent;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/
@Event
public interface ITestEvent extends IEvent{
<E extends IEvent & IAccountEvent, H> void onTest(E event, H h, int messageId, String message) throws Exception;
<E extends IEvent & IAccountEvent, H> void onTest(E event, H h, int messageId, String message);

<E extends IEvent & IAccountEvent, H> void onTest(E event, H h, int messageId);

Expand Down
1 change: 1 addition & 0 deletions evenbus-annotation/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
9 changes: 9 additions & 0 deletions evenbus-annotation/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
apply plugin: 'java'
apply from: rootProject.file('z_publish.gradle')

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"
1 change: 1 addition & 0 deletions evenbus-annotation/gradle.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
POM_ARTIFACT_ID=EventBus-Annotation
35 changes: 21 additions & 14 deletions eventbus-api/build.gradle
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
apply plugin: 'java'
apply plugin: 'com.android.library'
apply from: rootProject.file('z_publish.gradle')

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"
android {
compileSdkVersion 24
buildToolsVersion "24.0.0"


allprojects {
tasks.withType(Javadoc) {
options {
encoding "UTF-8"
charSet 'UTF-8'
links "http://docs.oracle.com/javase/7/docs/api"
defaultConfig {
minSdkVersion 10
targetSdkVersion 24
versionCode 8
versionName "1.0.7"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
abortOnError false
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
}
1 change: 0 additions & 1 deletion eventbus-api/gradle.properties
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
POM_ARTIFACT_ID=EventBus-Api
POM_PACKAGING=jar
6 changes: 6 additions & 0 deletions eventbus-api/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.shizhefei.eventbus">

<application/>

</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,24 @@

class EventHandler implements IEventHandler {

static final Map<Class<? extends IEvent>, EventProxy> interfaceImpMap = new HashMap<>();
interface EventImpFactory<IEVENT extends EventProxy> {
IEVENT create();
}

static final Map<Class<? extends IEvent>, EventImpFactory<? extends IEvent>> factoryMap = new HashMap<>();

private final static Map<IEvent, Set<EventProxy>> registers = new HashMap<>();
private final Map<Class<? extends IEvent>, EventHandler.EventProxy> interfaceImpMap = new HashMap<>();

public <IEVENT extends IEvent> IEVENT get(Class<IEVENT> eventClass) {
return (IEVENT) interfaceImpMap.get(eventClass);
private final Map<IEvent, Set<EventProxy>> registers = new HashMap<>();

public synchronized <IEVENT extends IEvent> IEVENT get(Class<IEVENT> eventClass) {
EventProxy eventProxy = interfaceImpMap.get(eventClass);
if (eventProxy == null) {
EventImpFactory<? extends IEvent> eventImpFactory = factoryMap.get(eventClass);
eventProxy = eventImpFactory.create();
interfaceImpMap.put(eventClass, eventProxy);
}
return eventClass.cast(eventProxy);
}

public synchronized void register(IEvent subscriber) {
Expand All @@ -29,7 +41,7 @@ public synchronized void register(IEvent subscriber) {
ArrayList<Class<? extends IEvent>> interfaces = Util.getInterfaces(subscriber);
Set<EventProxy> eventProxySet = new HashSet<>();
for (Class<? extends IEvent> in : interfaces) {
EventProxy eventProxy = interfaceImpMap.get(in);
EventProxy eventProxy = (EventProxy) get(in);
if (eventProxy != null) {
eventProxy.register(subscriber);
eventProxySet.add(eventProxy);
Expand Down
53 changes: 53 additions & 0 deletions eventbus-api/src/main/java/com/shizhefei/eventbus/Subscribe.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Copyright 2015 shizhefei(LuckyJayce)
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.shizhefei.eventbus;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


/**
* 标记事件的调用环境,可以注解在类上。
* Created by LuckyJayce on 2016/7/23.
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Subscribe {
/**
* 发事件后直接调用,收发在同一线程中
*/
int POSTING = 0;
/**
* 无论之前什么线程发送,都在主线程接收
*/
int MAIN = 1;
/**
* 在后台线程接收,如果发送的线程不是主线程直接调用这个,如果是主线程就开个线程执行这个方法
*/
int BACKGROUND = 2;
/**
* 无论如何都会在开个线程执行(会有个线程池,不一定是真的开个线程,可能取线程池中空闲的线程)
*/
int ASYNC = 3;

/**
* 执行在哪个线程
*/
int threadMode();

}
46 changes: 46 additions & 0 deletions eventbus-api/src/main/java/com/shizhefei/eventbus/Util.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package com.shizhefei.eventbus;

import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;

import java.util.ArrayList;


Expand All @@ -24,4 +29,45 @@ static ArrayList<Class<? extends IEvent>> getInterfaces(IEvent event) {
static boolean isExtendsInterface(Class<?> in, Class<?> superClass) {
return superClass.isAssignableFrom(in);
}

/**
* 判断是直接执行,还是需要post一个runnable
* @param subscribe
* @return true 直接执行,false 需要post一个runnable
*/
static boolean isSyncInvoke(Subscribe subscribe) {
if (subscribe == null) {
return true;
}
boolean isMainThread = Looper.getMainLooper() == Looper.myLooper();
boolean isInv;
switch (subscribe.threadMode()) {
case Subscribe.POSTING:
default:
isInv = true;
break;
case Subscribe.MAIN:
isInv = isMainThread;
break;
case Subscribe.BACKGROUND:
isInv = !isMainThread;
break;
case Subscribe.ASYNC:
isInv = false;
break;
}
return isInv;
}

private static Handler mainHandler = new Handler(Looper.getMainLooper());

static void postMain(Runnable runnable){
mainHandler.post(runnable);
}

static void postThread(Runnable runnable){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
AsyncTask.THREAD_POOL_EXECUTOR.execute(runnable);
}
}
}
2 changes: 1 addition & 1 deletion eventbus-compiler/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.google.auto.service:auto-service:1.0-rc2'
compile 'com.squareup:javapoet:1.7.0'
compile project(':eventbus-api')
compile project(':evenbus-annotation')
}
1 change: 0 additions & 1 deletion eventbus-compiler/gradle.properties
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
POM_ARTIFACT_ID=EventBus-Compiler
POM_PACKAGING=jar
Loading

0 comments on commit db05176

Please sign in to comment.