Android (Notification)訊息推送機制

來源:互聯網
上載者:User

標籤:des   android   style   blog   http   io   ar   color   os   

從網上查詢資料學習Android訊息推送機制,如下:

1.首先是布局檔案代碼 activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="hello" />    <Button        android:id="@+id/btnStart"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="通知" />    <Button        android:id="@+id/btnStop"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="清除" /></LinearLayout>

2.然後是java主介面代碼MainActivity.java

package com.example.notificationservice;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {    private Button btnStart;    private Button btnStop;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();    }    private void initView() {        btnStart = (Button) findViewById(R.id.btnStart);        btnStop = (Button) findViewById(R.id.btnStop);        btnStart.setOnClickListener(this);        btnStop.setOnClickListener(this);    }    @Override    public void onClick(View v) {        int id = v.getId();        if (id == R.id.btnStart) {            // 啟動Service            Intent intent = new Intent();            intent.setAction("ymw.MY_SERVICE");            startService(intent);        }        if (id == R.id.btnStop) {            // 關閉Service            Intent intent = new Intent();            intent.setAction("ymw.MY_SERVICE");            stopService(intent);        }    }    @Override    public void onBackPressed() {        System.exit(0);        super.onBackPressed();    }}

3.然後是訊息推送服務檔案 NotificationService.java

package com.example.notificationservice;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.IBinder;public class NotificationService extends Service {    // 擷取訊息線程    private MessageThread messageThread = null;    // 點擊查看    private Intent messageIntent = null;    private PendingIntent messagePendingIntent = null;    // 通知欄訊息    private int messageNotificationID = 1000;    private Notification messageNotification = null;    private NotificationManager messageNotificatioManager = null;    public IBinder onBind(Intent intent) {        return null;    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        // 初始化        messageNotification = new Notification();        messageNotification.icon = R.drawable.ic_launcher;        messageNotification.tickerText = "新訊息";        messageNotification.defaults = Notification.DEFAULT_SOUND;        messageNotificatioManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);        messageIntent = new Intent(this, MainActivity.class);        messagePendingIntent = PendingIntent.getActivity(this, 0,                messageIntent, 0);        // 開啟線程        messageThread = new MessageThread();        messageThread.isRunning = true;        messageThread.start();        return super.onStartCommand(intent, flags, startId);    }    /**     * 從伺服器端擷取訊息     *      */    class MessageThread extends Thread {        // 設定是否迴圈推送        public boolean isRunning = true;        public void run() {            // while (isRunning) {            try {                // 間隔時間                Thread.sleep(1000);                // 擷取伺服器訊息                String serverMessage = getServerMessage();                if (serverMessage != null && !"".equals(serverMessage)) {                    // 更新通知欄                    messageNotification.setLatestEventInfo(                            getApplicationContext(), "新訊息", "您有新訊息。"                                    + serverMessage, messagePendingIntent);                    messageNotificatioManager.notify(messageNotificationID,                            messageNotification);                    // 每次通知完,通知ID遞增一下,避免訊息覆蓋掉                    messageNotificationID++;                }            } catch (InterruptedException e) {                e.printStackTrace();            }            // }        }    }    @Override    public void onDestroy() {        // System.exit(0);        messageThread.isRunning = false;        super.onDestroy();    }    /**     * 類比發送訊息     *      * @return 返回伺服器要推送的訊息,否則如果為空白的話,不推送     */    public String getServerMessage() {        return "NEWS!";    }}

 

4.最後別忘了在mainfeast.xml檔案中配置Service

項目代碼如下連結:

http://files.cnblogs.com/_ymw/NotificationService_%E5%8D%9A%E5%AE%A2%E9%99%84%E4%BB%B6.rar

 

Android (Notification)訊息推送機制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.