这个名字够骚的,没办法 问题尚未解决 同志们还需努力啊!
完整代码:http://download.csdn.net/detail/onebelowzero2012/9311039
废话不多说 上整理后的代码:
package com.example.jpushdemo;
import android.app.Application;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;
/**
* For developer startup JPush SDK
*
* 一般建议在自定义 Application 类里初始化。也可以在主 Activity 里。
*/
public class ExampleApplication extends Application {
private static final String TAG = "JPush";
@Override
public void onCreate() {
Log.d(TAG, "[ExampleApplication] onCreate");
super.onCreate();
JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志
JPushInterface.init(this); // 初始化 JPush
}
}
====================
package com.example.jpushdemo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class ExampleUtil {
public static final String PREFS_NAME = "JPUSH_EXAMPLE";
public static final String PREFS_DAYS = "JPUSH_EXAMPLE_DAYS";
public static final String PREFS_START_TIME = "PREFS_START_TIME";
public static final String PREFS_END_TIME = "PREFS_END_TIME";
public static final String KEY_APP_KEY = "JPUSH_APPKEY";
public static boolean isEmpty(String s) {
if (null == s)
return true;
if (s.length() == 0)
return true;
if (s.trim().length() == 0)
return true;
return false;
}
// 校验Tag Alias 只能是数字,英文字母和中文
public static boolean isValidTagAndAlias(String s) {
Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
Matcher m = p.matcher(s);
return m.matches();
}
// 取得AppKey
public static String getAppKey(Context context) {
Bundle metaData = null;
String appKey = null;
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_META_DATA);
if (null != ai)
metaData = ai.metaData;
if (null != metaData) {
appKey = metaData.getString(KEY_APP_KEY);
if ((null == appKey) || appKey.length() != 24) {
appKey = null;
}
}
} catch (NameNotFoundException e) {
}
return appKey;
}
// 取得版本号
public static String GetVersion(Context context) {
try {
PackageInfo manager = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return manager.versionName;
} catch (NameNotFoundException e) {
return "Unknown";
}
}
public static void showToast(final String toast, final Context context)
{
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
Looper.loop();
}
}).start();
}
public static boolean isConnected(Context context) {
ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = conn.getActiveNetworkInfo();
return (info != null && info.isConnected());
}
public static String getImei(Context context, String imei) {
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
imei = telephonyManager.getDeviceId();
} catch (Exception e) {
Log.e(ExampleUtil.class.getSimpleName(), e.getMessage());
}
return imei;
}
}
================================
package com.example.jpushdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import cn.jpush.android.api.InstrumentedActivity;
import cn.jpush.android.api.JPushInterface;
import com.example.myjpushdemo.R;
public class MainActivity extends InstrumentedActivity implements OnClickListener{
public static boolean isForeground = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
registerMessageReceiver(); // used for receive msg
}
// 初始化 JPush。如果已经初始化,但没有登录成功,则执行重新登录。
private void init(){
JPushInterface.init(getApplicationContext());
}
@Override
protected void onResume() {
isForeground = true;
super.onResume();
}
@Override
protected void onPause() {
isForeground = false;
super.onPause();
}
@Override
protected void onDestroy() {
unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
//for receive customer msg from jpush server
private MessageReceiver mMessageReceiver;
public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
public static final String KEY_TITLE = "title";
public static final String KEY_MESSAGE = "message";
public static final String KEY_EXTRAS = "extras";
/**
* 注册广播服务
*/
public void registerMessageReceiver() {
mMessageReceiver = new MessageReceiver();
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(MESSAGE_RECEIVED_ACTION);
registerReceiver(mMessageReceiver, filter);
}
public class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
String messge = intent.getStringExtra(KEY_MESSAGE);
String extras = intent.getStringExtra(KEY_EXTRAS);
StringBuilder showMsg = new StringBuilder();
showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
if (!ExampleUtil.isEmpty(extras)) {
showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
}
//setCostomMsg(showMsg.toString());
}
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
===============================
重点来了! 这个类相信你一看就知道JPush的原理了 他的sdk包向后台传输了一些参数 广播的方式
package com.example.jpushdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import cn.jpush.android.api.JPushInterface;
/**
* 自定义接收器
* 如果不定义这个 Receiver,则:
* 1) 默认用户会打开主界面
* 2) 接收不到自定义消息
*/
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "JPush";
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
//send the Registration Id to your server...
} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
processCustomMessage(context, bundle);
} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
//打开自定义的Activity
Intent i = new Intent(context, TestActivity.class);
i.putExtras(bundle);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
context.startActivity(i);
} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
//在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等..
} else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
Log.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
} else {
Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
}
}
// 打印所有的 intent extra 数据
private static String printBundle(Bundle bundle) {
StringBuilder sb = new StringBuilder();
for (String key : bundle.keySet()) {
if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
} else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
Log.i(TAG, "This message has no Extra data");
continue;
}
try {
JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
Iterator<String> it = json.keys();
while (it.hasNext()) {
String myKey = it.next().toString();
sb.append("\nkey:" + key + ", value: [" +
myKey + " - " +json.optString(myKey) + "]");
}
} catch (JSONException e) {
Log.e(TAG, "Get message extra JSON error!");
}
} else {
sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
}
}
return sb.toString();
}
//send msg to MainActivity
private void processCustomMessage(Context context, Bundle bundle) {
if (MainActivity.isForeground) {
String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
if (!ExampleUtil.isEmpty(extras)) {
try {
JSONObject extraJson = new JSONObject(extras);
if (null != extraJson && extraJson.length() > 0) {
msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
}
} catch (JSONException e) {
}
}
context.sendBroadcast(msgIntent);
}
}
}
================================================
这个activity即 接受消息布局什么操作
package com.example.jpushdemo;
import cn.jpush.android.api.JPushInterface;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("用户自定义打开的Activity");
Intent intent = getIntent();
if (null != intent) {
Bundle bundle = getIntent().getExtras();
String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
String content = bundle.getString(JPushInterface.EXTRA_ALERT);
tv.setText("Title : " + title + " " + "Content : " + content);
}
//设置
addContentView(tv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
}
=========================清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myjpushdemo"
android:versionCode="205"
android:versionName="2.0.5"
>
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="17" />
<permission
android:name="com.example.myjpushdemo.permission.JPUSH_MESSAGE"
android:protectionLevel="signature" />
<!-- Required 一些系统要求的权限,如访问网络等-->
<uses-permission android:name="com.example.myjpushdemo.permission.JPUSH_MESSAGE" />
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<!-- Optional for location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<application
android:icon="@drawable/ic_launcher"
android:allowBackup="true"
android:label="@string/app_name"
android:name="com.example.jpushdemo.ExampleApplication">
<!-- For test only 测试的主程序-->
<activity
android:name="com.example.jpushdemo.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>
<!-- For test only 测试状态通知栏,需要打开的Activity -->
<activity android:name="com.example.jpushdemo.TestActivity" android:exported="false">
<intent-filter>
<action android:name="jpush.testAction" />
<category android:name="jpush.testCategory" />
</intent-filter>
</activity>
<!-- 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.example.myjpushdemo" />
</intent-filter>
</activity>
<!-- Required SDK核心功能-->
<service
android:name="cn.jpush.android.service.DownloadService"
android:enabled="true"
android:exported="false" >
</service>
<!-- Required SDK 核心功能-->
<!-- 可配置android:process参数将PushService放在其他进程中 -->
<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.example.myjpushdemo" />
</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.example.myjpushdemo" />
</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.example.jpushdemo.MyReceiver"
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.example.myjpushdemo" />
</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="28bc73cc46de72a438050b40" /> <!-- </>值来自开发者平台取得的AppKey-->
</application>
</manifest>
================
values目录下文件
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, JPush!</string>
<string name="app_name">JPush SDK Demo</string>
<string name="tag_hint">Tag为大小写字母,数字,下划线,中文, 多个用以逗号分隔</string>
<string name="alias_hint">Alias为大小写字母,数字,下划线</string>
<string name="style_hint">style为数字</string>
<string name="error_style_empty">style不能为空</string>
<string name="error_alias_empty">alias不能为空</string>
<string name="error_tag_empty">tag不能为空</string>
<string name="error_tag_gs_empty">格式不对</string>
<string name="error_network">网络连接异常,初始化失败 请检查网络!</string>
<string name="logining">程序在后台执行, 请查看日志!</string>
<string name="setting_su">设置成功</string>
</resources>
==========
styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="push_style">
<item name="android:hint">@string/style_hint</item>
<item name="android:inputType">number</item>
<item name="android:textSize">14sp</item>
</style>
<style name="push_alias">
<item name="android:hint">@string/alias_hint</item>
<item name="android:textSize">14sp</item>
</style>
<style name="push_tag">
<item name="android:hint">@string/tag_hint</item>
<item name="android:textSize">14sp</item>
</style>
</resources>
这个可能没用到,时间仓促
关于富文本编辑 需和前台交互,先埋个伏笔 有空研究一下。
完整代码下载见:http://download.csdn.net/detail/onebelowzero2012/9311039