`
aliusa
  • 浏览: 84237 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Service Broadcast BroadcastReceiver AlarmManager,Notification利用service定时/周期性发送广播

阅读更多
1.如题








主要实现
1.启动service,关闭service;
2.activity 向service发送广播。
3.service向 activity发送广播。
4.service 利用AliarmMnager定时向activity push 数据,其实也是发了个广播。
5.service 利用AliarmMnager周期性的向 activity push 数据,其实也是发了个广播
6.定时/周期性向通知栏推送消息

1.Demo.java

package aliusa.cn;

import android.app.Activity;

/**
 * The Class Demo.
 * @author aliusa
 */
public class Demo extends Activity{
   
   TextView textView;
   
   Button[] btn;
   
   MyReceiver receiver = new MyReceiver();
   
   static final String ACTION = "aliusa.cn.Demo";
   String serviceState = "MyService is not Running.";
   String requireData = "The data is";
   
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setGravity(Gravity.CENTER);
        textView = new TextView(this);
        textView.setText(serviceState + requireData);
        layout.addView(textView);
        
        btn = new Button[6];
        btn[0] = new Button(this);
        btn[1] = new Button(this);
        btn[2] = new Button(this);
        btn[3] = new Button(this);
        btn[4] = new Button(this);
        btn[5] = new Button(this);
        
        btn[0].setText("StopService");
        btn[1].setText("BackGround");
        btn[2].setText("RequireData");
        btn[3].setText("StartService");
        btn[4].setText("RequireDataDelay 5s");
        btn[5].setText("RequireDataRepeating 5s");
        
        //1.activity communicate with service through broadcast
        btn[0].setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                stopService();
            }
        });

        btn[1].setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //2.activity communicate with service through service instance.
        btn[2].setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MyService.getInstance().pushDataImmediately();
            }
        });

        btn[3].setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startService();
            }
        });
        
        btn[4].setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MyService.getInstance().pushDataDelay();
            }
        });
        
        btn[5].setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MyService.getInstance().pushDataRepeating();
            }
        });
        
        layout.addView(btn[0]);
        layout.addView(btn[1]);
        layout.addView(btn[2]);
        layout.addView(btn[3]);
        layout.addView(btn[4]);
        layout.addView(btn[5]);
        setContentView(layout);
        
        startService();
    }
    
    Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            textView.setText(serviceState + requireData);
            super.handleMessage(msg);
        }
    };
    

    public void startService(){
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION);
        registerReceiver(receiver, filter);
        
        Intent i = new Intent(this, MyService.class);
        startService(i);
        
        serviceState = "MyService is Running.";
        myHandler.sendEmptyMessage(0);
    }
    
    
    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        myHandler = null;
        super.onDestroy();
    }
    
    public class MyReceiver extends BroadcastReceiver {
        
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            int data = bundle.getInt("data");
            requireData = "The data is "+data;
            myHandler.sendEmptyMessage(0);
        }
    }
    
    public void stopService(){
        Intent intent = new Intent();
        intent.setAction(MyService.ACTION);
        intent.putExtra("cmd", MyService.SERVICE_STOP);
        sendBroadcast(intent);
        serviceState = "MyService is not Running.";
        myHandler.sendEmptyMessage(0);
    }
 
}



2.MyService.java
package aliusa.cn;


import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.SystemClock;

import java.util.Calendar;
import java.util.Random;

/**
 * The Class MyService.
 * @author aliusa
 */
public class MyService extends Service{
    
    static final int SERVICE_STOP = 0;
    
    static final int SERVICE_PUSH_DATA = 1;
    
    static final String ACTION= "aliusa.cn.MyService";
    
    static MyService instance = null;
    
    MyReceiver recevier;
    
    NotificationManager nm;

    AlarmManager am;
    PendingIntent senderDelay;
    PendingIntent senderRepeating;
    
    
    public void registerReviver(){
        recevier = new MyReceiver();
        IntentFilter filter1 = new IntentFilter();
        filter1.addAction(ACTION);
        registerReceiver(recevier, filter1);
    }
    
    
    class MyReceiver extends BroadcastReceiver {
        
        public void onReceive(Context context, Intent intent) {
            int cmd = intent.getIntExtra("cmd", -1);
            switch (cmd) {
                case MyService.SERVICE_STOP:
                    stopSelf();
                    break;
                case MyService.SERVICE_PUSH_DATA:
                    pushDataImmediately();
                    break;
            }
        }
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }



    @Override
    public void onCreate() {
        instance = this;
        super.onCreate();
    }


    @Override
    public void onStart(Intent intent, int startId) {
        registerReviver();
        super.onStart(intent, startId);
    }
    
    

    /**
     * Push data.
     */
    public void pushData(){
        final Random random = new Random();
        Intent i = new Intent();
        i.setAction(Demo.ACTION);
        i.putExtra("data", random.nextInt(100));
        sendBroadcast(i);
    }
    
    
    public void pushDataImmediately(){
        showNotification();
        pushData();
    }
 
    
    private void showNotification() {
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, Demo.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        Notification myNotification = new Notification();
        myNotification.icon = R.drawable.icon;
        myNotification.defaults = Notification.DEFAULT_ALL;
        myNotification.setLatestEventInfo(this, "MyService is running", "chose to have a look", pi);
        nm.notify(0, myNotification);
    }

    
    @Override
    public void onDestroy() {
        cancelAlarmManager();
        if (nm != null){
            nm.cancelAll();
        }
        unregisterReceiver(recevier);
        System.out.println("MyService.onDestroy");
        super.onDestroy();
    }
    
  
    public void pushDataDelay() {
        Intent intent = new Intent();
        intent.setAction(MyService.ACTION);
        intent.putExtra("cmd", MyService.SERVICE_PUSH_DATA);
        senderDelay = PendingIntent.getBroadcast(this, 0, intent, 0);        
        //设定一个五秒后的时间    
        Calendar calendar=Calendar.getInstance();    
        calendar.setTimeInMillis(System.currentTimeMillis());    
        calendar.add(Calendar.SECOND, 5);        
        am =(AlarmManager)getSystemService(ALARM_SERVICE);    
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), senderDelay);    
        //或者以下面方式简化    
        //alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5*1000, senderDelay);
    }
    
    /**
     * Require data.
     */
    public void pushDataRepeating() {
        Intent intent = new Intent();
        intent.setAction(MyService.ACTION);
        intent.putExtra("cmd", MyService.SERVICE_PUSH_DATA);
        senderRepeating = PendingIntent.getBroadcast(this, 1, intent, 0);        
        //开始时间    
        long firstime=SystemClock.elapsedRealtime();    
        am=(AlarmManager)getSystemService(ALARM_SERVICE);
        //5秒一个周期,不停的发送广播    
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, 5*1000, senderRepeating);
    }
    
    public void cancelAlarmManager(){
        if (am != null) {
            if (senderDelay != null) {
                am.cancel(senderDelay);
                senderDelay = null;
            }
            if (senderRepeating != null) {
                am.cancel(senderRepeating);
                senderRepeating = null;
            }
            am = null;
        }
    }


    public static MyService getInstance() {
        return instance;
    }
       
}


3.AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="aliusa.cn"
    android:versionCode="1"
    android:versionName="1.0">
    <uses-permission android:name="android.permission.VIBRATE"></uses-permission>
    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name">
        <activity
            android:name=".Demo"
            android:label="@string/app_name">
            <intent-filter>
                <action
                    android:name="android.intent.action.MAIN" />
                <category
                    android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name="aliusa.cn.MyService">
        </service>
    </application>
    <uses-sdk
        android:minSdkVersion="7" />

</manifest> 
  • 大小: 34.8 KB
  • 大小: 38.3 KB
分享到:
评论

相关推荐

    Notification_Broadcast

    在Android开发中,"Notification_Broadcast"涉及到的关键技术主要包括通知(Notification)的使用、广播接收器(BroadcastReceiver)以及服务(Service)。这三个组件是Android系统中的重要组成部分,它们协同工作,...

    Android 广播事件处理

    在Android开发中,广播事件处理(Broadcast Receiver)是一种核心组件,...同时,利用Notification Manager和AlarmManager可以实现非交互式的用户通知和定时任务调度。理解并熟练运用这些概念对于Android开发至关重要。

    第7章AndroidBroadcastReceiver组件.pptx

    AlarmManager负责设置和管理系统的定时任务,它可以安排一次性或周期性的任务。例如,可以设置一个定时发送广播的闹钟,触发BroadcastReceiver执行特定操作。 ```java AlarmManager alarmManager = (AlarmManager) ...

    android中标准广播action常量.docx

    `NotificationManager`允许开发者创建和管理通知,而`AlarmManager`则可以设置一次性或周期性的闹钟事件,即使应用未运行也能触发指定的Broadcast Receiver或Service。 例如,使用`NotificationManager`创建一个...

    Android基于广播事件机制实现简单定时提醒功能代码

    总结来说,Android的广播事件机制使得在后台处理定时任务成为可能,而通过创建BroadcastReceiver和Notification,我们可以实现一个简单但实用的定时提醒功能。这个功能在日程管理、待办事项提醒等场景中非常有用。...

    Android应用源码之Android一个小闹钟例子.rar

    1. **BroadcastReceiver**: 在Android中,闹钟触发时会发送一个广播(Broadcast),这时我们需要创建一个`BroadcastReceiver`来接收这个广播。`BroadcastReceiver`是Android中的一个组件,用于监听并响应系统或应用...

    基于安卓Android的闹钟功能源码.zip

    2. **BroadcastReceiver**: 当AlarmManager触发的闹钟时间到达时,系统会发送一个Broadcast Intent。你需要创建一个BroadcastReceiver来接收这个Intent,并在onReceive()方法中处理闹钟事件,如播放铃声、显示通知等...

    android 闹铃源程序

    当AlarmManager触发闹钟时,通常会发送一个Broadcast,由注册的BroadcastReceiver来接收并处理这个广播事件。闹钟应用的BroadcastReceiver会在特定时间点被唤醒,执行设定的动作,如播放铃声、振动等。 3. **...

    Android小闹钟项目源码

    当闹钟触发时,系统会发送一个Broadcast Intent,BroadcastReceiver监听到这个Intent后,执行相应的操作,如播放铃声、显示通知等。 3. **Notification**: Android的通知系统用于向用户传达信息。在小闹钟项目中...

    Android应用源码安卓闹钟简洁版注释详细

    2. **BroadcastReceiver**: 闹钟触发后,系统会通过`BroadcastIntent`发送一个广播,这需要我们创建一个`BroadcastReceiver`来接收这个广播。在`onReceive()`方法中,我们可以执行闹钟响起时的逻辑,如播放铃声、...

    安卓闹钟源码

    PendingIntent是一个抽象的意图(Intent)对象,它允许其他应用程序组件(如AlarmManager)在未来的某个时刻启动你的Activity、Service或者发送Broadcast。在闹钟应用中,我们创建一个PendingIntent与...

    Android 小闹钟程序源码

    开发者可以通过AlarmManager设置一次性或周期性的提醒,当到达指定时间时,它会触发BroadcastIntent。 4. **BroadcastReceiver**:接收到AlarmManager触发的广播后,BroadcastReceiver会执行相应的操作,比如启动...

    安卓Android源码——闹钟程序.rar

    2. **BroadcastReceiver**: 闹钟触发时,系统会发送一个广播(Broadcast),而`BroadcastReceiver`是接收这个广播的组件。你需要创建一个继承自`BroadcastReceiver`的类,并在`onReceive()`方法中处理闹钟触发的逻辑...

    andriod闹钟源代码.zip

    2. **BroadcastReceiver**:在闹钟触发时,系统会通过Broadcast发送一个ACTION_BOOT_COMPLETED广播,这通常需要在AndroidManifest.xml中注册一个BroadcastReceiver来接收这个广播。在源代码中,你可能会看到一个名为...

    Android代码-闹钟源码.zip

    2. **BroadcastReceiver**: 闹钟触发时,系统会发送一个广播(Broadcast Intent),这需要一个`BroadcastReceiver`来接收并处理这个事件。在AndroidManifest.xml中注册这个接收器,并指定对应的Intent过滤器,确保...

    Android应用源码闹钟程序-IT计算机-毕业设计.zip

    在Android应用开发中,闹钟程序是一个常见的实用功能,它涉及到Android系统服务、BroadcastReceiver、AlarmManager、Intent以及用户界面等多个关键组件。本项目是一个基于Android的毕业设计示例,旨在帮助学生理解和...

    基于android的移动应用闹钟源代码.zip

    1. **Android应用程序基础**:Android应用通常由多个组件构成,包括Activity(用户界面)、Service(后台服务)、BroadcastReceiver(广播接收器)和ContentProvider(数据共享)。在这个闹钟应用中,主要关注...

Global site tag (gtag.js) - Google Analytics