退出应用程序时 Android 服务未运行

发布于 2024-12-18 12:27:25 字数 4485 浏览 1 评论 0原文

我在运行服务时遇到问题,实际上,当我退出应用程序时,无论是从应用程序本身退出还是单击任务管理器中的“退出应用程序”按钮,该服务都没有运行。如果应用程序未关闭,则服务正在运行并且用户将收到通知。该服务实际上会通知用户最新的评论。下面是我的服务等级。

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>

I'm having a problem to run a service, actually the service is not running when I exit the my application wether exit from application itself or click 'exit application' button from task manager. If the app is not close, the services is running and user will be notify. The service actually will notify user latest comment. below is my service class.

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

}

below is my manifest file

<?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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酒绊 2024-12-25 12:27:25

在您的服务中实现 onStartCommand 并确保从中返回 Service.START_STICKY;

Implement onStartCommand in your service and ensure that you return Service.START_STICKY; from it.

浪漫人生路 2024-12-25 12:27:25

当我退出应用程序时,无论是从应用程序本身退出还是单击任务管理器中的“退出应用程序”按钮,该服务都没有运行

Android 中没有“从应用程序本身退出”,因此不清楚您的意思。

Android 中没有“任务管理器”,更不用说带有“退出应用程序”按钮的任务管理器了。如果您的意思是您正在使用任务杀手或通过“设置”应用程序,那么您的整个应用程序将停止,包括您可能正在运行的任何服务。

此外,“评论查看器”不太可能需要 android:configChanges="orientation|keyboardHidden",因为很少有活动应该使用它。

the service is not running when I exit the my application wether exit from application itself or click 'exit application' button from task manager

There is no "exit from application itself" in Android, so it is unclear what you mean by this.

There is no "task manager" in Android, let alone one with an "exit application" button. If you mean that you are using a task killer or via the Settings application, then your entire application is stopped, including any services that you may have had running.

Also, it is highly unlikely that a "comment viewer" needs android:configChanges="orientation|keyboardHidden", as few activities should use this.

天涯离梦残月幽梦 2024-12-25 12:27:25

今天早上,我通过使用 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 吗?

This morning I found ugly solution to my problem by using Alarmmanager, so eventhought my application is not running the user still be notify. Here is my code:

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

}

below is my CommentReceiver class

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

Btw I'm beginner in android development so I'm sorry if my question is unclear. I don't think this is the best way as service might be crashed on low memory available. So should I directly using AlarmManager instead of calling the AlarmManager in the service, in case of no interaction between user and the apps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文