android 當中service的簡單用法(用於消息推送)

用於服務器的消息推送。

基本上就是用來做新消息提醒的,比較好用這個方法。

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;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;

import com.ladongjiguang.meikuangwuziyunshu.R;
import com.ladongjiguang.meikuangwuziyunshu.activity.MainActivity;
import com.ladongjiguang.meikuangwuziyunshu.activity.OrderDetailActivity;

/**
 * Created by admin on 2016/9/2.
 */
public class MessageService extends Service {
    //獲取消息線程
    private MessageThread messageThread = null;
    //通知欄通知疊加
    private int i = 0;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //開啓線程
        messageThread = new MessageThread();
        messageThread.isRunning = true;
        messageThread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 從服務器端獲取消息
     *
     */
    class MessageThread extends Thread{
        //運行狀態,下一步驟有大用
        public boolean isRunning = true;//終止服務時需要終止這個子線程,賦值false
        public void run() {
            while(isRunning){
                try {
                    //休息10秒
                    Thread.sleep(10000);
                    //獲取服務器消息
                    String serverMessage = getServerMessage();
                    if(serverMessage!=null&&!"".equals(serverMessage)){
                        //更新通知欄
                        /*獲取狀態通知欄管理*/
                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        /*實例化通知欄構造器NotificationCompat.Builder*/
                        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getBaseContext());
                        /*點擊事件*/
                        Intent intent = new Intent(getBaseContext(),OrderDetailActivity.class);
                        PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent, 0);
                        /*配置通知欄*/
                        mBuilder.setContentTitle("你有新的消息")//設置通知欄標題
                                .setContentText("測試內容"+getServerMessage()) //設置通知欄顯示內容
//                                .setContentIntent(pendingIntent)//通知欄點擊事件
                                //	.setNumber(number) //設置通知集合的數量
                                .setTicker("通知來啦") //通知首次出現在通知欄,帶上升動畫效果的
                                .setWhen(System.currentTimeMillis())//通知產生的時間,會在通知信息裏顯示,一般是系統獲取到的時間
                                .setPriority(Notification.PRIORITY_DEFAULT) //設置該通知優先級
                                //	.setAutoCancel(true)//設置這個標誌當用戶單擊面板就可以讓通知將自動取消
                                .setOngoing(false)//ture,設置他爲一個正在進行的通知。他們通常是用來表示一個後臺任務,用戶積極參與(如播放音樂)或以某種方式正在等待,因此佔用設備(如一個文件下載,同步操作,主動網絡連接)
                                .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加聲音、閃燈和振動效果的最簡單、最一致的方式是使用當前的用戶默認設置,使用defaults屬性,可以組合
                                //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加聲音
                                // requires VIBRATE permission
                                .setSmallIcon(R.drawable.ic_launcher);//設置通知小ICON
                        mNotificationManager.notify(i, mBuilder.build());
                        i++;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 這裏以此方法爲服務器Demo,僅作示例
     * @return 返回服務器要推送的消息,否則如果爲空的話,不推送
     */
    public String getServerMessage(){
        return "";
    }

    @Override
    public void onDestroy() {
        messageThread.isRunning = false;//銷燬service之時,銷燬子線程,必須有,否則子線程無限循環,耗電嚴重
        super.onDestroy();
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章