即使手机处于睡眠状态,也可以在后台运行上传过程

时间:2014-02-24 12:11:10

标签: android multithreading service alarmmanager

所以我开发了一个Android应用程序,它使用融合位置(LocationClient)每5秒确定用户的位置,并将此数据发送到我的服务器。当应用程序运行时,整个过程每5秒重复一次。我正在使用AsyncTask类在后台上传数据。

  • 问题:

    当用户关闭应用或手机进入睡眠状态时,数据上传会停止。

  • 我想要的是什么:

    即使用户关闭应用程序或手机处于睡眠状态,我希望应用程序不断向我的服务器发送位置数据。这个过程应该在一个单独的线程上运行,因为我不希望这个过程让我的UI线程没有响应。

  • 到目前为止我发现的事情:

    我听说过服务,intentservices和alarmmanager但我不知道使用哪一个。我也听说过唤醒锁,迫使CPU不要睡觉。请记住,我不想一直打开屏幕,因为这会耗尽电池。

如何让我的应用始终将数据发送到服务器?

2 个答案:

答案 0 :(得分:5)

在这里,您可以创建一个Service并根据需要每隔5/10秒使用AlarmManager调用此服务... 在MainActivity

public static AlarmManager alarm;
    public static PendingIntent pintent;

  // write this code on button click

            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, 10);

            Intent intent = new Intent(this, MyService.class);


            pintent = PendingIntent.getService(this, 0, intent, 0);


            alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 5000, pintent);

 // button click functionality over


    // write this code outside onCreate()
    protected ServiceConnection mConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                // TODO Auto-generated method stub

            }
        };

为MyService

public class MyService extends Service {
    public static int counter = 0;


    public MyService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        return new  Binder() ;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, "First Service was Created", Toast.LENGTH_SHORT).show();
       }

    @Override
    public void onStart(Intent intent, int startId) {

        counter++;
        Toast.makeText(this, " First Service Started" + "  " + counter,               Toast.LENGTH_SHORT).show();



    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
        }

    public void onTaskRemoved (Intent rootIntent){

        MainActivity.alarm.cancel(MainActivity.pintent);
        this.stopSelf();
       }

将此添加到

清单

 <application
        ....
        <activity
         .....
          </activity>
     <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" >
        </service>
      </application>

答案 1 :(得分:0)

您可以创建由您的应用程序发布的服务。它将在后台运行,并继续工作,直到用户从任务管理器关闭它(如果你没有在代码中调用onDestroy)。