Notification的基本用法以及使用RemoteView实现自定义(3)

RemoteView表示的是一种View结构,它可以在其他进程中显示(具体来讲是SystemServer进程),由于它是在其他进程中显示,为了更新它的界面,我们不能简单地使用普通View的那一套方法,RemoteView提供了一系列Set方法用于更新界面。

下面就是一个简单的示例;

package com.pignet.remoteviewtest; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RemoteViews; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnNotification = (Button) findViewById(R.id.btn_notification); btnNotification.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendNotification(); } }); } private void sendNotification(){ NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification =new Notification(); notification.icon=R.mipmap.ic_launcher; notification.when=System.currentTimeMillis(); notification.flags=Notification.FLAG_AUTO_CANCEL; //跳转意图 Intent intent = new Intent(this,SettingsActivity.class); //建立一个RemoteView的布局,并通过RemoteView加载这个布局 RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.layout_notification); //为remoteView设置图片和文本 remoteViews.setTextViewText(R.id.message,"第一条通知"); remoteViews.setImageViewResource(R.id.image,R.mipmap.ic_launcher_round); //设置PendingIntent PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT); //为id为openActivity的view设置单击事件 remoteViews.setOnClickPendingIntent(R.id.openActivity,pendingIntent); //将RemoteView作为Notification的布局 notification.contentView =remoteViews; //将pendingIntent作为Notification的intent,这样当点击其他部分时,也能实现跳转 notification.contentIntent=pendingIntent; notificationManager.notify(1,notification); } }

有图:

Notification的基本用法以及使用RemoteView实现自定义

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/d3ef519b3abf6e058b5ff03298981ff5.html