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

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android: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; @Override
public 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 {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(ServiceMainActivity.this, LocalService.class);
switch (v.getId()) {
case R.id.start:
// 启动Service
startService(intent);
toast("startService");
break;
case R.id.stop:
// 停止Service
stopService(intent);
toast("stopService");
break;
case R.id.bind:
// 绑定Service
bindService(intent, conn, Service.BIND_AUTO_CREATE);
toast("bindService");
break;
case R.id.unbind:
// 解除Service
unbindService(conn);
toast("unbindService");
break;
}
}
} private void toast(final String tip){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT).show();
}
});
}
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e(TAG, "连接成功");
// 当Service连接建立成功后,提供给客户端与Service交互的对象(根据Android Doc翻译的,不知道准确否。。。。)
myService = ((LocalService.LocalBinder) service).getService();
} @Override
public 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(); @Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind()");
//Toast.makeText(this, "onBind()", Toast.LENGTH_SHORT).show();
return myBinder;
} // 调用startService方法或者bindService方法时创建Service时(当前Service未创建)调用该方法
@Override
public void onCreate() {
Log.e(TAG, "onCreate()");
//Toast.makeText(this, "onCreate()", Toast.LENGTH_SHORT).show();
} // 调用startService方法启动Service时调用该方法
@Override
public void onStart(Intent intent, int startId) {
Log.e(TAG, "onStart()");
//Toast.makeText(this, "onStart()", Toast.LENGTH_SHORT).show();
} // Service创建并启动后在调用stopService方法或unbindService方法时调用该方法
@Override
public 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

Android中Service的一个Demo例子的更多相关文章

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

    Android中Service的使用详解和注意点(LocalService) 原文地址 开始,先稍稍讲一点android中Service的概念和用途吧~ Service分为本地服务(LocalServ ...

  2. Android中Service(服务)详解

    http://blog.csdn.net/ryantang03/article/details/7770939 Android中Service(服务)详解 标签: serviceandroidappl ...

  3. 在Android中动画移动一个View的位置,采用Scroller类实现Android动画之 View移动

    在Android中动画移动一个View的位置,采用Scroller类实现 今天说最近自己遇到的一个问题,就是要用动画效果来移动一个VIew的位置. 这个具体的情况是,需要做一个SlidingMenu的 ...

  4. Angular2 不明真相第一个Demo例子

    如果不是去年换工作接触到AngularJS,估计是不会花时间去学习这个框架的,毕竟是前端的框架,不是自己熟悉的领域.但是为了混得下去,去年就学习了AngularJS的一些用法,当时还整理了一些积累 & ...

  5. android中service启动后台程序

    Service是Android中一个类,它是Android四大组件之一,使用Service可以在后台执行长时间的操作( perform long-running operations in the b ...

  6. Android中如何搭建一个WebServer

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

  7. Android中Service和Activity之间的通信

    启动Service并传递数据进去: Android中通过Intent来启动服务会传递一个Intent过去. 可以在Intent中通过putExtra()携带数据 Intent startIntent ...

  8. Android中Service 使用详解(LocalService + RemoteService)

    Service 简介: Service分为本地服务(LocalService)和远程服务(RemoteService): 1.本地服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外L ...

  9. Android中Service的使用

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

随机推荐

  1. Unity3d 开发(七)AssetBundle组织文件夹

    本文探讨怎样配置一个AssetBundle更为合理. 对于结构为 的文件夹结构,当中shared是Hero文件夹下须要用到的公用资源.即公有依赖.可採用例如以下的打包策略 整个文件夹打包 将整个100 ...

  2. SQLSever: 怎样在select中的每一行产生不同的随机数?

    select 的随机函数有点假, 或许是由于它是基于时间来的吧, 同一select中由于时间无法错开导致产生的随机数都是一样的. 怎样做到让不同的行拥有不同的随机数呢? 以下以产生某个月的随机日期来演 ...

  3. ACdream 1139(Sum-逆元)

    J - Sum Time Limit: 2000/1000MS (Java/Others) Memory Limit: 128000/64000KB (Java/Others) SubmitStatu ...

  4. maven3+eclipse搭建webAPP企业级实战《一》

    想做企业级web系统:环境搭建不可缺少GO 1:新建 2:next : 3:选择webAPP next: 填完finish 初始项目结构: watermark/2/text/aHR0cDovL2Jsb ...

  5. 机器学习规则:ML工程最佳实践----rules_of_ml section 1【翻译】

    作者:黄永刚 机器学习规则:ML工程最佳实践 本文旨在指引具有机器学习基础知识的工程师等人,更好的从机器学习的实践中收益.介绍一些应用机器学习需要遵循的规则,类似于Google C++ 风格指南等流行 ...

  6. B-Boxes

    http://agc010.contest.atcoder.jp/tasks/agc010_b Problem Statement There are N boxes arranged in a ci ...

  7. Linux Putty 复制粘贴

    从putty复制:    用左键选中文字,再其他地方点中键就可以粘贴了,不需要右键粘贴. 在putty中粘贴:    在其他地方用左键选中文字,不用右键复制,保持选中文字高亮,然后在putty中点中键 ...

  8. Windows下使用VS的ADO访问MySQL

    数据库的访问的一种方式就是:CS结构.即使用TCP/UDP协议进行远程访问,而数据库对于服务端的软件是本地访问!这种管理方式比较常见. 这里主要叙述Windows访问本地数据库的方法. 需要了解几个概 ...

  9. 洛谷 P2015 二叉苹果树 && caioj1107 树形动态规划(TreeDP)2:二叉苹果树

    这道题一开始是按照caioj上面的方法写的 (1)存储二叉树用结构体,记录左儿子和右儿子 (2)把边上的权值转化到点上,离根远的点上 (3)用记忆化搜索,枚举左右节点分别有多少个点,去递归 这种写法有 ...

  10. js 异步加载的方式

    js 异步加载的方式 渲染引擎遇到 script 标签会停下来,等到执行完脚本,继续向下渲染 defer 是“渲染完再执行”,async 是“下载完就执行”,defer 如果有多个脚本,会按照在页面中 ...