标签:
注册与下载sdk略过,直接贴代码
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.monta.paopao" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <!-- 去掉READ_LOGS权限--> <uses-permission android:name="android.permission.READ_LOGS" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <!--开机启动添加 --> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.monta.paopao.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.monta.paopao.TestActivity" />
<!-- 测试用,可删除 --> <activity android:name="com.monta.paopao.TwoActivity" /> <receiver android:name="com.umeng.message.NotificationProxyBroadcastReceiver" android:exported="false" > </receiver> <receiver android:name="com.umeng.message.RegistrationReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PACKAGE_REMOVED" /> <data android:scheme="package" /> </intent-filter> </receiver> <receiver android:name="com.umeng.message.UmengBroadcastReceiver" > <intent-filter> <action android:name="org.agoo.android.intent.action.RECEIVE" /> </intent-filter> <intent-filter> <action android:name="com.monta.paopao.intent.action.COMMAND" /> </intent-filter> <intent-filter> <action android:name="org.agoo.android.intent.action.RE_ELECTION_V2" /> </intent-filter> </receiver> <service android:name="com.umeng.message.UmengService" android:exported="true" android:process=":umengService_v1" > <intent-filter> <action android:name="com.monta.paopao.intent.action.START" /> </intent-filter> <intent-filter> <action android:name="com.monta.paopao.intent.action.COCKROACH" /> </intent-filter> <intent-filter> <action android:name="org.agoo.android.intent.action.PING" /> </intent-filter> </service> <service android:name="org.android.agoo.service.ElectionService" android:exported="true" android:process=":umengService_v1" > <intent-filter> <action android:name="org.agoo.android.intent.action.ELECTION_V2" /> </intent-filter> </service> <service android:name="com.umeng.message.UmengIntentService" /> <meta-data android:name="UMENG_APPKEY" android:value="****" > </meta-data> <meta-data android:name="UMENG_MESSAGE_SECRET" android:value="*******" > </meta-data> <meta-data android:name="UMENG_CHANNEL" android:value="Umeng" > </meta-data> <!-- If you donot want to use the standard notification bar in SDK, you can define IntentService instead to handle message. --> <!-- 自定义消息接收service -->
<service android:name="com.monta.paopao.MyPushIntentService" /> <service android:name="com.umeng.message.UmengDownloadResourceService" > </service>
<!-- startReceiver 用来设置开机启动 消息推送的接收service -->
<receiver android:name="com.monta.paopao.StartReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </receiver> </application>
其中com.monta.paopao 为推送应用包名。
接下来是自定义的 application
package com.monta.paopao; import android.app.Application; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.RemoteViews; import android.widget.Toast; import com.monta.paopao.R; import com.umeng.message.PushAgent; import com.umeng.message.UTrack; import com.umeng.message.UmengMessageHandler; import com.umeng.message.UmengNotificationClickHandler; import com.umeng.message.UmengRegistrar; import com.umeng.message.entity.UMessage; public class MyApplication extends Application { private static final String TAG = MyApplication.class.getName(); private PushAgent mPushAgent; @Override public void onCreate() { mPushAgent = PushAgent.getInstance(this); mPushAgent.setDebugMode(true); /** * 该Handler是在IntentService中被调用,故 * 1. 如果需启动Activity,需添加Intent.FLAG_ACTIVITY_NEW_TASK * 2. IntentService里的onHandleIntent方法是并不处于主线程中,因此,如果需调用到主线程,需如下所示; * 或者可以直接启动Service * */ UmengMessageHandler messageHandler = new UmengMessageHandler(){ @Override public void dealWithCustomMessage(final Context context, final UMessage msg) { new Handler(getMainLooper()).post(new Runnable() { @Override public void run() { UTrack.getInstance(getApplicationContext()).trackMsgClick(msg); Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show(); } }); } @Override public Notification getNotification(Context context, UMessage msg) { switch (msg.builder_id) { case 1: NotificationCompat.Builder builder = new NotificationCompat.Builder(context); RemoteViews myNotificationView = new RemoteViews(context.getPackageName(), R.layout.notification_view); myNotificationView.setTextViewText(R.id.notification_title, msg.title); myNotificationView.setTextViewText(R.id.notification_text, msg.text); myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg)); myNotificationView.setImageViewResource(R.id.notification_small_icon, getSmallIconId(context, msg)); builder.setContent(myNotificationView); builder.setAutoCancel(true); Notification mNotification = builder.build(); //由于Android v4包的bug,在2.3及以下系统,Builder创建出来的Notification,并没有设置RemoteView,故需要添加此代码 mNotification.contentView = myNotificationView; return mNotification; default: //默认为0,若填写的builder_id并不存在,也使用默认。 return super.getNotification(context, msg); } } }; mPushAgent.setMessageHandler(messageHandler); /** * 该Handler是在BroadcastReceiver中被调用,故 * 如果需启动Activity,需添加Intent.FLAG_ACTIVITY_NEW_TASK * */ UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler(){ @Override public void dealWithCustomAction(Context context, UMessage msg) { Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show(); } }; mPushAgent.setNotificationClickHandler(notificationClickHandler); String device_token = UmengRegistrar.getRegistrationId(this); Log.i("device_token", device_token); } }
完全照搬推送demo中的application
接下来是重头戏 mainActivity
/** * Copyright (C) 2013 Umeng, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.monta.paopao; import java.util.ArrayList; import java.util.List; import java.util.Set; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.Notification; import android.app.ProgressDialog; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RemoteViews; import android.widget.TextView; import android.widget.Toast; import com.monta.paopao.R; import com.umeng.message.ALIAS_TYPE; import com.umeng.message.IUmengRegisterCallback; import com.umeng.message.IUmengUnregisterCallback; import com.umeng.message.PushAgent; import com.umeng.message.UTrack; import com.umeng.message.UmengMessageHandler; import com.umeng.message.UmengNotificationClickHandler; import com.umeng.message.UmengRegistrar; import com.umeng.message.entity.UMessage; import com.umeng.message.tag.TagManager; public class MainActivity extends Activity { protected static final String TAG = MainActivity.class.getSimpleName(); //------------设置标签等控件,demo中有,暂时先不考虑------------// private EditText edTag, edAlias; private TextView tvStatus, infoTextView; private ImageView btnEnable; private Button btnaAddTag, btnListTag, btnAddAlias; private ProgressDialog dialog; //------------设置标签等控件,demo中有,暂时先不考虑------------// private PushAgent mPushAgent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); printKeyValue(); mPushAgent = PushAgent.getInstance(this); mPushAgent.onAppStart(); mPushAgent.enable(mRegisterCallback); //------------设置标签等控件,demo中有,暂时先不考虑------------// tvStatus = (TextView) findViewById(R.id.tvStatus); btnEnable = (ImageView) findViewById(R.id.btnEnable); btnaAddTag = (Button) findViewById(R.id.btnAddTags); btnAddAlias = (Button) findViewById(R.id.btnAddAlias); btnListTag = (Button) findViewById(R.id.btnListTags); infoTextView = (TextView)findViewById(R.id.info); edTag = (EditText) findViewById(R.id.edTag); edAlias = (EditText) findViewById(R.id.edAlias); tvStatus.setOnClickListener(clickListener); btnEnable.setOnClickListener(clickListener); btnaAddTag.setOnClickListener(clickListener); btnListTag.setOnClickListener(clickListener); btnAddAlias.setOnClickListener(clickListener); updateStatus(); //------------设置标签等控件,demo中有,暂时先不考虑------------// //------------重点!!! 以下两行设置通过myPushIntentService来处理推送来的消息,其他代码块暂时不做处理------------// mPushAgent.setPushIntentServiceClass(MyPushIntentService.class); mPushAgent.getMessageHandler(); } @Override protected void onDestroy() { Log.d("-------------------------", "onDestroy"); super.onDestroy(); } private void printKeyValue() { //获取自定义参数 Bundle bun = getIntent().getExtras(); if (bun != null) { Set<String> keySet = bun.keySet(); for (String key : keySet) { String value = bun.getString(key); Log.i(TAG, key + ":" + value); } } } private void switchPush(){ String info = String.format("enabled:%s isRegistered:%s", mPushAgent.isEnabled(), mPushAgent.isRegistered()); Log.i(TAG, "switch Push:" + info); btnEnable.setClickable(false); if (mPushAgent.isEnabled() || UmengRegistrar.isRegistered(MainActivity.this)) { mPushAgent.disable(mUnregisterCallback); } else { mPushAgent.enable(mRegisterCallback); } } private void updateStatus() { String pkgName = getApplicationContext().getPackageName(); String info = String.format("enabled:%s isRegistered:%s DeviceToken:%s", mPushAgent.isEnabled(), mPushAgent.isRegistered(), mPushAgent.getRegistrationId()); tvStatus.setText("应用包名:"+pkgName+"\n"+info); btnEnable.setImageResource(mPushAgent.isEnabled()?R.drawable.open_button:R.drawable.close_button); btnEnable.setClickable(true); copyToClipBoard(); Log.i(TAG, "updateStatus:" + String.format("enabled:%s isRegistered:%s", mPushAgent.isEnabled(), mPushAgent.isRegistered())); Log.i(TAG, "============================="); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("NewApi") @SuppressWarnings("deprecation") private void copyToClipBoard() { if (Build.VERSION.SDK_INT<11) return; String deviceToken = mPushAgent.getRegistrationId(); if (!TextUtils.isEmpty(deviceToken)) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(deviceToken); toast("DeviceToken已经复制到剪贴板了"); } } // sample code to add tags for the device / user private void addTag() { String tag = edTag.getText().toString(); if (TextUtils.isEmpty(tag)) { toast("请先输入Tag"); return; } if (!mPushAgent.isRegistered()) { toast("抱歉,还未注册"); return; } showLoading(); new AddTagTask(tag).execute(); hideInputKeyboard(); } // sample code to add tags for the device / user private void listTags() { if (!mPushAgent.isRegistered()) { toast("抱歉,还未注册"); return; } showLoading(); new ListTagTask().execute(); } // sample code to add alias for the device / user private void addAlias() { String alias = edAlias.getText().toString(); if (TextUtils.isEmpty(alias)) { toast("请先输入Alias"); return; } if (!mPushAgent.isRegistered()) { toast("抱歉,还未注册"); return; } showLoading(); new AddAliasTask(alias).execute(); hideInputKeyboard(); } public void showLoading(){ if (dialog == null){ dialog = new ProgressDialog(this); dialog.setMessage("Loading"); } dialog.show(); } public void updateInfo(String info){ if (dialog != null && dialog.isShowing()) dialog.dismiss(); infoTextView.setText(info); } public OnClickListener clickListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (v == btnaAddTag){ addTag(); }else if (v == btnAddAlias){ addAlias(); }else if (v == btnListTag){ Intent intent = new Intent(getApplicationContext(), TwoActivity.class); startActivity(intent); finish(); // listTags(); }else if (v == btnEnable){ switchPush(); }else if (v == tvStatus) { updateStatus(); } } }; public Handler handler = new Handler(); public IUmengRegisterCallback mRegisterCallback = new IUmengRegisterCallback() { @Override public void onRegistered(String registrationId) { // TODO Auto-generated method stub handler.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub updateStatus(); } }); } }; public IUmengUnregisterCallback mUnregisterCallback = new IUmengUnregisterCallback() { @Override public void onUnregistered(String registrationId) { // TODO Auto-generated method stub handler.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub updateStatus(); } }); } }; private Toast mToast; public void toast(String str){ if (mToast == null) mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT); mToast.setText(str); mToast.show(); } class AddTagTask extends AsyncTask<Void, Void, String>{ String tagString; String[] tags; public AddTagTask(String tag) { // TODO Auto-generated constructor stub tagString = tag; tags = tagString.split(","); } @Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub try { TagManager.Result result = mPushAgent.getTagManager().add(tags); Log.d(TAG, result.toString()); return result.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { edTag.setText(""); updateInfo("Add Tag:\n" + result); } } class AddAliasTask extends AsyncTask<Void, Void, Boolean>{ String alias; public AddAliasTask(String aliasString) { // TODO Auto-generated constructor stub this.alias = aliasString; } protected Boolean doInBackground(Void... params) { try { return mPushAgent.addAlias(alias, ALIAS_TYPE.SINA_WEIBO); } catch (Exception e) { e.printStackTrace(); } return false; } @Override protected void onPostExecute(Boolean result) { if (Boolean.TRUE.equals(result)) Log.i(TAG, "alias was set successfully."); edAlias.setText(""); updateInfo("Add Alias:" + (result?"Success":"Fail")); } } class ListTagTask extends AsyncTask<Void , Void, List<String>>{ @Override protected List<String> doInBackground(Void... params) { List<String> tags = new ArrayList<String>(); try { tags = mPushAgent.getTagManager().list(); Log.d(TAG, String.format("list tags: %s", TextUtils.join(",", tags))); } catch (Exception e) { e.printStackTrace(); } return tags; } @Override protected void onPostExecute(List<String> result) { if (result != null) { StringBuilder info = new StringBuilder(); info.append("Tags:\n"); for (int i=0; i<result.size(); i++){ String tag = result.get(i); info.append(tag+"\n"); } info.append("\n"); updateInfo(info.toString()); } updateInfo(""); } } public void hideInputKeyboard() { ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(getCurrentFocus() .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } }
接下来是自定义的service ,用于接收处理推送来的消息。
package com.monta.paopao; import org.android.agoo.client.BaseConstants; import org.json.JSONObject; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.widget.RemoteViews; import com.umeng.common.message.Log; import com.umeng.message.UmengBaseIntentService; import com.umeng.message.entity.UMessage; /** * Developer defined push intent service. * Remember to call {@link com.umeng.message.PushAgent#setPushIntentServiceClass(Class)}. * @author lucas * */ public class MyPushIntentService extends UmengBaseIntentService{ private static final String TAG = MyPushIntentService.class.getName(); @Override protected void onMessage(Context context, Intent intent) { Log.d("onMessage", "onMessageonMessageonMessageonMessageonMessageonMessageonMessageonMessage"); super.onMessage(context, intent); try { String message = intent.getStringExtra(BaseConstants.MESSAGE_BODY); UMessage msg = new UMessage(new JSONObject(message)); android.util.Log.d(TAG, "-----------------------------"); Log.d(TAG, "message="+"----------------------------------"); Log.d(TAG, "message="+message); Log.d(TAG, "custom="+msg.custom); Log.d(TAG, "message="+"----------------------------------"); android.util.Log.d(TAG, "-----------------------------"); } catch (Exception e) { Log.e(TAG, e.getMessage()); } } }
经过测试,服务器推送来的消息可以通过这个MyPushIntentService onMessage方法中接收到,弹出消息框等问题待下一步进行处理。
接下来就是最后一步,设置开机启动推送接收服务MyPushIntentService ,通过广播接收者StartReceiver实现:
package com.monta.paopao; import com.umeng.message.PushAgent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class StartReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("--------------------", "开机启动楼~~~~"); PushAgent mPushAgent = PushAgent.getInstance(context); mPushAgent.onAppStart(); mPushAgent.setPushIntentServiceClass(MyPushIntentService.class); mPushAgent.getMessageHandler(); } }
资源文档等仍为原demo,至此基本的android推送自定义接收处理完成,更深入的处理学习理解完成后再贴出code。
标签:
原文地址:http://www.cnblogs.com/montahan/p/4268410.html