[英]How to create running application in Background android?
我在Android中創建了一個簡單的通知,當有新的輸入數據將在設備中顯示通知時,此通知將始終從服務器檢查數據,我使用了intentservice
並設置了androidManifest,但從服務器有新的數據輸入時仍未顯示通知,這是我的代碼:
類通知//在后台獲取通知
public class Notification extends IntentService {
private UrlHelper Url = new UrlHelper();
private JSONParser jsonParser = new JSONParser();
public Notification() {
super(Notification.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
new Notif().start();}
private class Notif extends Thread{
@Override
public void run() {
try {
while (true){
Thread.sleep(3000);
String jsonStr = new String();
List<NameValuePair> params = new ArrayList<NameValuePair>();
if(UserData.update_id==null){UserData.update_id= 0;}
jsonStr = jsonParser.makeHttpRequest(Url.updatesUrl(UserData.update_id), "GET", params);
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray data = json.getJSONArray("otg");
Log.d("cek", UserData.cek + "");
for(int i=0;i<data.length();i++) {
JSONObject otg = data.getJSONObject(i);
String ID = otg.getString("id");
String desc = otg.getString("Desc");
String type = otg.getString("Category");
UserData.update_id = Integer.parseInt(ID);
if (UserData.cek!=null){
fireNotif(type+"-"+desc);
}else{}}
UserData.cek = UserData.update_id;
} catch (Exception e) {
e.printStackTrace();
}}
} catch (InterruptedException e) {e.printStackTrace();
}}}
}
AndroidManifest
好的,您只是在AndroidManifest.xml中聲明了您的服務,這沒關系,但是您也需要啟動此服務。
在Activity中的onCreate()方法中,您可以啟動此服務:
startService(new Intent(this, Notif.class));
第二個問題是-IntentService有效期很短-即IntentService
工作到handleIntent()
方法完成為止。 在您的情況下,您的服務僅工作數毫秒,因為您創建了新的Thread並且handleMethod已完成。
我的主張是:不要創建新的線程。 IntentService為您創建新線程,而您無需創建新線程。 將所有邏輯放入handleIntent()
方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.