Broadcast与service----------通过广播启动服务

来源:互联网 发布:开淘宝网店押金多少钱 编辑:程序博客网 时间:2024/05/22 13:18

      

      BroadcastReceiverd的流程:注册、发送广播。

      Service的流程:注册、启动、停止。

      上一篇已经讲了,注册广播有两种方式,静态的和动态的。今天我用动态的方式注册一个广播,通过广播来启动服务。

大致过程为:定义三个按钮:发送、取消、退出。点击发送按钮时,注册广播、在广播的onReceive()方法中启动服务。

点击取消,停止服务。点击退出,停止服务退出系统。

这需要三个类:TestActivity.java、TestService.java、TestBroadcast.java。还需要在AndroidManifest.xml文件中注册广播。

 

AndroidManifest.xml文件:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.litsoft.mp3"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="8" />    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:name="com.litsoft.test.TestActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                <!-- android:name="com.litsoft.activity.ListActivity" -->        <!-- android:name="com.litsoft.test.TestBroad_Service"-->                        <!-- 测试用的 -->        <service android:name="com.litsoft.test.TestService" >            <intent-filter >                <action android:name="com.litsoft.testService"/>            </intent-filter>        </service>               <!--  <receiver android:name="com.litsoft.test.TestBroad_Service.TestBroadcast">            <intent-filter >                <actionandroid:name="com.litsoft.testBroad"/>            </intent-filter>        </receiver> -->            </application></manifest>

TestService.java

package com.litsoft.test;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.widget.Toast;public class TestService extends Service{@Overridepublic IBinder onBind(Intent intent) {System.out.println("onBind-------->");Toast.makeText(this, "OnBind(", Toast.LENGTH_SHORT).show();return null;}/** * 如果是第一次调用只执行一次 */@Overridepublic void onCreate() {super.onCreate();System.out.println("oncreat-------->");Toast.makeText(this, "OnCreate(", Toast.LENGTH_SHORT).show();}/** * Activity中启用一个Service是调用它的startService(Intent)方法 ,当调用该方法时, * Service中的onCreate()(如果是第一次调用,只执行一次)onStart()方法被调用。 */@Overridepublic void onStart(Intent intent, int startId) {super.onStart(intent, startId);/*String msg1 = intent.getStringExtra("msg1");System.out.println(msg1);*/System.out.println("onStart-------->");Toast.makeText(this, "OnStart(", Toast.LENGTH_SHORT).show();}/** * 停止一个Service是调用stopService(Intent)方法, * 当调用该方法时,Service中的onDestory()方法被调用。 */@Overridepublic void onDestroy() {super.onDestroy();System.out.println("onDesttroy-------->");Toast.makeText(this, "OnDestroy(", Toast.LENGTH_SHORT).show();}}


TestBroadcast.java

package com.litsoft.test;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class TestBroadcast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Toast.makeText(context, "广播我已经启动服务了", Toast.LENGTH_SHORT).show();System.out.println("广播我已经启动服务了");Intent service = new Intent(context,TestService.class);service.setAction(TestActivity.ACTION_Service);//在广播中启动服务必须加上startService(intent)的修饰语。Context是对象context.startService(service);}}


TestActivity.java

package com.litsoft.test;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;import com.litsoft.mp3.R;/** * 测试通过  广播  向    服务 发送一条消息、取消 ,服务效应广播事件 *  * @author maxiaopei * */public class TestActivity extends Activity{private Button send;private Button cancle;private Button exit;public static final String ACTION_Broad = "com.litsoft.testBroad";public static final String ACTION_Service = "com.litsoft.testService";//不能把它写在发送按钮的事件监听器中,否则每点击一次,就创建一个对象,就多了一个对象的响应。private TestBroadcast myReceiver=new TestBroadcast();@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.test);send = (Button) findViewById(R.id.send);cancle = (Button) findViewById(R.id.cancle);exit = (Button) findViewById(R.id.exit);send.setOnClickListener(new OnClickListener() {@Override// 启动广播,广播向服务发消息,服务把消息发到控制台public void onClick(View v) {System.out.println("发送");/*//通过广播启动服务// 注册广播IntentFilter fliter = new IntentFilter();fliter.addAction(ACTION_Broad);registerReceiver(myReceiver, fliter);//发送广播Intent intent = new Intent();intent.setAction(ACTION_Broad);sendBroadcast(intent);*///亲自启动服务//intent的写法有两种,一种是带参,一种是不带参,只要设置Action就行//Intent intent = new Intent();Intent intent = new Intent(TestActivity.this, TestService.class);intent.setAction(ACTION_Service);startService(intent);}});cancle.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {System.out.println("取消");//intent的写法有两种,一种是带参,一种是不带参,只要设置Action就行//Intent intent = new Intent();Intent intent = new Intent(TestActivity.this, TestService.class);intent.setAction(ACTION_Service);stopService(intent);//千万不能写这句话,否则会出现异常:java.lang.IllegalArgumentException: Receiver not registered//因为广播的生命周期值限于执行完自己的onRexeiver()方法,之后他就被kill掉了。//这时再调用下面的方法就会出现上面的异常。//不过如果是在activity中的onResume()方法注册的广播,就必须在activity的onPause()方法中取消注册广播//这是从系统资源的情况考虑的。//unregisterReceiver(myReceiver);}});exit.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {//如果服务没有停止,服务会一致存在。所以为了保证服务停止,先stop一下。Intent intent = new Intent(TestActivity.this, TestService.class);intent.setAction(ACTION_Service);stopService(intent);finish();}});}}


程序运行结果如下:

点击发送按钮结果:

 

点击取消按钮结果:

点击一次发送按钮一次取消按钮控制台结果:

点击两次发送按钮一次取消按钮控制台结果:

总结,在测试广播与服务时遇到了很多问题,原因都是自己没有掌握好。上面代码有很多注视,大家可以好好看下,测试下。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

原创粉丝点击