Android-03-BackgroundJobs

来源:互联网 发布:java swing 按键监听 编辑:程序博客网 时间:2024/06/01 07:21

IntentService

IntentService的一些限制

  • 无法直接与界面进行交互,必须把交互信息发到Activity中
  • 必须顺序地执行每一个任务
  • Service中的后台操作无法被中止

实现方法

1. 继承于IntentService

public class RSSPullService extends IntentService {    @Override    protected void onHandleIntent(Intent workIntent) {        // Gets data from the incoming Intent        String dataString = workIntent.getDataString();        ...        // Do work here, based on the contents of dataString        ...    }}
2. 修改Manifest
<service    android:name=".RSSPullService"    android:exported="false"/>
3. 调用Intent
mServiceIntent = new Intent(getActivity(), RSSPullService.class);mServiceIntent.setData(Uri.parse(dataUrl));// Starts the IntentServicegetActivity().startService(mServiceIntent);

4. 使用Broadcasts来进行通信

CursorLoader

实现方法

1. 实现相关接口

public class PhotoThumbnailFragment extends FragmentActivity implements        LoaderManager.LoaderCallbacks<Cursor> {...}

2. 调用查询

private static final int URL_LOADER = 0;getLoaderManager().initLoader(URL_LOADER, null, this);

3. 实现相关操作

public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle){    /*     * Takes action based on the ID of the Loader that's being created     */    switch (loaderID) {        case URL_LOADER:            // Returns a new CursorLoader            return new CursorLoader(                        getActivity(),   // Parent activity context                        mDataUrl,        // Table to query                        mProjection,     // Projection to return                        null,            // No selection clause                        null,            // No selection arguments                        null             // Default sort order        );        default:            // An invalid id was passed in            return null;    }}

管理设备唤醒

屏幕常亮

1. 方法一:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// clear the flag to turn the off the screen<code>// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)</code>

2. 方法二:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:keepScreenOn="true">    ...</RelativeLayout>

保持CPU运行

注意保持CPU运行有可能会降低电池寿命

方法: 首先设置权限,然后再调用powerManager

<uses-permission android:name="android.permission.WAKE_LOCK" />

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);Wakelock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,        "MyWakelockTag");wakeLock.acquire();<code>// wakelock.release()</code>;

闹钟

闹钟的一些特点

  • 允许你在某一时间启动一个Intent
  • 可以结合broadcast来启动service或实现其他的一些操作
  • 他在你的应用外运行,因此既使你的应用没有运行,他也可以触发一些事件或动作
  • 他可以提高资源的利用率,你无需手动去做一个时间记录或在一个Service中来不断地运行一些工作

0 0
原创粉丝点击