如何在android中暂停和恢复线程

时间:2014-06-26 17:07:53

标签: android multithreading android-asynctask adapter android-syncadapter

当我在UserRecoverableAuthIOException中获得AbstractThreadedSyncAdapter时,我正在创建如下通知。

以下是我创建服务的方式:

@覆盖     public IBinder onBind(Intent arg0){         // TODO自动生成的方法存根         Log.i("服务","线程开始");         return this.getSyncAdapter()。getSyncAdapterBinder();     }

private GoogleTasksSyncAdapter getSyncAdapter() {
    if (syncAdapter == null)
    {
        Log.i("Service", "syncAdapter started");
        syncAdapter = new MySyncAdapter(this);

    }
    return syncAdapter;

}

一旦线程启动,我就会发出通知。但是,一旦用户点击通知,他们就可以看到授权活动。授权后如何从最后一点恢复。即,在Syncadapter中关闭活动后如何收到通知。

3 个答案:

答案 0 :(得分:1)

SyncAdapter线程正在运行,您希望在SyncAdapter结束时收到通知,对吗?

因此,您可以将SyncAdapter线程与BroadCast通信。

在SyncAdapter类中:

Intent i = new Intent(SYNC_FINISHED);
    context.sendBroadcast(i);
    Log.i(TAG, "Network synchronization complete");

在活动或片段中:

private BroadcastReceiver syncFinishedReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Sync finished!!");

        // Here you can send your notification or another thing that you want
    }
};

@Override
public void onStart() {
    super.onStart();
    getActivity().registerReceiver(syncFinishedReceiver, new IntentFilter(SyncAdapter.SYNC_TASK_FINISHED));
}

@Override
public void onStop() {
    super.onStop();
    getActivity().unregisterReceiver(syncFinishedReceiver);
}

注意:SYNC_FINISHED常量,您可以先在SyncAdapter中定义

我希望我能帮助你。

问候!

答案 1 :(得分:1)

在SyncAdapter中,您可以执行以下操作:

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

    Log.i(TAG, "Beginning network synchronization");

    if(extras.getBoolean(RUN_METHOD_1) || extras.getBoolean(RUN_ALL)) {
        method1();
    }
    if(extras.getBoolean(RUN_METHOD_2) || extras.getBoolean(RUN_ALL)) {
        method2();
    }
}

public void method1(){
  try{
        // do something

     } catch (Exception e) {
       e.printStackTrace();

       // here you can send your notification when exception occours.
     }
}

public void method2(){
  try{
        // do something

     } catch (Exception e) {
       e.printStackTrace();

       // here you can send your notification when exception occours.
     }
}

在您的“授权”代码中,您执行以下操作:

        Bundle b = new Bundle();
        b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        b.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
        b.putBoolean(SyncAdapter.RUN_METHOD_1, true);

        ContentResolver.requestSync(account, CONTENT_AUTHORITY, b); 

所以你可以在同步停止的地方跑。

问候!!!

答案 2 :(得分:0)

这是解决方案,

我们需要使用syncResult.stats.numAuthExceptions来告诉异常,它会自动抛出消息。 syncResult.delayUntil将等待并在经过时间后重新启动同步

How to show sync failed message