如何从同步适配器访问应用程序对象

时间:2014-06-17 13:46:26

标签: android android-syncadapter

我正在使用开放式服务器开发IM应用程序。我正在实施同步适配器来管理联系人。

从我的同步适配器' s onPerformSync()如果我访问保存在Application类中的连接对象,则返回 null

我做错了什么?我该怎么做?

我的申请类

public class MyApp extends Application {
    private Connection connection;
    private static MyApp instance;
    public static MyApp getInstance() {
    return instance;
}

public static void setInstance(MyApp instance) {
    MyApp.instance = instance;
}
@Override
public void onCreate() {
    super.onCreate();
    instance = new MyApp();
}
public Connection getAuthenticatedConnection() throws NullPointerException {

    if (instance.connection != null
            && instance.connection.isAuthenticated()) {
        return instance.connection;
    } else {

//  Calling service which will create connection and update the object

        Intent intent = new Intent(IM_Service_IntentMessaging.ACTION);
        intent = new Intent(getContext(), IM_Service_IntentMessaging.class);
        Bundle b = new Bundle();
        b.putInt("key", IM_Service_IntentMessaging.KEY_CONNECTION);
        intent.putExtras(b);
        this.context.startService(intent);

        throw new NullPointerException();
    }
//service calls this method to update the object
public void setConnection(Connection connection) {
    instance.connection = connection;
}
}

我的onPerformSync方法如下......

@Override
public void onPerformSync(Account account, Bundle bundle, String authority,
        ContentProviderClient provider, SyncResult syncResult) {

    try {

        this.connection = MyApp.getInstance()
                .getAuthenticatedConnection();

        this.roster = this.connection.getRoster();

    } catch (NullPointerException e) {
                    //this line executes always
        Log.e(TAG, "connection null...ending....");

        return;
    }

    this.mAccount = account;

    Log.d(TAG, "...onPerformSync...");

    getAllContacts();
}

当我尝试在应用程序的getAuthenticatedConnection()方法中创建断点时,它没有被触发但是我从那里调用以创建连接的服务IM_Service_IntentMessaging正在工作。< / p>

1 个答案:

答案 0 :(得分:0)

我发现我的问题的解决方案是我应该从同步适配器的清单文件声明中删除android:process=":sync"。因此,它就像对待不同的过程一样。