第五十讲:Android之Nothfication(三)

勤能补拙是良训,一分辛劳一分才。


本讲内容:通知 Notification 和 通知管理器 NotificationManager


我们通过一个例子实现一个可更新进度的通知,代码的讲解都写在注释里了

下面是res/layout/activity_main.xml 布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.text1.MainActivity$PlaceholderFragment" >
	<Button 
	    android:id="@+id/download"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:text="download"
	    android:onClick="download"/>
	<Button 
	    android:id="@+id/cancel"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:text="cancel"
	    android:onClick="cancel"/>
	<!-- 为了使示例中的Java代码看起来结构更加清晰,我们将按钮的点击事件都定义在布局文件中。 -->
</LinearLayout>

下面是带进度的通知布局/res/layout/download_notification_layout.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"
    android:padding="3dp">
    <ImageView 
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:src="@drawable/ic_launcher"/>
    <TextView 
        android:id="@+id/fileName"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toRightOf="@id/imageView"
        android:layout_alignBottom="@id/imageView"
        android:gravity="center_vertical"
        android:textColor="#0f0"/>
    <TextView 
        android:id="@+id/rate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageView"
        android:layout_alignRight="@id/imageView"
        android:gravity="center"
        android:text="0%"
        android:textColor="#0f0"/>
    <ProgressBar 
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/fileName"
        android:layout_alignLeft="@id/fileName"
        android:max="100"
        android:progress="0"/>
</RelativeLayout>

下面是MainActivity.java主界面文件:

public class MainActivity extends Activity {
	private Notification notification;
	private NotificationManager notificationManager;
	private static final int NOTIFY_ID=0;
	private boolean flag;
	private Context context=this;
	
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				int rate=msg.arg1;
				if(rate<100){
					 // 更新进度  
                    RemoteViews contentView = notification.contentView;  
                    contentView.setTextViewText(R.id.rate, rate + "%");  
                    contentView.setProgressBar(R.id.progress, 100, rate, false);  
				}else{
					// 下载完毕后变换通知形式  
                    notification.flags = Notification.FLAG_AUTO_CANCEL;  
                    notification.contentView = null;  
                    Intent intent = new Intent(context, NotifyActivity.class);  
                    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);  
                    notification.setLatestEventInfo(context, "下载完成", "文件已下载完毕", contentIntent);  
				}
				 // 最后别忘了通知一下,否则不会更新  
                notificationManager.notify(NOTIFY_ID, notification);
				break;

			case 0:
				 // 取消通知  
                notificationManager.cancel(NOTIFY_ID);  
                break; 
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	public void download(View view){
		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
		  
        int icon = R.drawable.ic_launcher;  
        CharSequence tickerText = "开始下载";  
        long when = System.currentTimeMillis();  
        notification = new Notification(icon, tickerText, when); 
     // 放置在"正在运行"栏目中  
        notification.flags = Notification.FLAG_ONGOING_EVENT;  
        
        //点击通知时不跳转 
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, getIntent(), 0); 
        
        RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.download_notification_layout);  
        contentView.setTextViewText(R.id.fileName, "AngryBird.apk");  
        // 指定个性化视图  
        notification.contentView = contentView; 
        // 指定内容意图  
       notification.contentIntent = contentIntent; 
  
        notificationManager.notify(NOTIFY_ID, notification);  
  
        new Thread() {  
            public void run() {  
                startDownload();  
            };  
        }.start();  
	}
	 public void cancel(View view) {  
	        flag = true; // 在控制下载线程时使用了flag这个boolean值标志变量,对于线程的控制更好一些
	    }  
	 private void startDownload() {  
	        flag = false;  
	        int rate = 0;  
	        while (!flag && rate < 100) {  
	            try {  
	                // 模拟下载进度  
	                Thread.sleep(500);  
	                rate = rate + 5;  
	            } catch (InterruptedException e) {  
	                e.printStackTrace();  
	            }  
	            Message msg = handler.obtainMessage();  
	            msg.what = 1;  
	            msg.arg1 = rate;  
	            handler.sendMessage(msg);  
	        }  
	        if (flag) {  
	            Message msg = handler.obtainMessage();  
	            msg.what = 0;  
	            handler.sendMessage(msg);  
	        }  
	    }  
}
上面涉及到线程和handler类,后面章节我们会深入讲解


下面是运行结果:



本讲就到这里,Take your time and enjoy it

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。