安卓控件——定时广播案例
Posted a Fang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓控件——定时广播案例相关的知识,希望对你有一定的参考价值。
安卓控件——广播
其实在我们的安卓系统中有好多的地方都应用到了广播的部分:比如当我们手机电量很低的时候,手机就会发一个广播,告知用户,作出相应的操作。
1.项目布局:
7个button,俩text;
2.布局文件:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:outlineAmbientShadowColor="@android:color/holo_blue_bright">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:text="Handler方式定时发送广播" />
<Button
android:id="@+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="176dp"
android:text="取消发送广播" />
<Button
android:id="@+id/button7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button5"
android:layout_alignLeft="@+id/button5"
android:layout_marginBottom="46dp"
android:text="AlarmManager方式定时发送广播 5秒后发送广播,只发送一次" />
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button5"
android:layout_below="@+id/button5"
android:text="Handler方式定时服务" />
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button3"
android:layout_below="@+id/button3"
android:text="AlarmManager方式定时服务" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/button7"
android:layout_alignLeft="@+id/button7"
android:text="AlarmManager方式定时发送广播 每隔5秒重复发广播" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_alignParentTop="true"
android:layout_marginTop="41dp"
android:text="敌军还有5秒到达战场,碾碎他们" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignParentTop="true"
android:text="敌军还有5秒到达战场,碾碎他们" />
<Button
android:id="@+id/button6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button4"
android:layout_below="@+id/button4"
android:text="取消定时服务" />
</RelativeLayout>
3.服务类:
TimerService.java:
package com.example.broadcast;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class TimerService extends Service
private String TAG =TimerService.class.getSimpleName();
String message;
int count=1;
public TimerService()
@Override
// 创建后台进程
public void onCreate()
super.onCreate();
// super.onDestroy();
// 调用发送函数
sentMassage();
// 销毁后台进程
public void onDestroy()
super.onDestroy();
count=1;
Log.i(TAG,"进程销毁咯!!");
//发送创建后机制的发送消息函数
@SuppressLint("WrongConstant")
private void sentMassage()
Toast.makeText(getApplicationContext(),"创建一个后台任务",0).show();
stopSelf();
// 接收消息
public String getMessage()
return message;
@Override
public IBinder onBind(Intent intent)
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return null;
4.服务工具类:
4.1 ServiceUtil.java:
package com.example.broadcast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.util.List;
public class ServiceUtil
private final static String ServiceName="com.example.broadcast.TimerService";
@SuppressLint("LongLogTag")
public static boolean isServiceRunning(Context context, String className)
boolean isRunning=false;
ActivityManager activityManager =(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo>serviceInfos=activityManager.getRunningServices(50);
if (null==serviceInfos||serviceInfos.size()<1)
return false;
for (int i=0;i<serviceInfos.size();i++)
if (serviceInfos.get(i).service.getClassName().contains(className))
isRunning=true;
break;
Log.i("ServiceUtil-AlarmManager", className + " isRunning = " + isRunning);
return isRunning;
;
@SuppressLint("LongLogTag")
public static void startAMService(Context context)
Log.i("ServiceUtil-AlarmManager", "invokeTimerPOIService wac called.." );
PendingIntent alarmSender =null;
Intent startIntent=new Intent(context,TimerService.class);
startIntent.setAction(ServiceName);
try
alarmSender=PendingIntent.getService(context,0,startIntent,0);
catch (Exception e)
// 异常捕获
// 闹钟异常启动
Log.i("ServiceUtil-AlarmManager", "failed to start " + e.toString());
@SuppressLint("ServiceCast") AlarmManager am =(AlarmManager) context.getSystemService(Activity.ACTIVITY_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),5*1000,alarmSender);
@SuppressLint("LongLogTag")
public static void cancleAMServicer(Context context)
// 关闭闹钟服务
Log.i("ServiceUtil-AlarmManager", "cancleAlarmManager to start ");
Intent intent =new Intent(context,TimerService.class);
intent.setAction(ServiceName);
PendingIntent pendingIntent=PendingIntent.getService(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm=(AlarmManager)context.getSystemService(Activity.ALARM_SERVICE);
alarm.cancel(pendingIntent);
// 服务启动
public static void startHandlerService(Context cxt)
Intent intent=new Intent(cxt,TimerService.class);
cxt.startService(intent);
// 服务关闭
// 服务启动
public static void stopHandlerService(Context cxt)
Intent intent=new Intent(cxt,TimerService.class);
cxt.stopService(intent);
4.2 实现广播和接收机制的五个步骤:
- 创建Intent对象,设置其属性action,这个属性是接收广播数据的标志标识,只有注册了相同的action属性的广播接收器才可以接收到相同的数据。
- 编写广播信息内容,将需要播发的内容封装到Intent里面,通过Activity或者是Service继承父类的Context的setContext()方式将广播发送出去;
- 编写继承BroadcastRecevier的子类作为广播接收器,该对象是接收广播信息并对信息进行处理的组件,在子类中重写Onrecieve()方法。
- 配置文件中注册广播接收类
- 销毁广播接收器:Android系统在执行onReceive()方法的时候会启动一个程序计时器,到一定的时间,该进程就会被销毁(所以广播机制不适合传递大数据量的信息)
5.主类:
5.1 MainActivity.java:
package com.example.broadcast;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
// private TimerService mTimerService;
private final String MESSAGE = "message";
private Context mContext;
private TextView tv, tv2;
private Button bt1, bt2, bt3, bt4, bt5, bt6,bt7;
private final int Time = 5 * 1000;
private boolean isHanderType = false;
private static final String ACTION_NAME = "android.intent.action.alarm.timer";
private static final String ACTION_NAME2 = "android.intent.action.handler.timer";
private int countHandler = 1;// handler广播发送次数计数器
private int countAlarm = 0;// alarm广播发送次数计数器
Handler handler = new Handler();
Runnable runnable = new Runnable()
@Override
// 设置广播发送
public void run()
// TODO Auto-generated method stub
//设置发布延时
handler.postDelayed(runnable, Time);
Intent mIntent = new Intent(ACTION_NAME2);
mIntent.putExtra(MESSAGE, "这是第" + countHandler + "次"
+ "Handler发送的广播, 接下来是第" + countHandler + "次");
sendBroadcast(mIntent);
;
Runnable runnable2 = new Runnable()
@Override
public void run()
// TODO Auto-generated method stub
Intent intent = new Intent(mContext, TimerService.class);
startService(intent);
handler.postDelayed(runnable2, Time);
;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver()
@Override
public void onReceive(Context context, Intent intent)
String action = intent.getAction();
String message = intent.getStringExtra(MESSAGE);
if (action.equals(ACTION_NAME))
tv.setText("第" + countAlarm + "发送"
以上是关于安卓控件——定时广播案例的主要内容,如果未能解决你的问题,请参考以下文章