答案 0 :(得分:0)
要定期更新/监控/无论如何,您需要从您的应用启动服务。这是一个简短的解释:
这是漫长而详细的:
http://developer.android.com/guide/components/services.html
您可能需要前台服务,但粘性也可能有效,具体取决于具体要求。这里有一些基本的代码(与第一个链接中描述的方式略有不同,但是相同的一般概念):
在AndroidManifest.xml中声明您的服务:
<service android:name="Foo"/>
扩展服务类
public class FooService extends Service {
..........
@Override
public void onCreate() {
//if you want this service to run in the foreground so it doesn't get
//killed by the system, create a notification, and call this
startForeground(id, notification); //look at the Service API
//start your periodic monitoring thread
................
}
@Override
public void onDestroy() {
//do the cleanup here
................
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//whatever you need to do when the app calls the start command,
//which may happen multiple times, goes here
...............
//this makes sure the process is sticky (see links above for details
return START_STICKY;
}
..........
}
在您的主要活动的onCreate方法中,执行以下操作:
Context context = getApplicationContext();
Intent i= new Intent(context, FooService.class);
i.putExtra(whetever you want to pass to the service)
context.startService(i);
context.bindService(i, connection, 0); //read the API