如何防止每次创建活动时调用服务?

时间:2015-04-16 15:46:31

标签: android android-lifecycle android-cursoradapter android-cursorloader

在我的活动中,在onCreate方法中,我调用服务以打开Internet连接以发出服务器请求。然后,我将服务器的数据保存到数据库,并通过片段中的CursorLoader(和CursorAdapter)以列表的形式将其显示给UI。问题是,每次用户导航到该活动时,连接都会再次启动,提示Loader重新加载数据,从而多次显示相同的列表。因此,虽然列表每次都应该读取相同的内容,例如:

  • 运动
  • 天气
  • 新闻

实际发生的情况是,每次用户导航回主机活动时,列表都会再次显示,因此如果用户导航到活动3次,列表将会显示如下:

  • 运动
  • 天气
  • 新闻
  • 运动
  • 天气
  • 新闻
  • 运动
  • 天气
  • 新闻

如何阻止活动每次都调用服务? 此外,问题可能是装载机吗?

活动和片段的代码:

活动

public class HappinessActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_happiness);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.happiness_container, new HappinessFragment())
                .commit();
    }
        Intent intent = new Intent(this, ArticleService.class);
        intent.putExtra(ArticleService.CATEGORY_EXTRA, 1);
        startService(intent);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_happiness, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

片段

public class HappinessFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

private String LOG_TAG = this.getClass().getSimpleName();

private static final int ARTICLE_LOADER = 0;
private ArticleAdapter mAdapter;
private ListView mListView;

public HappinessFragment() {
}

private static final String[] ARTICLE_COLUMNS = {
        ArticleContract.ArticlesEntry._ID,
        ArticleContract.ArticlesEntry.COLUMN_CATEGORY_ID,
        ArticleContract.ArticlesEntry.COLUMN_ARTICLE_ID,
        ArticleContract.ArticlesEntry.COLUMN_AUTHOR,
        ArticleContract.ArticlesEntry.COLUMN_TITLE,
        ArticleContract.ArticlesEntry.COLUMN_URL
};

static final int COL_ART_ID = 0;
static final int COL_CATEGORY_ID = 1;
static final int COL_ARTICLE_ID = 2;
static final int COL_AUTHOR = 3;
static final int COL_TITLE = 4;
static final int COL_URL = 5;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    mAdapter = new ArticleAdapter(getActivity(), null, 0);
    View rootView = inflater.inflate(R.layout.fragment_happiness, container, false);

    mListView = (ListView) rootView.findViewById(R.id.happiness_list);
    mListView.setAdapter(mAdapter);

    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    getActivity().getLoaderManager().initLoader(ARTICLE_LOADER, null, this);
}

@Override
public void onPause() {
    super.onPause();
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    //Uri queryUri = ArticleContract.ArticlesEntry.buildArticleList();
    String URL = "content://app.quantumfinality.com.soulremedy/articles";
    Uri uri = Uri.parse(URL);
    Log.v("CursorLoader", "Table path built");
    String sortOrder = ArticleContract.ArticlesEntry._ID;

    return new CursorLoader(getActivity(),
            uri,
            ARTICLE_COLUMNS,
            null,
            null,
            sortOrder);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    mAdapter.swapCursor(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    mAdapter.swapCursor(null);

}
}

提前谢谢你。非常感谢任何帮助,因为该项目即将到期。

1 个答案:

答案 0 :(得分:2)

你可以尝试两种方法

1 创建布尔值并检查是否第一次调用它并调用代码

//static variable
static boolean firstTyme = true;     
// in onDestroy of your service class set it to false. 
// so with that the service takes care of the toggling
/// now you check the boolean in your activity onCreate if its true/false

2 第二种方法是检查服务是否已经在运行,如果没有调用它,如果它没有调用它

boolean running =false;
ActivityManager manager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (YourServiceClass.getName().equals(service.service.getClassName())) {
            // it checks out to be running so you let fly
            running = true;
            break;
        }
    }
 if(!running){ // if running is false
    // call your intent funtions
  }