Android的自訂notification選項我覺得限制還是挺多的,,官方API告訴我們它依然必須得設定icon,tittle,text三個選項,除此之外,還一定要設定pengdingintent,不少網友還反映 builder.setContent(remoteViews)後面一定要緊跟著builder.setContentIntent(pendingIntent),要不然會報錯誤:android.app.RemoteServiceException: Bad notification posted from package。
MainActivity代碼
package com.example.f04_notification;import android.os.Bundle;import android.app.Activity;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import android.support.v4.app.NotificationCompat;import android.view.View;import android.widget.Button;import android.widget.RemoteViews;public class MainActivity extends Activity {private NotificationManager manager;private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)this.findViewById(R.id.button1); //擷取系統服務 manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubNotificationCompat.Builder builder=new NotificationCompat.Builder(MainActivity.this);RemoteViews remoteViews=new RemoteViews(getPackageName(), R.layout.notifiaction);//因為android api的限制,自訂通知仍需要set small icon,setContentTittle,setContentTextbuilder.setSmallIcon(R.drawable.ic_launcher);builder.setContentText("hello world!");builder.setContentTitle("Android");//以上內容仍必須設定一遍remoteViews.setTextViewText(R.id.textView1, "通知來了");remoteViews.setImageViewResource(R.id.imageView1, R.drawable.ic_launcher);Intent intent=new Intent(MainActivity.this,MainActivity.class);//pendingintent的flag分為四個FLAG_CANCEL_CURRENT,FLAG_NO_CREATE,FLAG_ONE_SHOT,FLAG_UPDATE_CURRENTPendingIntent pendingIntent=PendingIntent.getActivity(MainActivity.this, 1, intent, PendingIntent.FLAG_ONE_SHOT);builder.setContent(remoteViews);builder.setContentIntent(pendingIntent);manager.notify((int)System.currentTimeMillis(), builder.build());}}); } }
布局xml檔案
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/imageView1" android:contentDescription="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="27dp" android:layout_marginTop="33dp" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/imageView1" android:layout_marginLeft="76dp" android:layout_toRightOf="@+id/imageView1" android:text="@string/hello_world" /></RelativeLayout>
感謝大家的閱讀,希望跟大家一起互相學習,互相進步!