<span style="color:#ff6666;">我用到的是Fragment</span>
一.fragment类继承OnCheckedChangeListener会要求实现onCheckedChanged方法
初始化,我是两个SwitchButton控件:
lv_pushMessage = (SwitchButton) view.findViewById(R.id.lv_pushMessage);
lv_pushMessage.setChecked(true);
lv_pushSound = (SwitchButton) view.findViewById(R.id.lv_pushSound);
lv_pushSound.setChecked(true);
onCheckedChanged方法中:
if (arg0==lv_pushMessage) {
if (!lv_pushMessage.isChecked()) {
// 关闭或开启推送功能
if (PushManager.isPushEnabled(getActivity())) {
PushManager.stopWork(getActivity());
Toast.makeText(getActivity(), "推送已关闭", Toast.LENGTH_SHORT)
.show();
}
}else {
PushManager.resumeWork(getActivity());
Toast.makeText(getActivity(), "推送已开启", Toast.LENGTH_SHORT)
.show();
}
}
if (arg0==lv_pushSound) {
//开启或关闭推送声音
if (!lv_pushSound.isChecked()) {
//没有点击
SPUtil.set(context, "issound", "false");
Toast.makeText(context, "推送声音关闭", Toast.LENGTH_SHORT).show();
} else {
SPUtil.set(context, "issound", "true");
Toast.makeText(context, "推送声音已开启", Toast.LENGTH_SHORT).show();
}
}
}
二、三、四步直接复制粘贴以下代码:
CheckBoxPreference 类:
package com.sfdj.salebaby.view;
import android.app.Service;
import android.content.Context;
import android.preference.PreferenceActivity;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import com.sfdj.salebaby.R;
public class CheckBoxPreference extends android.preference.CheckBoxPreference {
private Context mContext;
private int mLayoutResId = R.layout.preference;
private int mWidgetLayoutResId = R.layout.preference_widget_checkbox;
private boolean mShouldDisableView = true;
private CharSequence mSummaryOn;
private CharSequence mSummaryOff;
private boolean mSendAccessibilityEventViewClickedType;
private AccessibilityManager mAccessibilityManager;
public CheckBoxPreference(Context context, AttributeSet attrset,
int defStyle) {
super(context, attrset);
mContext = context;
mSummaryOn = getSummaryOn();
mSummaryOff = getSummaryOff();
mAccessibilityManager = (AccessibilityManager) mContext
.getSystemService(Service.ACCESSIBILITY_SERVICE);
}
public CheckBoxPreference(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.checkBoxPreferenceStyle);
}
public CheckBoxPreference(Context context) {
this(context, null);
}
/**
* Creates the View to be shown for this Preference in the
* {@link PreferenceActivity}. The default behavior is to inflate the main
* layout of this Preference (see {@link #setLayoutResource(int)}. If
* changing this behavior, please specify a {@link ViewGroup} with ID
* {@link android.R.id#widget_frame}.
* <p>
* Make sure to call through to the superclass's implementation.
*
* @param parent
* The parent that this View will eventually be attached to.
* @return The View that displays this Preference.
* @see #onBindView(View)
*/
protected View onCreateView(ViewGroup parent) {
final LayoutInflater layoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = layoutInflater.inflate(mLayoutResId, parent, false);
if (mWidgetLayoutResId != 0) {
final ViewGroup widgetFrame = (ViewGroup) layout
.findViewById(R.id.widget_frame);
layoutInflater.inflate(mWidgetLayoutResId, widgetFrame);
}
return layout;
}
@Override
protected void onBindView(View view) {
// 灞忚斀item鐐瑰嚮浜嬩欢
view.setClickable(false);
TextView textView = (TextView) view.findViewById(R.id.title);
if (textView != null) {
textView.setText(getTitle());
}
textView = (TextView) view.findViewById(R.id.summary);
if (textView != null) {
final CharSequence summary = getSummary();
if (!TextUtils.isEmpty(summary)) {
if (textView.getVisibility() != View.VISIBLE) {
textView.setVisibility(View.VISIBLE);
}
textView.setText(getSummary());
} else {
if (textView.getVisibility() != View.GONE) {
textView.setVisibility(View.GONE);
}
}
}
if (mShouldDisableView) {
setEnabledStateOnViews(view, isEnabled());
}
View checkboxView = view.findViewById(R.id.checkbox);
if (checkboxView != null && checkboxView instanceof Checkable) {
((Checkable) checkboxView).setChecked(isChecked());
SwitchButton switchButton = (SwitchButton) checkboxView;
switchButton
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mSendAccessibilityEventViewClickedType = true;
if (!callChangeListener(isChecked)) {
return;
}
setChecked(isChecked);
}
});
// send an event to announce the value change of the CheckBox and is
// done here
// because clicking a preference does not immediately change the
// checked state
// for example when enabling the WiFi
if (mSendAccessibilityEventViewClickedType
&& mAccessibilityManager.isEnabled()
&& checkboxView.isEnabled()) {
mSendAccessibilityEventViewClickedType = false;
int eventType = AccessibilityEvent.TYPE_VIEW_CLICKED;
checkboxView.sendAccessibilityEventUnchecked(AccessibilityEvent
.obtain(eventType));
}
}
// Sync the summary view
TextView summaryView = (TextView) view.findViewById(R.id.summary);
if (summaryView != null) {
boolean useDefaultSummary = true;
if (isChecked() && mSummaryOn != null) {
summaryView.setText(mSummaryOn);
useDefaultSummary = false;
} else if (!isChecked() && mSummaryOff != null) {
summaryView.setText(mSummaryOff);
useDefaultSummary = false;
}
if (useDefaultSummary) {
final CharSequence summary = getSummary();
if (summary != null) {
summaryView.setText(summary);
useDefaultSummary = false;
}
}
int newVisibility = View.GONE;
if (!useDefaultSummary) {
// Someone has written to it
newVisibility = View.VISIBLE;
}
if (newVisibility != summaryView.getVisibility()) {
summaryView.setVisibility(newVisibility);
}
}
}
/**
* Makes sure the view (and any children) get the enabled state changed.
*/
private void setEnabledStateOnViews(View v, boolean enabled) {
v.setEnabled(enabled);
if (v instanceof ViewGroup) {
final ViewGroup vg = (ViewGroup) v;
for (int i = vg.getChildCount() - 1; i >= 0; i--) {
setEnabledStateOnViews(vg.getChildAt(i), enabled);
}
}
}
}
2.FrameAnimationController类:
package com.sfdj.salebaby.view;
import android.os.Handler;
import android.os.Message;
public class FrameAnimationController {
private static final int MSG_ANIMATE = 1000;
public static final int ANIMATION_FRAME_DURATION = 1000 / 60;
private static final Handler mHandler = new AnimationHandler();
private FrameAnimationController() {
throw new UnsupportedOperationException();
}
public static void requestAnimationFrame(Runnable runnable) {
Message message = new Message();
message.what = MSG_ANIMATE;
message.obj = runnable;
mHandler.sendMessageDelayed(message, ANIMATION_FRAME_DURATION);
}
public static void requestFrameDelay(Runnable runnable, long delay) {
Message message = new Message();
message.what = MSG_ANIMATE;
message.obj = runnable;
mHandler.sendMessageDelayed(message, delay);
}
private static class AnimationHandler extends Handler {
public void handleMessage(Message m) {
switch (m.what) {
case MSG_ANIMATE:
if (m.obj != null) {
((Runnable) m.obj).run();
}
break;
}
}
}
}
3.SwitchButton类:
package com.sfdj.salebaby.view;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.view.ViewParent;
import android.widget.CheckBox;
import com.sfdj.salebaby.R;
public class SwitchButton extends CheckBox {
private Paint mPaint;
private ViewParent mParent;
private Bitmap mBottom;
private Bitmap mCurBtnPic;
private Bitmap mBtnPressed;
private Bitmap mBtnNormal;
private Bitmap mFrame;
private Bitmap mMask;
private RectF mSaveLayerRectF;
private PorterDuffXfermode mXfermode;
private float mFirstDownY; // 首次按下的Y
private float mFirstDownX; // 首次按下的X
private float mRealPos; // 图片的绘制位�?
private float mBtnPos; // 按钮的位�?
private float mBtnOnPos; // �?��打开的位�?
private float mBtnOffPos; // �?��关闭的位�?
private float mMaskWidth;
private float mMaskHeight;
private float mBtnWidth;
private float mBtnInitPos;
private int mClickTimeout;
private int mTouchSlop;
private final int MAX_ALPHA = 255;
private int mAlpha = MAX_ALPHA;
private boolean mChecked = false;
private boolean mBroadcasting;
private boolean mTurningOn;
private PerformClick mPerformClick;
private OnCheckedChangeListener mOnCheckedChangeListener;
private OnCheckedChangeListener mOnCheckedChangeWidgetListener;
private boolean mAnimating;
private final float VELOCITY = 350;
private float mVelocity;
private final float EXTENDED_OFFSET_Y = 15;
private float mExtendOffsetY; // Y轴方向扩大的区域,增大点击区域
private float mAnimationPosition;
private float mAnimatedVelocity;
public SwitchButton(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.checkboxStyle);
}
public SwitchButton(Context context) {
this(context, null);
}
public SwitchButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
private void initView(Context context) {
mPaint = new Paint();
mPaint.setColor(Color.WHITE);
Resources resources = context.getResources();
// get viewConfiguration
mClickTimeout = ViewConfiguration.getPressedStateDuration()
+ ViewConfiguration.getTapTimeout();
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
// get Bitmap
mBottom = BitmapFactory.decodeResource(resources, R.drawable.bottom);
mBtnPressed = BitmapFactory.decodeResource(resources, R.drawable.btn_pressed);
mBtnNormal = BitmapFactory.decodeResource(resources, R.drawable.btn_unpressed);
mFrame = BitmapFactory.decodeResource(resources, R.drawable.frame);
mMask = BitmapFactory.decodeResource(resources, R.drawable.mask);
mCurBtnPic = mBtnNormal;
mBtnWidth = mBtnPressed.getWidth();
mMaskWidth = mMask.getWidth();
mMaskHeight = mMask.getHeight();
mBtnOffPos = mBtnWidth / 2;
mBtnOnPos = mMaskWidth - mBtnWidth / 2;
mBtnPos = mChecked ? mBtnOnPos : mBtnOffPos;
mRealPos = getRealPos(mBtnPos);
final float density = getResources().getDisplayMetrics().density;
mVelocity = (int) (VELOCITY * density + 0.5f);
mExtendOffsetY = (int) (EXTENDED_OFFSET_Y * density + 0.5f);
mSaveLayerRectF = new RectF(0, mExtendOffsetY, mMask.getWidth(), mMask.getHeight()
+ mExtendOffsetY);
mXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
}
@Override
public void setEnabled(boolean enabled) {
mAlpha = enabled ? MAX_ALPHA : MAX_ALPHA / 2;
super.setEnabled(enabled);
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
/**
* 内部调用此方法设置checked状�?,此方法会延迟执行各种回调函数,保证动画的流畅度
*
* @param checked
*/
private void setCheckedDelayed(final boolean checked) {
this.postDelayed(new Runnable() {
@Override
public void run() {
setChecked(checked);
}
}, 10);
}
/**
* <p>
* Changes the checked state of this button.
* </p>
*
* @param checked true to check the button, false to uncheck it
*/
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
mBtnPos = checked ? mBtnOnPos : mBtnOffPos;
mRealPos = getRealPos(mBtnPos);
invalidate();
// Avoid infinite recursions if setChecked() is called from a
// listener
if (mBroadcasting) {
return;
}
mBroadcasting = true;
if (mOnCheckedChangeListener != null) {
mOnCheckedChangeListener.onCheckedChanged(SwitchButton.this, mChecked);
}
if (mOnCheckedChangeWidgetListener != null) {
mOnCheckedChangeWidgetListener.onCheckedChanged(SwitchButton.this, mChecked);
}
mBroadcasting = false;
}
}
/**
* Register a callback to be invoked when the checked state of this button
* changes.
*
* @param listener the callback to call on checked state change
*/
public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
mOnCheckedChangeListener = listener;
}
/**
* Register a callback to be invoked when the checked state of this button
* changes. This callback is used for internal purpose only.
*
* @param listener the callback to call on checked state change
* @hide
*/
void setOnCheckedChangeWidgetListener(OnCheckedChangeListener listener) {
mOnCheckedChangeWidgetListener = listener;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
float x = event.getX();
float y = event.getY();
float deltaX = Math.abs(x - mFirstDownX);
float deltaY = Math.abs(y - mFirstDownY);
switch (action) {
case MotionEvent.ACTION_DOWN:
attemptClaimDrag();
mFirstDownX = x;
mFirstDownY = y;
mCurBtnPic = mBtnPressed;
mBtnInitPos = mChecked ? mBtnOnPos : mBtnOffPos;
break;
case MotionEvent.ACTION_MOVE:
float time = event.getEventTime() - event.getDownTime();
mBtnPos = mBtnInitPos + event.getX() - mFirstDownX;
if (mBtnPos >= mBtnOffPos) {
mBtnPos = mBtnOffPos;
}
if (mBtnPos <= mBtnOnPos) {
mBtnPos = mBtnOnPos;
}
mTurningOn = mBtnPos > (mBtnOffPos - mBtnOnPos) / 2 + mBtnOnPos;
mRealPos = getRealPos(mBtnPos);
break;
case MotionEvent.ACTION_UP:
mCurBtnPic = mBtnNormal;
time = event.getEventTime() - event.getDownTime();
if (deltaY < mTouchSlop && deltaX < mTouchSlop && time < mClickTimeout) {
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
} else {
startAnimation(!mTurningOn);
}
break;
}
invalidate();
return isEnabled();
}
private final class PerformClick implements Runnable {
public void run() {
performClick();
}
}
@Override
public boolean performClick() {
startAnimation(!mChecked);
return true;
}
/**
* Tries to claim the user's drag motion, and requests disallowing any
* ancestors from stealing events in the drag.
*/
private void attemptClaimDrag() {
mParent = getParent();
if (mParent != null) {
mParent.requestDisallowInterceptTouchEvent(true);
}
}
/**
* 将btnPos转换成RealPos
*
* @param btnPos
* @return
*/
private float getRealPos(float btnPos) {
return btnPos - mBtnWidth / 2;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.saveLayerAlpha(mSaveLayerRectF, mAlpha, Canvas.MATRIX_SAVE_FLAG
| Canvas.CLIP_SAVE_FLAG | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
| Canvas.FULL_COLOR_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
// 绘制蒙板
canvas.drawBitmap(mMask, 0, mExtendOffsetY, mPaint);
mPaint.setXfermode(mXfermode);
// 绘制底部图片
canvas.drawBitmap(mBottom, mRealPos, mExtendOffsetY, mPaint);
mPaint.setXfermode(null);
// 绘制边框
canvas.drawBitmap(mFrame, 0, mExtendOffsetY, mPaint);
// 绘制按钮
canvas.drawBitmap(mCurBtnPic, mRealPos, mExtendOffsetY, mPaint);
canvas.restore();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension((int) mMaskWidth, (int) (mMaskHeight + 2 * mExtendOffsetY));
}
private void startAnimation(boolean turnOn) {
mAnimating = true;
mAnimatedVelocity = turnOn ? -mVelocity : mVelocity;
mAnimationPosition = mBtnPos;
new SwitchAnimation().run();
}
private void stopAnimation() {
mAnimating = false;
}
private final class SwitchAnimation implements Runnable {
@Override
public void run() {
if (!mAnimating) {
return;
}
doAnimation();
FrameAnimationController.requestAnimationFrame(this);
}
}
private void doAnimation() {
mAnimationPosition += mAnimatedVelocity * FrameAnimationController.ANIMATION_FRAME_DURATION
/ 1000;
if (mAnimationPosition <= mBtnOnPos) {
stopAnimation();
mAnimationPosition = mBtnOnPos;
setCheckedDelayed(true);
} else if (mAnimationPosition >= mBtnOffPos) {
stopAnimation();
mAnimationPosition = mBtnOffPos;
setCheckedDelayed(false);
}
moveView(mAnimationPosition);
}
private void moveView(float position) {
mBtnPos = position;
mRealPos = getRealPos(mBtnPos);
invalidate();
}
}
五、布局:
1.preference_widget_checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<com.sfdj.salebaby.view.SwitchButton xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center" />
2.preference.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="wrap_content"
android:gravity="center_vertical"
>
<RelativeLayout
android:id="@+id/primary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="6.0dip"
android:layout_marginLeft="20.0dip"
android:layout_marginRight="6.0dip"
android:layout_marginTop="6.0dip"
android:layout_weight="1.0" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/title"
android:layout_below="@+id/title"
android:maxLines="2"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
<LinearLayout
android:id="@+id/widget_frame"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="@dimen/preference_margin"
android:gravity="center"
android:orientation="vertical" />
</LinearLayout>
六、dimen资源:
<!-- switchButton -->
<dimen name="preference_icon_width">50.0dip</dimen>
<dimen name="preference_margin">19.0dip</dimen>
<dimen name="preference_widget_icon_width">48.0dip</dimen>
<dimen name="list_item_height">51.0dip</dimen>
七、raw资源:
八、MyPushMessageReceiver
package com.sfdj.salebaby.push;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.baidu.android.pushservice.PushManager;
import com.baidu.android.pushservice.PushNotificationBuilder;
import com.baidu.frontia.api.FrontiaPushMessageReceiver;
import com.sfdj.salebaby.R;
import com.sfdj.salebaby.activity.MainActivity;
import com.sfdj.salebaby.utils.SPUtil;
/**
* Push消息处理receiver。请编写您需要的回调函数, 一般来说: onBind是必须的,用来处理startWork返回值;
* onMessage用来接收透传消息; onSetTags、onDelTags、onListTags是tag相关操作的回调;
* onNotificationClicked在通知被点击时回调; onUnbind是stopWork接口的返回值回调
*
* 返回值中的errorCode,解释如下: 0 - Success 10001 - Network Problem 30600 - Internal
* Server Error 30601 - Method Not Allowed 30602 - Request Params Not Valid
* 30603 - Authentication Failed 30604 - Quota Use Up Payment Required 30605 -
* Data Required Not Found 30606 - Request Time Expires Timeout 30607 - Channel
* Token Timeout 30608 - Bind Relation Not Found 30609 - Bind Number Too Many
*
* 当您遇到以上返回错误时,如果解释不了您的问题,请用同一请求的返回值requestId和errorCode联系我们追查问题。
*
*/
public class MyPushMessageReceiver extends FrontiaPushMessageReceiver {
/** TAG to Log */
public static final String TAG = MyPushMessageReceiver.class
.getSimpleName();
/**
* 调用PushManager.startWork后,sdk将对push
* server发起绑定请求,这个过程是异步的。绑定请求的结果通过onBind返回。 如果您需要用单播推送,需要把这里获取的channel
* id和user id上传到应用server中,再调用server接口用channel id和user id给单个手机或者用户推送。
*
* @param context
* BroadcastReceiver的执行Context
* @param errorCode
* 绑定接口返回值,0 - 成功
* @param appid
* 应用id。errorCode非0时为null
* @param userId
* 应用user id。errorCode非0时为null
* @param channelId
* 应用channel id。errorCode非0时为null
* @param requestId
* 向服务端发起的请求id。在追查问题时有用;
* @return none
*/
@Override
public void onBind(Context context, int errorCode, String appid,
String userId, String channelId, String requestId) {
String responseString = "onBind errorCode=" + errorCode + " appid="
+ appid + " userId=" + userId + " channelId=" + channelId
+ " requestId=" + requestId;
Log.e(TAG, responseString);
// 绑定成功,设置已绑定flag,可以有效的减少不必要的绑定请求
if (errorCode == 0) {
Utils.setBind(context, true);// SPUtil.get(context,
// "baiduId")//SPUtil.get(context,
// "channelId")
}
SPUtil.set(context, "baiduId", appid);
SPUtil.set(context, "channelId", channelId);
// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, responseString);
}
// 判断是否开启了推送功能
public static boolean isPushEnabled(Context context) {
boolean flag = false;
if (PushManager.isPushEnabled(context)) {
flag = true;
return flag;
}
return flag;
}
// 关闭推送消息
public static void stopWork(Context context) {
PushManager.stopWork(context);
}
// 打开推送消息
public static void resumeWork(Context context) {
PushManager.resumeWork(context);
}
/**
* 接收透传消息的函数。
*
* @param context
* 上下文
* @param message
* 推送的消息
* @param customContentString
* 自定义内容,为空或者json字符串
*/
@Override
public void onMessage(Context context, String message,
String customContentString) {
String messageString = "透传消息 message=\"" + message
+ "\" customContentString=" + customContentString;
Log.e(TAG, messageString);
// 自定义内容获取方式,mykey和myvalue对应透传消息推送时自定义内容中设置的键和值
if (!TextUtils.isEmpty(customContentString)) {
JSONObject customJson = null;
try {
customJson = new JSONObject(customContentString);
String myvalue = null;
if (!customJson.isNull("mykey")) {
myvalue = customJson.getString("mykey");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//关闭或打开推送声音
NotificationManager nm = (NotificationManager) context
.getSystemService(context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
SPUtil.get(context, "message"),
System.currentTimeMillis());
PendingIntent pendingIntent = PendingIntent.getActivity(context,
0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context, null,
SPUtil.get(context, "message"), pendingIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
if(SPUtil.get(context, "issound").equals("false")){
notification.sound = null;
}else{
notification.sound=Uri.parse("android.resource://com.sfdj.salebaby/raw/yes");
}
nm.notify(1, notification);
SPUtil.set(context, "message", message);
Log.e(TAG, "nmnmnmnmn");
// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, messageString);
}
/**
* 接收通知点击的函数。注:推送通知被用户点击前,应用无法通过接口获取通知的内容。
*
* @param context
* 上下文
* @param title
* 推送的通知的标题
* @param description
* 推送的通知的描述
* @param customContentString
* 自定义内容,为空或者json字符串
*/
@Override
public void onNotificationClicked(Context context, String title,
String description, String customContentString) {
String notifyString = "通知点击 title=\"" + title + "\" description=\""
+ description + "\" customContent=" + customContentString;
Log.e(TAG, notifyString);
// 自定义内容获取方式,mykey和myvalue对应通知推送时自定义内容中设置的键和值
if (!TextUtils.isEmpty(customContentString)) {
JSONObject customJson = null;
try {
customJson = new JSONObject(customContentString);
String myvalue = null;
if (!customJson.isNull("mykey")) {
myvalue = customJson.getString("mykey");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent i = new Intent(context, MainActivity.class);
i.setComponent(new ComponentName("com.sfdj.salebaby",
"com.sfdj.salebaby.activity.MainActivity"));
i.putExtra("str", customContentString);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);// 关键的一步,设置启动模式
context.startActivity(i);
// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
// updateContent(context, notifyString);
}
/**
* setTags() 的回调函数。
*
* @param context
* 上下文
* @param errorCode
* 错误码。0表示某些tag已经设置成功;非0表示所有tag的设置均失败。
* @param successTags
* 设置成功的tag
* @param failTags
* 设置失败的tag
* @param requestId
* 分配给对云推送的请求的id
*/
@Override
public void onSetTags(Context context, int errorCode,
List<String> sucessTags, List<String> failTags, String requestId) {
String responseString = "onSetTags errorCode=" + errorCode
+ " sucessTags=" + sucessTags + " failTags=" + failTags
+ " requestId=" + requestId;
Log.d(TAG, responseString);
// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, responseString);
}
/**
* delTags() 的回调函数。
*
* @param context
* 上下文
* @param errorCode
* 错误码。0表示某些tag已经删除成功;非0表示所有tag均删除失败。
* @param successTags
* 成功删除的tag
* @param failTags
* 删除失败的tag
* @param requestId
* 分配给对云推送的请求的id
*/
@Override
public void onDelTags(Context context, int errorCode,
List<String> sucessTags, List<String> failTags, String requestId) {
String responseString = "onDelTags errorCode=" + errorCode
+ " sucessTags=" + sucessTags + " failTags=" + failTags
+ " requestId=" + requestId;
Log.d(TAG, responseString);
// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, responseString);
}
/**
* listTags() 的回调函数。
*
* @param context
* 上下文
* @param errorCode
* 错误码。0表示列举tag成功;非0表示失败。
* @param tags
* 当前应用设置的所有tag。
* @param requestId
* 分配给对云推送的请求的id
*/
@Override
public void onListTags(Context context, int errorCode, List<String> tags,
String requestId) {
String responseString = "onListTags errorCode=" + errorCode + " tags="
+ tags;
Log.d(TAG, responseString);
// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, responseString);
}
/**
* PushManager.stopWork() 的回调函数。
*
* @param context
* 上下文
* @param errorCode
* 错误码。0表示从云推送解绑定成功;非0表示失败。
* @param requestId
* 分配给对云推送的请求的id
*/
@Override
public void onUnbind(Context context, int errorCode, String requestId) {
String responseString = "onUnbind errorCode=" + errorCode
+ " requestId = " + requestId;
Log.d(TAG, responseString);
// 解绑定成功,设置未绑定flag,
if (errorCode == 0) {
Utils.setBind(context, false);
}
// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, responseString);
}
private void updateContent(Context context, String content) {
Log.d(TAG, "updateContent" + content);
// String logText = "" + Utils.logStringCache;
//
// if (!logText.equals("")) {
// logText += "\n";
// }
//
// SimpleDateFormat sDateFormat = new SimpleDateFormat("HH-mm-ss");
// logText += sDateFormat.format(new Date()) + ": ";
// logText += content;
//
// Utils.logStringCache = logText;a
//
// Intent intent = new Intent();
// intent.setClass(context.getApplicationContext(),
// PushDemoActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Log.e("YQY", "FLAG_ACTIVITY_NEW_TASK");
// context.getApplicationContext().startActivity(intent);
}
}