Android与app和app之间的通信

时间:2015-12-01 15:23:25

标签: android

我在Android中创建了一个库,我希望将一些值(字符串)从库中传递给在某些事件后使用该库的应用程序。使用该库的应用程序只有一个屏幕来显示库发送的字符串。

我的应用有一个MainActivity,可以使用库收到的事件填充listView。 它还有一个MyApp,可以扩展Application

我这样做:

public class MyApp extends Application{

    private static MyApp sMyApp;


    public MyApp() {

    }

    @Override
    public void onCreate() {
        super.onCreate();
        sMyApp= this;

        MyLibrary.getInstance().setApplication(sMyApp);

    }

    public static MyApp getInstance() {
        return sMyApp;
    }

}

在我的图书馆:

public class MyLibrary {
    private static MyLibrary sInstance = new MyLibrary();
    private Application mMyApp;

    public static MyLibrary getInstance() {
        return sInstance;
    }

    private MyLibrary() {
    } 

    public void setApplication(Application myApp) {
        mMyApp = myApp;

    }

    public void sendEventMessage(String message) {
        mMyApp.setEvent(message);
    }
}

我已尝试在MainActivity中实施一个界面,以便mMyApp.setEvent(message);可以发送MainActivity可以收到但却没有成功的消息。

我如何实现我假装的目标?

1 个答案:

答案 0 :(得分:0)

您可以尝试回调此示例:

首先,在库中声明你的回调

public interface ILibrary {
public void onStart(String msg);

public void onProcess(String msg);

public void onFish(String msg);}

public class SDK {
private static final String START = "I'm started";

private static final String PROCESSING = "I'm running";

private static final String STOP = "I'm done";

private ILibrary mCallback;

// Make it easy for demo
public SDK(ILibrary callback) {
    mCallback = callback;
}

public void start() {
    mCallback.onStart(START);
}

public void process() {
    mCallback.onProcess(PROCESSING);
}

public void stop() {
    mCallback.onFish(STOP);
}}

然后做那样的事情:

SDK sdk = new SDK(new ILibrary() {

    @Override
    public void onStart(String msg) {
        Log.d("TAG", msg);
    }

    @Override
    public void onProcess(String msg) {
        Log.d("TAG", msg);
    }

    @Override
    public void onFish(String msg) {
        Log.d("TAG", msg);
    }
});

AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            sdk.process();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            sdk.stop();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            sdk.start();
        }

    };
    asyncTask.execute();