JPush推送
来源:互联网 发布:模拟退火算法应用实例 编辑:程序博客网 时间:2024/05/16 13:54
在AndroidManifest.xml加入以下代码:
<!-- Required SDK核心功能--> <activity android:name="cn.jpush.android.ui.PushActivity" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.NoTitleBar" android:exported="false"> <intent-filter> <action android:name="cn.jpush.android.ui.PushActivity" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="com.shipping" /> </intent-filter> </activity> <!-- Required SDK核心功能 --> <service android:name="cn.jpush.android.service.DownloadService" android:enabled="true" android:exported="false" > </service> <!-- ANT FALG END1 --> <!-- Required SDK 核心功能 --> <service android:name="cn.jpush.android.service.PushService" android:enabled="true" android:exported="false" > <intent-filter> <action android:name="cn.jpush.android.intent.REGISTER" /> <action android:name="cn.jpush.android.intent.REPORT" /> <action android:name="cn.jpush.android.intent.PushService" /> <action android:name="cn.jpush.android.intent.PUSH_TIME" /> </intent-filter> </service> <!-- since 1.8.0 option 可选项。用于同一设备中不同应用的JPush服务相互拉起的功能。 --> <!-- 若不启用该功能可删除该组件,将不拉起其他应用也不能被其他应用拉起 --> <service android:name="cn.jpush.android.service.DaemonService" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="cn.jpush.android.intent.DaemonService" /> <category android:name="com.shipping" /> </intent-filter> </service> <!-- Required SDK核心功能--> <receiver android:name="cn.jpush.android.service.PushReceiver" android:enabled="true" android:exported="false"> <intent-filter android:priority="1000"> <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY" /> <!--Required 显示通知栏 --> <category android:name="com.shipping" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.USER_PRESENT" /> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> <!-- Optional --> <intent-filter> <action android:name="android.intent.action.PACKAGE_ADDED" /> <action android:name="android.intent.action.PACKAGE_REMOVED" /> <data android:scheme="package" /> </intent-filter> </receiver> <!-- Required SDK核心功能 --> <receiver android:name="cn.jpush.android.service.AlarmReceiver" android:exported="false"/> <!-- User defined. For test only 用户自定义的广播接收器 --> <receiver android:name="com.shipping.service.TalkReceiver" android:exported="false" android:enabled="true" > <intent-filter> <action android:name="cn.jpush.android.intent.REGISTRATION" /> <!--Required 用户注册SDK的intent--> <action android:name="cn.jpush.android.intent.UNREGISTRATION" /> <action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" /> <!--Required 用户接收SDK消息的intent--> <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" /> <!--Required 用户接收SDK通知栏信息的intent--> <action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" /> <!--Required 用户打开自定义通知栏的intent--> <action android:name="cn.jpush.android.intent.ACTION_RICHPUSH_CALLBACK" /> <!--Optional 用户接受Rich Push Javascript 回调函数的intent--> <action android:name="cn.jpush.android.intent.CONNECTION" /><!-- 接收网络变化 连接/断开 since 1.6.3 --> <category android:name="com.shipping" /> </intent-filter> </receiver> <!-- Required . Enable it you can get statistics data with channel --> <meta-data android:name="JPUSH_CHANNEL" android:value="developer-default" /> <meta-data android:name="JPUSH_APPKEY" android:value="5a603b9fd7831099a1bfe468" /> </application> <uses-permission android:name="com.shipping.permission.JPUSH_MESSAGE" /> <uses-permission android:name="android.permission.SET_WALLPAPER" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />接收推送消息的Receiver
package com.shipping.service;import org.json.JSONException;import org.json.JSONObject;import com.shipping.activity.ship.MyInquiryPalletDetailActivity;import com.shipping.activity.ship.MyInquiryPalletDlActivity;import com.shipping.app.IntentAction;import com.shippingframework.app.Config;import com.shippingframework.sharedpreferences.AppSharedPreferences;import com.shippingframework.utils.JsonUtil;import com.shippingframework.utils.L;import cn.jpush.android.api.JPushInterface;import android.app.NotificationManager;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.util.Log;public class TalkReceiver extends BroadcastReceiver {private static final String TAG = "TalkReceiver";private NotificationManager nm;@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubif (null == nm) {nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);}Bundle bundle = intent.getExtras();// L.i(TAG, "onReceive - " + intent.getAction() + ", extras: " +// AndroidUtil.printBundle(bundle));L.i(TAG, "onReceive - " + intent.getAction());if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {L.i(TAG, "JPush用户注册成功");} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {L.i(TAG, "接受到推送下来的自定义消息");// Push Talk messages are push down by custom message formatprocessCustomMessage(context, bundle);} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {L.i(TAG, "接受到推送下来的通知");} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {L.i(TAG, "用户点击打开了通知");//Intent i = new Intent(//context,//MyInquiryPalletDlActivity.class);//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//context.startActivity(i);} else {L.i(TAG, "Unhandled intent - " + intent.getAction());}} private void processCustomMessage(Context context, Bundle bundle) { String title = bundle.getString(JPushInterface.EXTRA_TITLE); String message = bundle.getString(JPushInterface.EXTRA_MESSAGE); Log.d(TAG, "[processCustomMessage]msg_content: " + bundle.getString(JPushInterface.EXTRA_MESSAGE)); Log.d(TAG, "[processCustomMessage]content_type: " + bundle.getString(JPushInterface.EXTRA_CONTENT_TYPE)); Log.d(TAG, "[processCustomMessage]extras: " + bundle.getString(JPushInterface.EXTRA_EXTRA)); Log.d(TAG, "[processCustomMessage]title: " + bundle.getString(JPushInterface.EXTRA_TITLE)); if (title.equals("")||title.length()<1) { L.i(TAG, "Unexpected: empty title (friend). Give up"); return; } boolean needIncreaseUnread = true; // if (title.equalsIgnoreCase(Config.myName)) {// Logger.d(TAG, "Message from myself. Give up");// needIncreaseUnread = false;// if (!Config.IS_TEST_MODE) {// return;// }// } String friendName=""; int friendId=0; int notificationId=0; // String channel = null; String extras = bundle.getString(JPushInterface.EXTRA_EXTRA); try { JSONObject extrasJson = new JSONObject(extras); friendName=JsonUtil.getString(extrasJson, "SendNickName"); friendId=JsonUtil.getInt(extrasJson, "toUserId"); notificationId=JsonUtil.getInt(extrasJson, "ChatRecordId"); } catch (Exception e) { L.i(TAG, "Unexpected: extras is not a valid json"+e); } // Send message to UI (Webview) only when UI is up if (!Config.isBackground) { Intent msgIntent = new Intent(IntentAction.MESSAGE_RECEIVED_ACTION); msgIntent.putExtra(IntentAction.CHAT_KEY_MESSAGE, message); msgIntent.putExtra(IntentAction.CHAT_KEY_TITLE, title);// if (null != channel) {// msgIntent.putExtra(Constants.KEY_CHANNEL, channel);// } JSONObject all = new JSONObject(); try { // all.put(IntentAction.CHAT_KEY_TITLE, title); all.put(IntentAction.CHAT_KEY_MESSAGE, message); //all.put(IntentAction.CHAT_KEY_EXTRAS, new JSONObject(extras)); all.put(IntentAction.CHAT_KEY_EXTRAS, new JSONObject(extras)); } catch (JSONException e) { } L.i(TAG, "---------all="+all.toString()); msgIntent.putExtra("all", all.toString()); context.sendBroadcast(msgIntent); } AppSharedPreferences appSP=new AppSharedPreferences(context,AppSharedPreferences.CHATTING_SHAREPRE_FILE);// String currentChatting = appSP.getChattingCurrentId(); if ((friendId+"").equalsIgnoreCase(currentChatting)) { L.d(TAG, "Is now chatting with - " + friendId + ". Dont show notificaiton."); return; } NotificationHelper.showMessageNotification(context, nm, friendId,friendName, notificationId,message); } // When received message, increase unread number for Recent Chat// private void unreadMessage(final String friend, final String channel) {// new Thread() {// public void run() {// String chattingFriend = null;// //if (StringUtils.isEmpty(channel)) {// chattingFriend = friend;// //}// // Map<String, String> params = new HashMap<String, String>();// params.put("udid", Config.udid);// params.put("friend", chattingFriend);// params.put("channel_name", channel);// // try {// HttpHelper.post(Constants.PATH_UNREAD, params);// } catch (Exception e) {// Logger.e(TAG, "Call pushtalk api to report unread error", e);// }// }// }.start();// } }
用户登录app成功后,把UserIntId发送给极光推送的后台,后边就可以给这个用户推送消息
package com.shipping.activity;import java.util.Set;import android.annotation.SuppressLint;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import cn.jpush.android.api.JPushInterface;import cn.jpush.android.api.TagAliasCallback;import com.shipping.R;import com.shippingframework.entity.UserOnlineEntity;import com.shippingframework.http.ResponseInfo;import com.shippingframework.services.UserService;import com.shippingframework.sharedpreferences.AppSharedPreferences;import com.shippingframework.utils.L;import com.shippingframework.utils.T;import com.shippingframework.utils.TextViewUtil;import com.shippingframework.utils.ValidateUtil;public class LoginActivity extends ShipBaseActivity {// button layoutprivate TextView login_forget_password;private TextView goto_register;private EditText login_account;private EditText login_password;private Button btn_login;/** * 用户级别的配置文件 * */private AppSharedPreferences userSP;private AppSharedPreferences appSP;private static final int LOGIN_COMPLETE = 1;private String uAccount = "";private String uPassword = "";private String TAG="LoginActivity";private static final int MSG_SET_ALIAS = 1001;private static final int MSG_SET_TAGS = 1002;private int UserIntId=0;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);context = this;title = "登录";// 设置视图setContentView(R.layout.activity_login);// 获得实例对象userSP = new AppSharedPreferences(context,AppSharedPreferences.USER_SHAREPRE_FILE);appSP = new AppSharedPreferences(context,AppSharedPreferences.APP_SHAREPRE_FILE);InitView();InitData();}@Overrideprotected void InitView() {super.InitView();login_account = (EditText) findViewById(R.id.login_account);btn_login = (Button) findViewById(R.id.btn_login);login_password = (EditText) findViewById(R.id.login_password);login_forget_password = (TextView) findViewById(R.id.Login_forget_password);goto_register = (TextView) findViewById(R.id.goto_register);TextViewUtil.setFlagsUnderline(login_forget_password);}@Overrideprotected void InitData() {// TODO Auto-generated method stubsuper.InitData();// 登录btn_login.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubuAccount = login_account.getText().toString().trim();uPassword = login_password.getText().toString().trim();Login(uAccount, uPassword);}});// 忘记密码login_forget_password.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO 自动生成的方法存根 startActivity(new Intent(context,ForgetPasswordActivity.class));goFinish();}});// 用户注册goto_register.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO 自动生成的方法存根startActivity(new Intent(context, RegisterActivity.class));goFinish();}});login_account.setText(appSP.getAppDefaultAccount());login_password.setText(appSP.getAppDefaultPwd());Intent intent = getIntent(); // 用于激活它的意图对象if (intent != null) {String phone = intent.getStringExtra("phone");String password = intent.getStringExtra("password");if (phone != null && !phone.equals("")) {login_account.setText(phone);if (password != null && !password.equals("")) {login_password.setText(password);}}}// 实现自动登录uAccount = login_account.getText().toString().trim();uPassword = login_password.getText().toString().trim();if (uAccount != null && !uAccount.equals("") && uPassword != null&& !uPassword.equals("")) {// if (StringUtil.isMobileNO(mAccount)) {Login(uAccount, uPassword);// }}}protected void Login(final String uAccount, final String uPassword) {if (uAccount != null && !uAccount.equals("") && uPassword != null&& !uPassword.equals("")) {if(ValidateUtil.IsMobile(uAccount)){UserService userService = new UserService(context);loading.show();userService.Login(uAccount, uPassword, mHandler);}else{T.show(context, "帐号格式不正确");}} else {T.show(context, "账户和密码不能为空");}}Handler mHandler = new Handler() {@SuppressLint("HandlerLeak")public void handleMessage(android.os.Message msg) {responseInfo = (ResponseInfo<?>) msg.obj;loading.cancel();switch (msg.what) {case LOGIN_COMPLETE: {if (responseInfo != null) {if (responseInfo.success) {UserOnlineEntity userOnline = (UserOnlineEntity) responseInfo.t;if (userOnline != null&& !userOnline.getUserId().equals("")&& userOnline.getUserId().length() > 0) {resetAliasAndTags();T.show(context, "登录成功"); } else {T.show(context, "登录失败");}goFinish();} else {T.show(context, responseInfo.message);}} else {T.show(context, "服务器请求无响应");}}break;default:break;}};};public void goFinish() {this.finish();}private void resetAliasAndTags() {L.i(TAG, "----------------------------------resetAliasAndTags begin");// reset to jpush// JPushInterface.setAliasAndTags(ChattingActivity.this, UserIntId+"",// null, new TagAliasCallback() {//// @Override// public void gotResult(int code, String alias, Set<String> tags) {// L.i(TAG, "[TagAliasCallback], code: " + code);// L.i(TAG, "[TagAliasCallback], alias: " + alias);// L.i(TAG, "[TagAliasCallback], tags: " + tags);// }// });UserIntId = userSP.getUserIntId();L.i(TAG,"----------------------------------resetAliasAndTags UserIntId="+ UserIntId);if(UserIntId>0){// 调用JPush API设置AliasjpushHandler.sendMessage(jpushHandler.obtainMessage(MSG_SET_ALIAS,UserIntId + ""));}L.i(TAG, "----------------------------------resetAliasAndTags end");}private final TagAliasCallback mAliasCallback = new TagAliasCallback() {@Overridepublic void gotResult(int code, String alias, Set<String> tags) {L.i(TAG, "[TagAliasCallback], code: " + code);L.i(TAG, "[TagAliasCallback], alias: " + alias);L.i(TAG, "[TagAliasCallback], tags: " + tags);String logs;switch (code) {case 0:logs = "Set tag and alias success";L.i(TAG, logs);break;case 6002:logs = "Failed to set alias and tags due to timeout. Try again after 60s.";L.i(TAG, logs);jpushHandler.sendMessageDelayed(jpushHandler.obtainMessage(MSG_SET_ALIAS, alias),1000 * 60);break;default:logs = "Failed with errorCode = " + code;L.i(TAG, logs);}// T.show(getApplicationContext(),logs);}};private final Handler jpushHandler = new Handler() {@Overridepublic void handleMessage(android.os.Message msg) {super.handleMessage(msg);switch (msg.what) {case MSG_SET_ALIAS:L.i(TAG, "Set alias in handler.");JPushInterface.setAliasAndTags(getApplicationContext(),(String) msg.obj, null, mAliasCallback);break;// case MSG_SET_TAGS:// Log.d(TAG, "Set tags in handler.");// JPushInterface.setAliasAndTags(getApplicationContext(), null,// (Set<String>) msg.obj, mTagsCallback);// break;default:L.i(TAG, "Unhandled msg - " + msg.what);}}};}
在主Activity中即
<application android:name="com.shipping.application.ShippingApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/NormalTheme" > <activity android:name="com.shipping.activity.WelcomeActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
的onResume / onPause添加
JPushInterface.onResume(
this
);和
JPushInterface.onPause(
this
);
package com.shipping.activity;import cn.jpush.android.api.JPushInterface;import com.shipping.R;import com.shipping.app.App;import com.shipping.guide.GuideActivity;import com.shippingframework.activity.BaseActivity;import com.shippingframework.services.TokenService;import com.shippingframework.services.UserService;import com.shippingframework.sharedpreferences.AppSharedPreferences;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.os.Handler;public class WelcomeActivity extends ShipBaseActivity{private AppSharedPreferences appSP; // 延迟1秒private static final long SPLASH_DELAY_MILLIS = 1000*2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);instance=this;setContentView(R.layout.activity_welcome);new App(instance);appSP=new AppSharedPreferences(instance,AppSharedPreferences.APP_SHAREPRE_FILE);ApplicationInit();// 使用Handler的postDelayed方法,3秒后执行跳转到MainActivitynew Handler().postDelayed(new Runnable() {public void run() {goHome();}}, SPLASH_DELAY_MILLIS); }private void ApplicationInit(){//获取tokenTokenService tokenService=new TokenService(instance);tokenService.GetAccessToken();//系统自动登录UserService userService=new UserService(instance);userService.AutoLogin();}private void goHome() {if (appSP.getAppIsFirstRun()) {appSP.setAppIsFirstRun(false);Intent intent = new Intent(WelcomeActivity.this,GuideActivity.class);WelcomeActivity.this.startActivity(intent);WelcomeActivity.this.finish();} else {Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);WelcomeActivity.this.startActivity(intent);WelcomeActivity.this.finish();}}@Overrideprotected void onResume() {super.onResume();JPushInterface.onResume(this);}@Overrideprotected void onPause() {super.onPause();JPushInterface.onPause(this);}}
JPushInterface.onResume(this)开如统计,
JPushInterface.onPause(this);结束统计
1 0
- jpush推送
- jpush 推送
- JPush推送
- 极光推送JPush
- 试用JPush极光推送
- JPUSH andoid推送开发
- JPush 服务器消息推送
- Android Jpush极光推送
- 极光推送Jpush
- Android 推送 之 JPush
- JPush 推送应用
- jpush极光推送
- 导入 JPush推送
- JPush推送整理总结
- jpush停止推送
- JPush极光推送
- Android 推送 之 JPush
- iOS JPush极光推送
- JQuery点击复制文本框内容的方法插件
- 我的第一个struts 例子
- 批量配置SSH 免密钥登录脚本
- MyBatis动态SQL之 set 和 trim标记的使用
- Android进程/线程通信方式
- JPush推送
- 百炼OJ1004
- 淘宝CDN架构全解析
- IOS 用 xcode 设置 开机启动页
- Qt程序移植到ARM板上去掉鼠标样子
- java设计模式之单例篇
- elasticsearch的IK分词插件安装
- Linux使用shell脚本调用sendmail发送带附件的邮件
- Concurrency之Introduce