最近根据项目需要,做了个消息推送,使用友盟消息推送,开始根据友盟的Api的实例进行做,可是到传数据到你需要的Activity中,就是始终都传不过去,最后发现他们都不在一个进程中,但是不用担心,友盟还是很友好的,你只需要继承UmengBaseIntentService服务,在再onMessage()方法中去获取推送过来的消息,在根据你的需求进行操作。
1、在你需要的MainActivity中进行操作。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UmengUpdateAgent.update(this);
mPushAgent = PushAgent.getInstance(this);
mPushAgent.enable();
mPushAgent.onAppStart();
mPushAgent.setDebugMode(true);
Runnable addAliasRunnable = new Runnable() {
public void run() {
try {
//根据业务需要自定义的Alias的类型
mPushAgent.addAlias(getUserId(), Constants.ALIAS_TYPE_NEW_MSG);
mPushAgent.addAlias(getUserId(), Constants.ALIAS_TYPE_COOP);
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(addAliasRunnable).start();
mPushAgent.setPushIntentServiceClass(PushIntentService.class);
mPushAgent.getMessageHandler();
}
2. 在你应用的Application的onCreate方法中去获取推送过的消息,注意,现在还没在应用的进程中。
public class OwnerApplication extends Application {
static Context mContext;
static Resources mResource;
private PushAgent mPushAgent;
public static synchronized OwnerApplication context() {
return (OwnerApplication) mContext;
}
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
mResource = mContext.getResources();
Fresco.initialize(this);
Stetho.initialize(Stetho
.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(
Stetho.defaultInspectorModulesProvider(this)).build());
mPushAgent = PushAgent.getInstance(this);
mPushAgent.enable();
mPushAgent.setDebugMode(true);
}
}
3. 在继承友盟的UmengBaseIntentService服务进行取数据,当然我在是使用的广播进行数据发送,然后你需要的MainActivity中去注册广播进行获取数据。
public class PushIntentService extends UmengBaseIntentService {
@Override
protected void onMessage(Context context, Intent intent) {
super.onMessage(context, intent);
String message = intent.getStringExtra(BaseConstants.MESSAGE_BODY);
try {
UMessage msg = new UMessage(new JSONObject(message));
Intent localIntent=new Intent();
localIntent.setAction(Constants.ACTION_NEW_MESSAGE);
localIntent.putExtra(Constants.INTENT_NEW_MESSAGE,msg.custom);//msg.custom就是我们要获取的数据
sendBroadcast(localIntent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}