执行后台任务并与活动进行通信

时间:2016-09-19 16:48:25

标签: android

我有一个Activity,用户可以启动后台网络任务。活动需要与任务(两个方向)进行沟通。

如果活动被杀死且任务需要用户输入,则该任务应该发出重新启动活动的通知。

因此。什么项目应该是“任务?服务?意图服务?”

2 个答案:

答案 0 :(得分:2)

任务可以是广播接收器以重新启动活动。检查一下:

Android - launch app from broadcast receiver

BroadCast Receiver Documentation

答案 1 :(得分:1)

后台任务可以是Service,IntentService或AsyncTask。问题是接收用户输入,必须在活动中完成。所以你必须告诉活动从后台线程重启自己。这可以通过广播接收器或处理程序(具有弱引用)来完成。

我将使用如下服务,活动和处理程序:

TThread.CreateAnonymousThread(procedure begin
  Sleep(1000); // timeout

  // put here what you want to do

end).Start;

和服务:

public class ActivityMain extends Activity 
{
    public static MyService myService;    
    private MyHandler myHandler = new MyHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startService(MyService.class, myConnection, null); 
    }

    private static class MyHandler extends Handler {
        private final WeakReference<ActivityMain> activityMain;

        public MyHandler(ActivityMain activity) {
            activityMain = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MyService.NEED_USER_INPUT:
                    final Intent i = new Intent(activityMain, ActivityMain.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(i);                   
                    break;
            }
        }
    } 

    private final ServiceConnection myConnection = new ServiceConnection()
    {
        @Override
        public void onServiceConnected(ComponentName arg0, IBinder arg1)
        {
            myService = ((MyService.UsbBinder) arg1).getService();
            myService.setHandler(myHandler);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0)
        {
            myService = null;
        }
    };

    private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras)
    {
        if(MyService.SERVICE_CONNECTED == false)
        {
            Intent startService = new Intent(this, service);
            if(extras != null && !extras.isEmpty())
            {
                Set<String> keys = extras.keySet();
                for(String key: keys)
                {
                    String extra = extras.getString(key);
                    startService.putExtra(key, extra);
                }
            }
            startService(startService);
        }
        Intent bindingIntent = new Intent(this, service);
        bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
}