編輯:關於 Android 程式設計
本文示範一種最直觀的推送模擬方式:讓 Service 在後台常駐,定期向伺服器發出請求,若判定有新訊息就發出通知。涉及的主要知識點是 Service、Notification,以及 android-async-http 這個開源 HTTP 框架。
應用常有這樣的需求:客戶端每隔一段時間向伺服器發一次請求,取得即時更新的重要資訊,例如天氣預報或簡訊提醒。而 Android 四大元件之一的 Service,正好適合承擔這種「不需要使用者參與、持續在背景運行」的工作。
思路很直接:在 Service 裡開一條執行緒,只要 Service 不停止,迴圈就一直跑,每隔固定時間打一次網路請求。
public void open(View view) {
Intent intent = new Intent(this, PushSmsService.class);
startService(intent);
}
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"));
}
}
}
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;
}
}
上面是最容易理解的實作,但把它直接搬上正式環境會遇到幾個問題,值得先想清楚:
WorkManager;需要即時性則應改用 FCM 推送。setLatestEventInfo() 與 new Notification() 在建構方式上早已被取代。Android 8.0 起必須建立 NotificationChannel,並改用 Notification.Builder;Android 13 起還需要 POST_NOTIFICATIONS 執行期權限。startForeground() 搭配常駐通知,讓系統知道這個服務不該被隨意回收。總結來說,Service 加執行緒的輪詢模式非常適合理解 Android 背景作業的基本骨架;但要真正上線,請把「週期性任務」交給 WorkManager,把「即時送達」交給 FCM,Service 則專心處理需要長連線或長時間耗費的場景,例如音樂播放或檔案傳輸。
Android CM9 源碼下載與編譯實戰指南
本文以 Samsung Galaxy S2 為例,說明如何在 Ubuntu 環境中下載、編譯 CyanogenMod 9 源碼,並進一步編譯單一 App 或 Framew
魅藍E與紅米Pro全面對比 誰更值得入手
隨著魅藍E正式發表,魅族與小米在千元機市場的對決再度升溫。不少網友拿它和前不久登場的紅米Pro做對比,那麼魅藍E和紅米Pro到底哪個更好?下面我們就從各個面向詳細比一比。
Android Fragment 使用方法整理
Android Fragment 使用方法整理 Fragment 是 Android 中常見的 UI 元件,可視為可重複使用、可嵌入 Activity 的畫面區塊。它適合
Android 官方文檔譯讀:用 Intent 在應用之間分享簡單數據
Sharing Simple Data Android 應用最迷人的一點,是它們彼此之間能通信、能整合。既然某個功能已經有別的 app 做好了,為什麼還要在自己的 app