gpt4 book ai didi

android - 如何在后台android中创建正在运行的应用程序?

转载 作者:行者123 更新时间:2023-11-30 01:56:27 25 4
gpt4 key购买 nike

我在 Android 中创建简单的通知,当有新的输入数据将在设备中显示通知时,此通知始终检查来自服务器的数据,我使用了 intentservice 并设置了 androidManifest 但仍然不显示通知来自服务器的新数据输入,这是我的代码:

Class Notification//在后台获取通知

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();
}}}
}

安卓 list

最佳答案

好的,您刚刚在 AndroidManifest.xml 中声明了您的服务,这没问题,但您也需要启动该服务。

在 onCreate() 方法中的 Activity 中,您可以启动此服务:

startService(new Intent(this, Notif.class));

第二个问题是 - IntentService 的生命周期很短 - 即 IntentService 一直工作到 handleIntent() 方法完成。在您的情况下,您的服务仅工作几毫秒,因为您创建了新的 Thread 并且 handleMethod 已完成。

我的建议是:不要创建新线程。 IntentService 为您创建新线程,您不需要创建新线程。将所有逻辑放在 handleIntent() 方法中

关于android - 如何在后台android中创建正在运行的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32135134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com