本文主要是介绍消息通知 Notification 点击切换回原Activity,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一个简单的应用场景:假如用户打开Activity以后,按Home键,此时Activity 进入-> onPause() -> onStop() 不可见。代码在此时机发送一个Notification到通知栏。当用户点击通知栏的Notification后,又重新onRestart() -> onStart() -> onResume() 切换回原Activity。
效果图:
package com.example.notification;import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;public class MainActivity extends Activity {private final int NOTIFICATION_ID = 0xa01;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);Log.d(this.getClass().getName(), "onCreate()");setContentView(R.layout.activity_main);Button send = (Button) findViewById(R.id.send);send.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {sendNotification();}});Button clear = (Button) findViewById(R.id.clear);clear.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {clearNotification();}});}private void sendNotification() {NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);mBuilder.setSmallIcon(R.drawable.ic_launcher);// mBuilder.setContentTitle("来自徐华清");// mBuilder.setContentText("烟花易冷,很好听!");Notification notification = mBuilder.build();// 当用户下来通知栏时候看到的就是RemoteViews中自定义的Notification布局RemoteViews rv = new RemoteViews(getPackageName(),R.layout.notification);rv.setImageViewResource(R.id.image, R.drawable.qq);rv.setTextViewText(R.id.title, "清清");rv.setTextViewText(R.id.text, "烟花易冷,很好听!");notification.contentView = rv;// 需要注意的是,作为选项,此处可以设置MainActivity的启动模式为singleTop,避免重复新建onCreate()。Intent intent = new Intent(this, MainActivity.class);// 当用户点击通知栏的Notification时候,切换回MainActivity。PendingIntent pi = PendingIntent.getActivity(this, 0x05, intent,PendingIntent.FLAG_UPDATE_CURRENT);notification.contentIntent = pi;// 缺省设置为当发送通知到通知栏的时候:提示声音+震动notification.defaults = Notification.DEFAULT_SOUND| Notification.DEFAULT_VIBRATE;// 通知的时间notification.when = System.currentTimeMillis()
这篇关于消息通知 Notification 点击切换回原Activity的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!