安卓 service 后台运行,activity 启动和停止service

安卓activity界面,上面有两个按钮,一个是开始服务,一个是取消服务。

界面布局:

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:paddingBottom="@dimen/activity_vertical_margin"
 6     android:paddingLeft="@dimen/activity_horizontal_margin"
 7     android:paddingRight="@dimen/activity_horizontal_margin"
 8     android:paddingTop="@dimen/activity_vertical_margin"
 9     tools:context=".MainActivity" >
10
11     <TextView
12         android:id="@+id/textView1"
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
15         android:text="@string/hello_world" />
16
17
18     <Button
19         android:id="@+id/quxiao"
20         android:layout_width="wrap_content"
21         android:layout_height="wrap_content"
22         android:layout_below="@+id/textView1"
23         android:layout_marginTop="65dp"
24         android:text="取消服务" />
25
26     <Button
27         android:id="@+id/bangding"
28         android:layout_width="wrap_content"
29         android:layout_height="wrap_content"
30         android:layout_alignBaseline="@+id/quxiao"
31         android:layout_alignBottom="@+id/quxiao"
32         android:layout_alignParentRight="true"
33         android:layout_marginRight="66dp"
34         android:text="开始服务" />
35
36 </RelativeLayout>

activity的代码:

 1 package com.example.test2;
 2
 3 import java.util.Date;
 4
 5 import com.example.application.GlobalVaries;
 6
 7 import android.os.Bundle;
 8 import android.os.Handler;
 9 import android.os.IBinder;
10 import android.app.Activity;
11 import android.content.ComponentName;
12 import android.content.Intent;
13 import android.content.ServiceConnection;
14 import android.view.View;
15 import android.view.View.OnClickListener;
16 import android.widget.Button;
17 import android.widget.TextView;
18 import android.widget.Toast;
19
20 public class MainActivity extends Activity {
21     private boolean isBound = false;
22     TextView labelView;
23     private Intent serviceIntent;
24     private GlobalVaries global;
25
26     @Override
27     protected void onCreate(Bundle savedInstanceState) {
28         super.onCreate(savedInstanceState);
29         setContentView(R.layout.activity_main);
30         global = (GlobalVaries) getApplication();
31         labelView = (TextView) findViewById(R.id.textView1);
32         Button bindButton = (Button) findViewById(R.id.bangding);
33         Button unbindButton = (Button) findViewById(R.id.quxiao);
34
35         myMainRunning();
36         // 绑定按钮
37         bindButton.setOnClickListener(new OnClickListener() {
38             @Override
39             public void onClick(View v) {
40                 if (!isBound) {
41                     serviceIntent = new Intent(MainActivity.this,
42                             MyService.class);
43                     MainActivity.this.startService(serviceIntent);
44                     isBound = true;
45
46                 }
47             }
48         });
49         // 取消绑定按钮
50         unbindButton.setOnClickListener(new View.OnClickListener() {
51             @Override
52             public void onClick(View v) {
53                 onDestroy();
54                 System.exit(0);
55                 finish();
56             }
57         });
58
59     }
60
61     private void myMainRunning() {
62         final Handler handler = new Handler();
63         Runnable runnable = new Runnable(){
64              @Override
65              public void run() {
66                  // 在此处添加执行的代码
67
68                  long nowTime = global.getNowTime();
69                  labelView.setText(""+new Date(nowTime));
70                  handler.postDelayed(this, 500);// 50是延时时长
71              }
72          };
73          handler.postDelayed(runnable, 1000);// 打开定时器,执行操作
74          handler.removeCallbacksAndMessages(this);// 关闭定时器处理
75     }
76
77     @Override
78     protected void onDestroy() {
79         MainActivity.this.stopService(serviceIntent);
80         super.onDestroy();
81     }
82
83
84 }

服务部分的代码:

 1 package com.example.test2;
 2
 3 import java.util.Date;
 4
 5 import com.example.application.GlobalVaries;
 6
 7 import android.app.Service;
 8 import android.content.Intent;
 9 import android.os.Handler;
10 import android.os.IBinder;
11 import android.util.Log;
12 import android.widget.Toast;
13
14 public class MyService extends Service {
15
16     private GlobalVaries global;
17
18     @Override
19     public void onCreate() {
20         Log.i("start", "MyService onCreate");
21         global = (GlobalVaries) getApplication();
22         myrunningProgram();
23         super.onCreate();
24     }
25
26     private void myrunningProgram() {
27         final Handler handler = new Handler();
28             Runnable runnable = new Runnable(){
29                  @Override
30                  public void run() {
31                      // 在此处添加执行的代码
32                      Toast.makeText(MyService.this, ""+new Date(),
33                              Toast.LENGTH_SHORT).show();
34                      global.setNowTime(System.currentTimeMillis());
35                      handler.postDelayed(this, 2000);// 50是延时时长
36                  }
37              };
38              handler.postDelayed(runnable, 1000);// 打开定时器,执行操作
39              handler.removeCallbacksAndMessages(this);// 关闭定时器处理
40
41     }
42
43     //开启绑定
44     @Override
45     public IBinder onBind(Intent arg0) {
46         //为了使Service支持绑定,需要在Service类中重载onBind()方法,并在onBind()方法中返回Service对象
47         Toast.makeText(this, "本地绑定:MyService",
48                 Toast.LENGTH_SHORT).show();
49         System.out.println("----2");
50
51         return null;
52     }
53
54     //取消绑定
55     @Override
56     public boolean onUnbind(Intent intent) {
57         Toast.makeText(this, "取消本地绑定:MyService",
58                              Toast.LENGTH_SHORT).show();
59         System.out.println("----3");
60         return false;
61     }
62
63
64 }

根据需求可以修改相应部分的代码。以上代码就是为了实现自己的需求。

时间: 2024-08-29 19:30:31

安卓 service 后台运行,activity 启动和停止service的相关文章

如何把apache和nginx 加入到系统服务,用service 命令来控制启动、停止

1 把apache 加入到系统服务,即用service 命令来控制Apache 启动.停止 如果Linux服务器上默认安装了httpd的话(用rpm -qa|grep httpd查看),那你就可以用编译生成的来覆盖到 /etc/init.d/httpd 如果没有安装的话,那么就下面的方法 # grep -v "#"  /usr/local/apache2/bin/apachectl  >/etc/init.d/httpd 然后用vi编辑Apache服务控制脚本/etc/init.

Android学习小记-----监听并保存传感器数据,让service后台运行(保持CPU运转

最近做了一个Demo,监听手机中传感器的数据,并将数据保存到手机文件中,发现数据会有丢失的现象. 经过多次测试,发现系统进入深度休眠了,之后service会停止,虽然增加了service自动启动的功能,但是还会导致数据中断一段时间.如果屏幕一直亮着会比较耗电,所以亮屏这种方法直接Pass掉.那么怎么保证service一直运行不会中断呢? 1,PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);通过Con

安卓开机启动service后台运行

Android开机启动时会发送一个广播android.intent.action.BOOT_COMPLETED,捕捉到这个广播,然后可以进行相应的操作,比如:通过捕捉开机广播启动Activity,或者Service. 1.新建BootBroadcastReceiver类,继承BroadcastReceiver. public class BootBroadcastReceiver extends BroadcastReceiver { private final String ACTION_BO

PYTHON的程序在LINUX后台运行

1.nohup 命令 nohup nohup 命令 用途:LINUX命令用法,不挂断地运行命令. 语法:nohup Command [ Arg ... ] [ & ] 描述:nohup 命令运行由 Command 参数和任何相关的 Arg 参数指定的命令,忽略所有挂断(SIGHUP)信号.在注销后使用 nohup 命令运行后台中的程序.要运行后台中的 nohup 命令,添加 & ( 表示“and”的符号)到命令的尾部. 如果不将 nohup 命令的输出重定向,输出将附加到当前目录的 noh

mongodb后台运行

默认的情况下,关闭shell,mongodb就停止运行了. 如果想在后台运行,启动时只需添加 --fork函数即可. 可以在日志路径后面添加--logappend,防止日志被删除. bin/mongodb  --fork --dbpath=//  --logpath=//  --logappend 在后台运行,如果想要关闭它的话,需要给他发送shutdownServer() 1.普通命令: $ ./mongod > use admin > db.shutdownServer() 要注意的是,这

php后台运行以及定时任务的4种实现原理以及代码

后台任务在我们php编程中虽然用的不是很多甚至很多php程序员都没听过甚至觉得后台运行是不可能实现的,本人因为项目需求多次演变在这里分享给大家,本人第一次想实现后台运行是利用 方法二 在其执行完成后输出一段Js代码让页面再次执行,然后在服务器中打开该页面!以下实现方式除了方法一我不推荐使用外其他我在项目中都使用过! 方法一.php自带函数实现后台运行(不推荐使用,不太稳定而且弊端很多)set_time_limit  允许运行的最长时间,0表示不限制sleep 运行后延时多久在运行后面的代码 当我

Android 启动后台运行程序(Service)

Android开发中,当需要创建在后台运行的程序的时候,就要使用到Service.Service 可以分为有无限生命和有限生命两种.特别需要注意的是Service跟Activities是不同的(简单来说可以理解为后台与前台的区别),例如,如果需要使用Service的话,需要调用startService(),从而利用startService()去调用Service中的OnCreate()和onStart()方法来启动一个后台的Service.      启动一个Service的过程如下:conte

redis 启动和停止和后台运行

启动: 当安装好redis之后,运行redis-server命令之后,显示如图所示: 但是这样没有办法在这个tab下做任何操作了,如果这个时候使用Ctrl+c之后,就直接退出了 那么我想让redis在后台启动怎么办呢? 可以通过配置文件的方式启动,并在配置文件中设置后台运行 把daemonize设置为yes 然后运行以下命令即可在后台启动 redis redis-server 配置文件路径 停止 redis-cli -a 密码  -h 127.0.0.1 -p 6379 shutdown 没有密

【安卓面试题】在一个Activity启动另一个Activity和在Service中启动一个Activity有什么区别

在Activity中可以直接使用Intent启动另一个Activity 显式Intent intent = new Intent(context, activity.class) 隐式 Intent intent = new Intent(“com.aa.www.act”); startActivity(intent); 如果从Service中用同样方法启动Activity 的话,会报错: android.util.AndroidRuntimeException: Calling startAc