【Android】利用服務Service創建標題欄通知

創建標題欄通知的核心代碼

	public void CreateInform() {
		//定義一個PendingIntent,當用戶點擊通知時,跳轉到某個Activity(也可以發送廣播等)
		Intent intent = new Intent(context,MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
		
		//創建一個通知
		Notification notification = new Notification(R.drawable.icon, "巴拉巴拉~~", System.currentTimeMillis());
		notification.setLatestEventInfo(context, "點擊查看", "點擊查看詳細內容", pendingIntent);
		
		//用NotificationManager的notify方法通知用戶生成標題欄消息通知
		NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nManager.notify(100, notification);//id是應用中通知的唯一標識
		//如果擁有相同id的通知已經被提交而且沒有被移除,該方法會用更新的信息來替換之前的通知。
	}

全部Service代碼

package com.app.myservice;

import org.json.JSONException;
import org.json.JSONObject;

import com.app.util.MyApplication;

import android.R.integer;
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 ServiceDemo02 extends Service{
	Context context;
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		context = getApplicationContext();
	}
	//創建通知
	public void CreateInform() {
		//定義一個PendingIntent,當用戶點擊通知時,跳轉到某個Activity(也可以發送廣播等)
		Intent intent = new Intent(context,MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
		
		//創建一個通知
		Notification notification = new Notification(R.drawable.icon, "巴拉巴拉~~", System.currentTimeMillis());
		notification.setLatestEventInfo(context, "點擊查看", "點擊查看詳細內容", pendingIntent);
		
		//用NotificationManager的notify方法通知用戶生成標題欄消息通知
		NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nManager.notify(100, notification);//id是應用中通知的唯一標識
		//如果擁有相同id的通知已經被提交而且沒有被移除,該方法會用更新的信息來替換之前的通知。
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stubm
		super.onStart(intent, startId);
		CreateInform();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

}

效果圖





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