推送是每一個(gè)APP必不可少的一部分,這幾天正好在做這一塊,所以總結(jié)一下遇到的一些問題。在APP被殺死的情況下,對應(yīng)的推送service也一起被殺死了,這個(gè)時(shí)候我們怎么能夠收到后臺的推送呢?
解決辦法很簡單,但是也特別粗暴,在mainfest中給application設(shè)置這個(gè)屬性android:persistent="true",看意思我們就知道,持續(xù)的,一直的,這樣的話,app是殺不死的,推送肯定有可以收到了。但是強(qiáng)烈建議不要這樣做,因?yàn)檫@樣就像某些流氓軟件一樣了,畢竟我們做個(gè)應(yīng)用出來,也不想讓別人以為我們的是流氓軟件吧。好了,重頭戲來了,最后一種方法,也是我比較推薦的一種。用Broadcast Receivers。我們都知道,推送實(shí)際上應(yīng)用的就是廣播,這里我們自定義一個(gè)廣播接收器,讓它繼承系統(tǒng)的Broadcast Receivers,然后復(fù)寫它的onReceive方法,在onReceive里面開啟推送的服務(wù)。最后在mainfest中去注冊我們自定義的廣播接收器。這里一定要用靜態(tài)注冊的廣播接收器。如果是動(dòng)態(tài)注冊的,APP被殺死后,廣播接收器也會(huì)被殺死。下面我已極光推送為例。
//自定義的接收器
public class BoardcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent pushintent=new Intent(context,PushService.class);//啟動(dòng)極光推送的服務(wù)
context.startService(pushintent);
}
}
//靜態(tài)注冊接收器
<receiver
android:name="BoardcastReceiver"
android:enabled="true">
<intent-filter>
<!--Required 用戶注冊SDK的intent-->
<action android:name="cn.jpush.android.intent.REGISTRATION" />
<!--Required 用戶接收SDK消息的intent-->
<action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" />
<!--Required 用戶接收SDK通知欄信息的intent-->
<action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" />
<!--Required 用戶打開自定義通知欄的intent-->
<action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" />
<!-- 接收網(wǎng)絡(luò)變化 連接/斷開 since 1.6.3 -->
<action android:name="cn.jpush.android.intent.CONNECTION" />
<action android:name="android.intent.action.BOOT_COMPLETED"/><!--開機(jī)廣播-->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/><!--網(wǎng)絡(luò)狀態(tài)改變廣播-->
<category android:name="com.woman.RCTest" />
</intent-filter>
</receiver>