Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Service 實作 Android 訊息推送:後台輪詢與通知欄的完整流程

編輯:關於 Android 程式設計

本文示範一種最直觀的推送模擬方式:讓 Service 在後台常駐,定期向伺服器發出請求,若判定有新訊息就發出通知。涉及的主要知識點是 Service、Notification,以及 android-async-http 這個開源 HTTP 框架。

需求場景

應用常有這樣的需求:客戶端每隔一段時間向伺服器發一次請求,取得即時更新的重要資訊,例如天氣預報或簡訊提醒。而 Android 四大元件之一的 Service,正好適合承擔這種「不需要使用者參與、持續在背景運行」的工作。

思路很直接:在 Service 裡開一條執行緒,只要 Service 不停止,迴圈就一直跑,每隔固定時間打一次網路請求。

一、啟動 Service

public void open(View view) {
    Intent intent = new Intent(this, PushSmsService.class);
    startService(intent);
}

二、自訂 PushSmsService

public class PushSmsService extends Service {
    private MyThread myThread;
    private NotificationManager manager;
    private Notification notification;
    private PendingIntent pi;
    private AsyncHttpClient client;
    private boolean flag = true;

    @Override
    public IBinder onBind(Intent intent) {
        return null;   // 不需要綁定式服務
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.client = new AsyncHttpClient();
        this.myThread = new MyThread();
        this.myThread.start();
    }

    @Override
    public void onDestroy() {
        this.flag = false;   // 讓迴圈退出
        super.onDestroy();
    }

    /** 發出通知 */
    private void notification(String content, String number, String date) {
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notification = new Notification(R.drawable.ic_menu_compose, content,
                System.currentTimeMillis());
        notification.defaults = Notification.DEFAULT_ALL;   // 鈴聲、震動、閃燈
        notification.flags = Notification.FLAG_AUTO_CANCEL; // 點擊後自動消失
        notification.flags |= Notification.FLAG_NO_CLEAR;   // 手動清除時不消失

        Intent intent = new Intent(getApplicationContext(), ContentActivity.class);
        intent.putExtra("content", content);
        intent.putExtra("number", number);
        intent.putExtra("date", date);

        pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
        notification.setLatestEventInfo(getApplicationContext(),
                number + " 發來簡訊", content, pi);

        manager.notify(0, notification);
    }

    /** 輪詢執行緒 */
    private class MyThread extends Thread {
        @Override
        public void run() {
            String url = "https://110.65.99.66:8080/jerry/PushSmsServlet";
            while (flag) {
                try {
                    Thread.sleep(10000);   // 每 10 秒請求一次
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                client.get(url, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          byte[] responseBody) {
                        try {
                            JSONObject result = new JSONObject(
                                    new String(responseBody, "utf-8"));
                            int state = result.getInt("state");
                            // 範例規則:偶數視為未讀
                            if (state % 2 == 0) {
                                notification(result.getString("content"),
                                        result.getString("number"),
                                        result.getString("date"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers,
                                          byte[] responseBody, Throwable error) {
                        Toast.makeText(getApplicationContext(),
                                "資料請求失敗", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }
}

三、清單檔註冊與權限

<service android:name=".PushSmsService"></service>
<activity android:name=".ContentActivity"></activity>

<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

四、通知點擊後的詳情頁

public class ContentActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content);

        TextView tv_content = (TextView) findViewById(R.id.tv_content);
        TextView tv_number  = (TextView) findViewById(R.id.tv_number);
        TextView tv_date    = (TextView) findViewById(R.id.tv_date);

        Intent intent = getIntent();
        if (intent != null) {
            tv_content.setText("內容:" + intent.getStringExtra("content"));
            tv_number.setText("號碼:" + intent.getStringExtra("number"));
            tv_date.setText("日期:" + intent.getStringExtra("date"));
        }
    }
}

五、伺服器端:一個 Servlet 加一個實體類

public class PushSmsServlet extends HttpServlet {
    private static int index = 1;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Sms sms = new Sms(index++, "測試內容" + index, "2013-03-03", "13522224444");

        response.setContentType("text/html");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();
        String json = new Gson().toJson(sms);   // 用 Gson 序列化
        out.write(json);
        out.flush();
        out.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
}

// 訊息實體
class Sms {
    private int state;
    private String content;
    private String date;
    private String number;

    public Sms(int state, String content, String date, String number) {
        this.state = state;
        this.content = content;
        this.date = date;
        this.number = number;
    }
}

六、這套做法在真實專案中的取捨

上面是最容易理解的實作,但把它直接搬上正式環境會遇到幾個問題,值得先想清楚:

  • Doze 模式與後台限制。Android 6.0 之後,長時間常駐的 foreground service 以外的後台執行緒會被系統凍結,10 秒輪詢根本不可能穩定執行。若確實需要週期性工作,應改用 WorkManager;需要即時性則應改用 FCM 推送。
  • 輪詢既耗電又耗流量。伺服器沒訊息時的每一次請求都是純消耗。實務上會搭配退避策略(失敗後拉長間隔)或改用長連線。
  • Notification API 已全面更新。範例中的 setLatestEventInfo() 與 new Notification() 在建構方式上早已被取代。Android 8.0 起必須建立 NotificationChannel,並改用 Notification.Builder;Android 13 起還需要 POST_NOTIFICATIONS 執行期權限。
  • execute 於主線程的 Toast。背景執行緒直接彈 Toast 行為不穩定,應改用 Handler 拋回主線程處理。
  • Service 缺少降級處理。建議改用 startForeground() 搭配常駐通知,讓系統知道這個服務不該被隨意回收。

總結來說,Service 加執行緒的輪詢模式非常適合理解 Android 背景作業的基本骨架;但要真正上線,請把「週期性任務」交給 WorkManager,把「即時送達」交給 FCM,Service 則專心處理需要長連線或長時間耗費的場景,例如音樂播放或檔案傳輸。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved