Android中Service的一个Demo例子
  Service组件是Android系统重要的一部分,网上看了代码,很简单,但要想熟练使用还是需要Coding。
  本文,主要贴代码,不对Service做过多讲解。
  代码是从网上找的一个例子,Copy下来发现代码不完全正确,稍微修改了下。
  AndroidManifest.xml

<applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name" ><activityandroid:label="@string/app_name"android:name=".service.ServiceMainActivity" ><intent-filter ><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><!-- 注册Service -->  <service android:name="LocalService">  <intent-filter>  <action android:name="cn.fansunion.service.LocalService" />  </intent-filter>  </service>  </application>

ServiceMainActivity.java

package cn.fansunion.service;import cn.fansunion.R;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;public class ServiceMainActivity extends Activity {private Button startBtn;private Button stopBtn;private Button bindBtn;private Button unBindBtn;private static final String TAG = "MainActivity";private LocalService myService;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.service);startBtn = (Button) findViewById(R.id.start);stopBtn = (Button) findViewById(R.id.stop);bindBtn = (Button) findViewById(R.id.bind);unBindBtn = (Button) findViewById(R.id.unbind);startBtn.setOnClickListener(new MyOnClickListener());stopBtn.setOnClickListener(new MyOnClickListener());bindBtn.setOnClickListener(new MyOnClickListener());unBindBtn.setOnClickListener(new MyOnClickListener());}class MyOnClickListener implements OnClickListener {@Overridepublic void onClick(View v) {Intent intent = new Intent();intent.setClass(ServiceMainActivity.this, LocalService.class);switch (v.getId()) {case R.id.start:                       // 启动ServicestartService(intent);toast("startService");break;case R.id.stop:// 停止ServicestopService(intent);toast("stopService");break;case R.id.bind:// 绑定ServicebindService(intent, conn, Service.BIND_AUTO_CREATE);toast("bindService");break;case R.id.unbind:// 解除ServiceunbindService(conn);toast("unbindService");break;}}}private void toast(final String tip){runOnUiThread(new Runnable() {                    @Overridepublic void run() {Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT).show();                         }});}private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {Log.e(TAG, "连接成功");// 当Service连接建立成功后,提供给客户端与Service交互的对象(根据Android Doc翻译的,不知道准确否。。。。)myService = ((LocalService.LocalBinder) service).getService();}@Overridepublic void onServiceDisconnected(ComponentName name) {Log.e(TAG, "断开连接");myService = null;}};
}

LocalService.java

package cn.fansunion.service;import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;public class LocalService extends Service {private static final String TAG = "MyService";private final IBinder myBinder = new LocalBinder();@Overridepublic IBinder onBind(Intent intent) {Log.e(TAG, "onBind()");//Toast.makeText(this, "onBind()", Toast.LENGTH_SHORT).show();return myBinder;}// 调用startService方法或者bindService方法时创建Service时(当前Service未创建)调用该方法@Overridepublic void onCreate() {Log.e(TAG, "onCreate()");//Toast.makeText(this, "onCreate()", Toast.LENGTH_SHORT).show();}// 调用startService方法启动Service时调用该方法@Overridepublic void onStart(Intent intent, int startId) {Log.e(TAG, "onStart()");     //Toast.makeText(this, "onStart()", Toast.LENGTH_SHORT).show();}// Service创建并启动后在调用stopService方法或unbindService方法时调用该方法@Overridepublic void onDestroy() {Log.e(TAG, "onDestroy()");//Toast.makeText(this, "onDestroy()", Toast.LENGTH_SHORT).show();}//提供给客户端访问public class LocalBinder extends Binder {LocalService getService() {return LocalService.this;}}
}

service.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><Button android:id="@+id/start" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="启动Service" /><Button android:id="@+id/stop" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="停止Service" /><Button android:id="@+id/bind" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="绑定Service" /><Button android:id="@+id/unbind" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="解除Service" />
</LinearLayout>

[2015-11-14 17:39:10 - xp2p4android] ------------------------------
[2015-11-14 17:39:10 - xp2p4android] Android Launch!
[2015-11-14 17:39:10 - xp2p4android] adb is running normally.
[2015-11-14 17:39:10 - xp2p4android] Performing cn.fansunion.service.ServiceMainActivity activity launch
[2015-11-14 17:39:10 - xp2p4android] Automatic Target Mode: using device '51bf63f2'
[2015-11-14 17:39:10 - xp2p4android] Uploading xp2p4android.apk onto device '51bf63f2'
[2015-11-14 17:39:10 - xp2p4android] Installing xp2p4android.apk...
[2015-11-14 17:39:13 - xp2p4android] Success!
[2015-11-14 17:39:13 - xp2p4android] Starting activity cn.fansunion.service.ServiceMainActivity on device 51bf63f2
[2015-11-14 17:39:13 - xp2p4android] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=cn.fansunion/.service.ServiceMainActivity }
[2015-11-14 17:39:13 - xp2p4android] Attempting to connect debugger to 'cn.fansunion' on port 8600

运行效果图

原来的代码,Toast对话框没有展示出来。
在CSDN论坛找到一个贴子说,可能是被手机屏蔽了。
我倒是觉得更有可能调用的方式不对。
Service中调用,Toast合适么?
public void onCreate() {
Log.e(TAG, "onCreate()");
//Toast.makeText(this, "onCreate()", Toast.LENGTH_SHORT).show();
}

最后参考网友的办法,在UI线程,新建线程执行Toast。
private void toast(final String tip){
runOnUiThread(new Runnable() {
            @Override
            public void run() {
            Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT).show();                         
            }
        });
}
不错,是在Activity中调用的。

这充分说明,网上代码再漂亮,还是得动手运行下。
代码的那个贴子,是2011年了,好古老啊~

参考资料
Android中Service组件详解
http://blog.csdn.net/zuolongsnail/article/details/6427037

Android Toast显示不出来
http://bbs.csdn.net/topics/390889540

转载于:https://www.cnblogs.com/qitian1/p/6462592.html

Android中Service的一个Demo例子相关推荐

  1. Android中Service的使用详解和注意点(LocalService)

    开始,先稍稍讲一点android中Service的概念和用途吧~ Service分为本地服务(LocalService)和远程服务(RemoteService): 1.本地服务依附在主进程上而不是独立 ...

  2. android小球移动代码,Android中如何绘制一个跟随手指移动的小球

    Android中如何绘制一个跟随手指移动的小球 发布时间:2020-11-07 16:22:43 来源:亿速云 阅读:82 作者:Leah 本篇文章为大家展示了Android中如何绘制一个跟随手指移动 ...

  3. Android中service应用

    Android开发中,当需要创建在后台运行的程序的时候,就要使用到Service.Service 可以分为有无限生命和有限生命两种.特别需要注意的是Service跟Activities是不同的(简单来 ...

  4. Android中如何搭建一个WebServer

    今天终于把老大交代的任务搞完了,感觉收获挺多的,所以就写一篇来记录一下吧,首先还是来看一下,老大们的需求 需求: 希望移动端的用户标识(IMEI)和HTML页面的用户标识(Cookie)连接起来,其中 ...

  5. 知识点干货--聊一聊Android中Service与Thread的区别

    古语说得好:"一寸光阴一寸金,寸金难买寸光阴."一寸光阴和一寸长的黄金一样昂贵,而一寸长的黄金却难以买到一寸光阴.比喻时间十分宝贵.此语句出自唐朝王贞白的<白鹿洞二首> ...

  6. Android中Service深入学习

    概述 1.当用户在与当前应用程序不同的应用程序时,Service可以继续在后台运行. 2.Service可以让其他组件绑定,以便和它交互并进行进程间通信. 3.Service默认运行在创建它的应用程序 ...

  7. 关于Android中Service的手动、自动以及其在特殊条件下的重启

    上一篇博客有说到Service之间的守护问题. 博客地址:http://blog.csdn.net/lemon_tree12138/article/details/40322887 接着这个Sevic ...

  8. Android中Service的使用

    我个人的理解是:我们平时使用的android系统的app的后台应用,就是这个原理 可以利用Service实现程序在后台运行,依照这个原理,可以通过Service来实现关键代码的运行与实现. <一 ...

  9. Android SqlDelight详解和Demo例子

    一.简介 SQLDelight 和 SqlBrite 是 Square 公司推出的一个 Android 平台数据库解决方案. 在了解这个两个东西前,必须先得有Andorid的Sqlite的知识(Sql ...

  10. android中Service使用startService

    一.什么是Service?   Service(服务)是一个一种可以在后台执行长时间运行操作而没有用户界面的应用组件.服务可由其他应用组件启动(如Activity),服务一旦被启动将在后台一直运行,即 ...

最新文章

  1. WCF访问iis元数据库失败--解决方法
  2. paragraph设置行距_LaTex学术写作——设置段落 行间距 段间距 文本对齐方式
  3. Spring Boot Starters启动器
  4. python正则判断列表是否有元素,python – 从列表中删除正则表达式元素
  5. 在64位Win7系统中配置jsp开发环境以及一些问题解决方案
  6. vuex 源码分析_前端入门之(vuex-router-sync解析)
  7. Java是有法_Java基础语法
  8. Solaris 10 ftp,telnet,ssh,sendmail
  9. APICloud学习笔记之div样式设置套路
  10. OpenCV笔记(十八)——使用霍夫变换检测圆圈
  11. python中await async_asyncio中的async和await
  12. 图形验证码识别接口(免费)
  13. kpi绩效考核流程图_绩效考核流程图
  14. Permission denied: user=administrator, access=WRITE 问题解决
  15. openlayers给要素加文字注记
  16. 机试算法讲解:第26题 分解素因数
  17. 维度灾难 维数灾难 暂记
  18. P4084 [USACO17DEC]Barn Painting
  19. win7原版镜像_AMD平台B450主板安装WIN7教程
  20. Reactive的方式访问Redis

热门文章

  1. 复盘人生第一次科研经历
  2. pytorch 实现半圆数据分类
  3. python库批量安装的方法
  4. Java网络编程之流的详解
  5. 最小生成树-Prim算法的Python实现
  6. 应用系统接入接口开发
  7. MYOP究竟能为站长提供哪些便利
  8. 3分钟tips:Python中的range与xrange
  9. 无法添加外键约束的原因(cannot add foreign key constraint)
  10. Pytorch基本操作