[英]Android services not running while exit application
我在運行服務時遇到問題,實際上,當我退出應用程序而從應用程序本身退出或單擊任務管理器中的“退出應用程序”按鈕時,服務未運行。 如果應用未關閉,則服務正在運行,並且將通知用戶。 該服務實際上將通知用戶最新評論。 以下是我的服務班級。
package com.android.my.hotnews;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.Cursor;
public class CommentNotificationService extends Service{
private Notification notifyMe;
private NotificationManager notifyManager;
private PendingIntent pIntent;
private Intent intent;
private static String DBPATH="data/data/com.android.my.hotnews/databases/";
private static String DBNAME="mydb.db";
private String path = DBPATH+DBNAME;
private Timer timer = new Timer();
private static final long UPDATE_INTERVAL = 5000;
String title = null;
String content = null;
String date = null;
Calendar cal = null;
public void onCreate(){
super.onCreate();
notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifyMe = new Notification(R.drawable.comment_icon, "New Comment", System.currentTimeMillis());
intent = new Intent(android.content.Intent.ACTION_VIEW, null, getApplicationContext(), CommentViewer.class);
pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
inComingComment();
}
public void inComingComment() throws SQLiteException{
SQLiteDatabase db;
db=SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
Cursor rs = db.rawQuery("SELECT * FROM Comment_Log ORDER BY Comment_Date_Time ASC", null);
if(rs.getCount()>0){
rs.moveToFirst();
try {
String[] dmy = rs.getString(1).split("/");
String[] hm = rs.getString(2).split(":");
cal = Calendar.getInstance();
cal.set(Calendar.DATE, Integer.parseInt(dmy[0]));
cal.set(Calendar.MONTH, Integer.parseInt(dmy[1])-1);
cal.set(Calendar.YEAR, Integer.parseInt(dmy[2]));
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hm[0]));
cal.set(Calendar.MINUTE, Integer.parseInt(hm[1]));
title="new comment";
content=rs.getString(3);
db.close();
} catch (Exception e) {
log.d("error ocurred",e.getClass().getName());
db.close();
}
}
//timer.scheduleAtFixedRate(new TimerTask(){
timer.schedule(new TimerTask(){
@Override
public void run() {
notifyMe.setLatestEventInfo(getApplicationContext(), title , content, pIntent);
notifyManager.notify(0, notifyMe);
}
}, cal.getTime(), UPDATE_INTERVAL);
}
public void onDestroy(){
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
以下是我的清單文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.my.hotnews"
android:versionCode="1"
android:versionName="1.0">
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:resizeable="true"
android:anyDensity="true"
/>
<application android:icon="@drawable/apps_icon" android:label="@string/app_name" android:debuggable="true">
<activity android:name=".ContentLoader"
android:configChanges="orientation|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CommentViewer" android:configChanges="orientation|keyboardHidden"/>
<service android:name=".CommentNotificationService"/>
</application>
</manifest>
在您的服務中實現onStartCommand
並確保您返回Service.START_STICKY;
從中。
當我退出應用程序時,服務未運行,或者從應用程序本身退出,或者從任務管理器中單擊“退出應用程序”按鈕
Android中沒有“從應用程序本身退出”,因此尚不清楚您的意思。
Android中沒有“任務管理器”,更不用說帶有“退出應用程序”按鈕的了。 如果您是要使用任務殺手或通過“設置”應用程序,則整個應用程序都將被停止,包括您可能已在運行的所有服務。
另外,“評論查看器”極不可能需要android:configChanges="orientation|keyboardHidden"
,因為很少有活動可以使用它。
今天早上,我通過使用Alarmmanager找到了解決我問題的丑陋解決方案,因此即使我的應用程序未運行,仍會通知用戶。 這是我的代碼:
package com.android.my.hotnews;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.Cursor;
public class CommentNotificationService extends Service{
private Notification notifyMe;
private NotificationManager notifyManager;
private PendingIntent pIntent;
private Intent intent;
private static String DBPATH="data/data/com.android.my.hotnews/databases/";
private static String DBNAME="mydb.db";
private String path = DBPATH+DBNAME;
private Timer timer = new Timer();
private static final long UPDATE_INTERVAL = 5000;
String title = null;
String content = null;
String date = null;
Calendar cal = null;
public void onCreate(){
super.onCreate();
notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifyMe = new Notification(R.drawable.comment_icon, "New Comment", System.currentTimeMillis());
intent = new Intent(android.content.Intent.ACTION_VIEW, null, getApplicationContext(), CommentViewer.class);
pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
inComingComment();
}
public void inComingComment() throws SQLiteException{
SQLiteDatabase db;
db=SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
Cursor rs = db.rawQuery("SELECT * FROM Comment_Log ORDER BY Comment_Date_Time ASC", null);
if(rs.getCount()>0){
rs.moveToFirst();
try {
String[] dmy = rs.getString(1).split("/");
String[] hm = rs.getString(2).split(":");
cal = Calendar.getInstance();
cal.set(Calendar.DATE, Integer.parseInt(dmy[0]));
cal.set(Calendar.MONTH, Integer.parseInt(dmy[1])-1);
cal.set(Calendar.YEAR, Integer.parseInt(dmy[2]));
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hm[0]));
cal.set(Calendar.MINUTE, Integer.parseInt(hm[1]));
title="new comment";
content=rs.getString(3);
db.close();
} catch (Exception e) {
log.d("error ocurred",e.getClass().getName());
db.close();
}
}
timer.schedule(new TimerTask(){
@Override
public void run() {
//here i set time for AlarmManager
Intent intent = new android.content.Intent(getApplicationContext(), CommentReceiver.class);
intent.putExtra("Title", title);
intent.putExtra("Content", content);
PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pIntent);
}
}, 0, UPDATE_INTERVAL);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
以下是我的CommentReceiver類
package com.android.my.hotnews;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.PendingIntent;
import android.app.Notification;
import android.app.NotificationManager;
public class CommentReceiver extends BroadcastReceiver{
private NotificationManager nm;
private Notification notify;
@Override
public void onReceive(Context context, Intent intent) {
String title = intent.getExtras().get("Title").toString();
String content = intent.getExtras().get("Content").toString();
Intent notifyIntent = new Intent(context, CommentViewer.class);
PendingIntent pending = PendingIntent.getActivity(context, 0, notifyIntent, 0);
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notify = new Notification(R.drawable.app_icon, "Incoming comment", System.currentTimeMillis());
notify.setLatestEventInfo(context, title, content, pending);
nm.notify(1, notify);
}
}
順便說一句,我是android開發的初學者,所以很抱歉,如果我的問題不清楚。 我認為這不是最好的方法,因為服務可能會在可用內存不足時崩潰。 因此,如果用戶和應用程序之間沒有交互,我應該直接使用AlarmManager而不是在服務中調用AlarmManager。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.