2011-11-28 115 views
0

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

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> 
+0

您需要启动服务'STICKY',这意味着服务将在其明确关闭时停止。 –

+0

我需要在哪里指定STICKY? – Zahary

回答

0

实现您的服务onStartCommand,并确保你从它返回Service.START_STICKY;

+0

我已经覆盖了我的服务类中的以下代码,但它仍然不工作public int onStartCommand(意图intent,int flags,int startId){ return START_STICKY; } – Zahary

0

的服务没有运行,当我从应用程序退出我的应用程序阉退出本身或从任务管理器

有Android中没有“从应用本身退出”点击“退出应用程序”按钮,所以目前还不清楚你的意思。

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

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

+0

owh我的意思是活动类中有一个按钮,一旦点击它就会触发finish()方法。一旦应用程序不再在内存中激活,服务就不会运行。 – Zahary

+0

@zarie:“一旦应用程序不再在内存中激活,服务就不会运行 - 按照定义,这是事实。你的句子是相当于'1 == 1'的语言。 – CommonsWare

0

今天早上我通过使用Alarmmanager发现了丑陋的解决方案,所以eventhought我的应用程序没有运行,用户仍然被通知。这里是我的代码:下面

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,以防用户和应用之间没有交互。

相关问题