实现类似QQ音乐的notification

1.设置布局:notification.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ImageView 
        android:src="@drawable/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="QQ音乐播放器" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="模仿音乐播放器" />
    </LinearLayout>

</LinearLayout> 

2.封装Notification:BaseActivity.java
package com.anjoyo.notificationM;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.anjoyu.activity.Qq_muiceActivity;
import com.anjoyu.second.R;

public class BaseActivity extends Activity {
	/**
	 * 封装notification类,并且主线程activit必须继承本类
	 * 
	 * */

	private NotificationManager manager;//为,标题栏管理方法,设置 Notification的发通知
	private static final int NOTIFY_ID = 1;
	private Notification notificy;//具体为标题栏的对象,可以设置文字,图片,声音,震动等...
	private Context context = this;
	TextView title;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 后台运行
		manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notificy = new Notification(R.drawable.icon, "正在跳转",
				System.currentTimeMillis());
		notificy.flags = Notification.FLAG_AUTO_CANCEL
				| Notification.FLAG_ONGOING_EVENT | Notification.DEFAULT_SOUND;
		// PendingIntent (点击通知执行页面跳转)
		PendingIntent contenIntent = PendingIntent.getActivity(context, 1,
				new Intent(context, Qq_muiceActivity.class),
				PendingIntent.FLAG_UPDATE_CURRENT);
		notificy.setLatestEventInfo(context, "hello", "QQ音乐",//后台界面设置
				contenIntent);
	}

	public void settitle() {

	}

	// onResume事件
	protected void onResume() {
		super.onResume();
		manager.cancel(NOTIFY_ID);
	}

	// onPause事件
	protected void onPause() {
		manager.notify(NOTIFY_ID, notificy);
		super.onPause();
	}

}

3.主类必须继承封装类:qq_musicActivity extends BaseActivity

4.在主线程中设置返回键问题:
 //notification 在返回键的操作
    public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			moveTaskToBack(true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}


你可能感兴趣的:(实现类似QQ音乐的notification)