我正在为我的高中最终安卓项目做一个简单的宏安卓应用程序,我想让一个后台进程,每隔一定的时间运行(由用户决定),以更新当前位置和其他一些事情作为条件来启动他们选择的行动,降低亮度或更改智能手机到静音模式或其他一些action....how,以使该进程(或服务),请记住,我是完全初学者(我甚至不知道进程或服务之间的区别)。所以,如果可以的话,请用示例代码来回答。谢谢!:D
发布于 2014-05-25 04:48:53
要执行定期更新/监控/其他操作,您需要从应用程序启动一个服务。这里有一个简短的解释:
http://www.basic4ppc.com/android/forum/threads/creating-a-sticky-service-long-running-background-tasks.27065/
下面是详细的长篇文章:
http://developer.android.com/guide/components/services.html
您可能需要前台服务,但sticky也可以工作,这取决于特定的要求。以下是一些基本代码(与第一个链接中描述的方式略有不同,但大体相同):
在AndroidManifest.xml中声明您的服务:
<service android:name="Foo"/>扩展Service类
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 APIhttps://stackoverflow.com/questions/23847474
复制相似问题