Android Api Demos登顶之路(五十)Notification-->Service Controller

本文详细介绍了如何在Android应用中实现并管理通知服务,包括创建服务类、发送消息通知以及与用户交互的动作响应。通过使用NotificationManager和Builder类,开发者能够轻松地在通知栏展示自定义通知,增强用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个demo演示了如何利用服务发送消息通知
activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/hello_world" />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/start"
        android:text="Start Service"
        android:layout_gravity="center_horizontal"/>
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/stop"
        android:text="Stop Service"
        android:layout_gravity="center_horizontal"/>

</LinearLayout>

NotificationService

public class NotificationService extends Service {

    private static final int MOOD_NOTIFICATION = R.id.start;
    // ConditionVariable用于线程同步
    private ConditionVariable mCondition;
    private NotificationManager nm;

    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化一些变量
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mCondition = new ConditionVariable(false);
        Thread notifyThread = new Thread(mTask, "NotificationService");
        notifyThread.start();
    }

    private Runnable mTask = new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 4; i++) {
                showNotification(R.drawable.star_big_on, "OK");
                //如果阻塞在5秒内被打开了,则跳出循环
                if(mCondition.block(5*1000)){
                    break;
                }
                showNotification(R.drawable.icon48x48_2, "Happy");
                //如果阻塞在5秒内被打开了,则跳出循环
                if(mCondition.block(5*1000)){
                    break;
                }
                showNotification(R.drawable.ic_launcher, "Sad");
                //如果阻塞在5秒内被打开了,则跳出循环
                if(mCondition.block(5*1000)){
                    break;
                }
            }
            //循环结束后则结束服务
            NotificationService.this.stopSelf();
        }
    };

    //这个对象接收客户端的交互动作
    private final IBinder mBinder = new Binder() {

        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply,
                int flags) throws RemoteException {
            return super.onTransact(code, data, reply, flags);
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    protected void showNotification(int moodId, String text) {
        // 点击消息时启动自己的主Activity,最后一个参数设为0表示使用系统默认的标识符
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);
        Notification.Builder builder=new Builder(this);
        /*
         * 这里需要注意的是,在这里没对trickerText进行设值,而是通过在通知栏中图标的更新
         * 变化来显示通知消息已经发生了改变。官方也强烈要求以这种方式进行设置(如同网络状态的改变的通知)
         */
        builder.setSmallIcon(moodId)
               .setWhen(System.currentTimeMillis())
               .setContentTitle("Mood")
               .setContentText(text)
               .setDefaults(Notification.DEFAULT_ALL)
               .setContentIntent(contentIntent);
        Notification noti=builder.build();
        nm.notify(MOOD_NOTIFICATION, noti);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消通知消息
        nm.cancel(MOOD_NOTIFICATION);
        //打开阻塞
        mCondition.open();
    }

}

MainActivity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button start=(Button) findViewById(R.id.start);
        Button stop=(Button) findViewById(R.id.stop);
        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(MainActivity.this, NotificationService.class));
            }
        });
        stop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(new Intent(MainActivity.this, NotificationService.class));
            }
        });
    }


}

配置文件

<service 
            android:name="com.fishtosky.notificationservice.NotificationService"></service>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值