Android service sample (2015.12.3)
来源:互联网 发布:js下拉框搜索功能 编辑:程序博客网 时间:2024/06/05 13:33
http://www.tutorialspoint.com/android/android_services.htm
1. 新建一个service文件:MyService.java
package com.example.helloworld;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.widget.Toast;public class MyService extends Service { @Overridepublic IBinder onBind(Intent arg0){return null;}@Override public int onStartCommand(Intent intent, int flags, int startId) {Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();return START_STICKY;}@Overridepublic void onDestroy() {super.onDestroy();Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();}}
2. 在Manifest.xml中声明:
<service android:name=".MyService" />
3. 修改界面文件:增加2个buttong, 来启动和停止 service
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/textView1" android:layout_marginTop="68dp" android:text="Start Service" <span style="color:#ff0000;">android:onClick="startService" /></span> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/button1" android:layout_below="@+id/button1" android:text="Stop Service" <span style="color:#ff0000;">android:onClick="stopService"/></span>
4. 在界面xml中调用的两个函数:定义在MainActivity.java中
//Method to start the service public void startService(View view) { startService(new Intent(getBaseContext(), MyService.class)); } public void stopService(View view) { stopService(new Intent(getBaseContext(), MyService.class)); }
编译,运行。
多体会下面的切换过程:
0 0
- Android service sample (2015.12.3)
- Android 学习笔记 Service (二) Remote Service Sample
- android broadcast receiver sample (2015.12.3)
- Local Service Sample & Remote Messenger Service Sample
- Android provider sample (2015.12.7)
- Simple Windows Service Sample
- Simple Windows Service Sample
- Indexing Service simple sample
- 【计划】Android Sample Codes
- Android导入sample项目
- Android Sample 之 BasicNetworking
- android SDK sample说明
- Android Sample 之 BasicNetworking
- android sample 之 其他
- Android Studio Import Sample
- Android WiFi Management Sample
- Android Google Sample
- Android Jni sample
- UILabel的换行问题
- WCF列子
- 销售发货自动批次
- 【Solutions系列】目标危险性分析
- android6.0源码编译及刷机
- Android service sample (2015.12.3)
- 代理模式Proxy
- ThinkPHP中的select()方法调用注意点
- 关于AlertDialog位置的问题
- 华为OJ基础篇-蛇形矩阵
- 干了十年对日外包的菜鸟的简单告白
- [hadoop2.7.1]I/O之序列化(serializer)
- 【Tech-IM】IM类型app开发浅谈(二)---聊天中的消息协议的定义与客户端数据库设计
- iOS TableView经常用得到