0

每当任何新数据进入服务器时,我都会尝试显示通知。但我面临一个问题。它仅在我打开活动时显示通知。但它不是在后台运行。我正在使用服务在后台运行该功能。谁能告诉我如何始终在后台运行此应用程序,如果应用程序也关闭了?

我在主要活动的 onCreate 方法中调用服务,如下所示:

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dashboard);
    startService(new Intent(this, ReviewUpdateService.class));
      .....
      }

在 ReviewUpdateService.class 我写了这段代码:

   public class ReviewUpdateService extends IntentService{

private Notification.Builder earthquakeNotificationBuilder;
public static final int NOTIFICATION_ID = 1;
public static String QUAKES_REFRESHED = "com.example.androidhive.QUAKES_REFRESHED";
private String user_id;
JSONObject jsonData;
private static String share_pref_file = "json_file";    

JSONArray service_notification;
int no_of_notify;

  public ReviewUpdateService() {
        super("ReviewUpdateService");
  }

  private AlarmManager alarmManager;
  private PendingIntent alarmIntent;


public void onCreate() {
    super.onCreate();
    alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    SharedPreferences prefs = getSharedPreferences(share_pref_file,
            Context.MODE_PRIVATE);
    String strJson = prefs.getString("jsondata", "");

    if (!strJson.equals("")) {
        try {
            jsonData = new JSONObject(strJson);
            user_id = jsonData.getString(LoginActivity.KEY_UID);                
        } catch (JSONException e) {

            e.printStackTrace();
        }
    }

    String ALARM_ACTION = ReviewAlarmReceiver.ACTION_REFRESH_DASHBOARD_ALARM;
    Intent intentToFire = new Intent(ALARM_ACTION);
    alarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);

    earthquakeNotificationBuilder = new Notification.Builder(this);
    earthquakeNotificationBuilder
        .setAutoCancel(true)
        .setTicker("New Review detected")
        .setSmallIcon(R.drawable.icon_1);
}
 public void refreshEarthquakes(String formattedDate) {
        // Get the XML
        //URL url;
     UserFunctions userFunctions =  new UserFunctions();;
        try {           
                 Log.d("user_id", user_id);
                JSONObject json_city = userFunctions
                    .getNotification(user_id, formattedDate);
            if(json_city!=null){
        {
                try {
                    String notify_get_id = json_city.getString(LoginActivity.KEY_NO_NOTIFY);
                    no_of_notify = Integer.parseInt(notify_get_id);
                    service_notification = json_city
                            .getJSONArray(LoginActivity.KEY_SERVICE_NOTIFY);
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
                }

            if(service_notification!=null)
            {

            // looping through all item nodes <item>
            for (int i = 0; i < service_notification.length(); i++) {

                try {
                    JSONObject c = service_notification.getJSONObject(i);                                                   
                    String dealer = c.getString("Dealer Rater");
                    String google = c.getString("Google+ Local");
                    String car = c.getString("Cars.com");
                    String edmunds = c.getString("Edmunds.com");
                    String yelp = c.getString("Yelp");
                    String yahoo = c.getString("Yahoo! Local");
                    String insider = c.getString("Insider Pages");
                    String city = c.getString("City Search");   
                    int dealer2 = Integer.parseInt(dealer);
                    int google2 = Integer.parseInt(google);
                    int car2 = Integer.parseInt(car);
                    int edmunds2 = Integer.parseInt(edmunds);
                    int yelp2 = Integer.parseInt(yelp);
                    int yahoo2 = Integer.parseInt(yahoo);
                    int insider2 = Integer.parseInt(insider);
                    int city2 = Integer.parseInt(city);
                    String service_unit1 = "Dealer Rater";
                    String service_unit2 = "Google+ Local";
                    String service_unit3 = "Cars.com";
                    String service_unit4 = "Edmunds.com";
                    String service_unit5 = "Yelp";
                    String service_unit6 = "Yahoo! Local";
                    String service_unit7 = "Insider Pages";
                    String service_unit8 = "City Search";
                    if(dealer2 > 0 ) {
                        if(no_of_notify > 0){
                            broadcastNotification(no_of_notify,service_unit1);
                        }
                    }else if(google2 > 0 ) {
                        if(no_of_notify > 0){
                            broadcastNotification(no_of_notify,service_unit2);
                        }
                    }else if(car2 > 0 ) {
                        if(no_of_notify > 0){
                            broadcastNotification(no_of_notify,service_unit3);
                        }
                    }else if(edmunds2 > 0 ) {
                        if(no_of_notify > 0){
                            broadcastNotification(no_of_notify,service_unit4);
                        }
                    }else if(yelp2 > 0 ) {
                        if(no_of_notify > 0){
                            broadcastNotification(no_of_notify,service_unit5);
                        }
                    }else  if(yahoo2 > 0 ) {
                        if(no_of_notify > 0){
                            broadcastNotification(no_of_notify,service_unit6);
                        }
                    }else if(insider2 > 0 ) {
                        if(no_of_notify > 0){
                            broadcastNotification(no_of_notify,service_unit7);
                        }
                    }else if(city2 > 0 ) {
                        if(no_of_notify > 0){
                            broadcastNotification(no_of_notify,service_unit8);
                        }
                    }

                } catch (JSONException e) {

                    e.printStackTrace();
                }
                }
             }  
      //  }
        }


        finally {
        }
      }


    @Override
    protected void onHandleIntent(Intent intent) {



        int updateFreq = 60;    
         Calendar calender = Calendar.getInstance();
            System.out.println("Current time => "+calender.getTime());

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String formattedDate = df.format(calender.getTime());
            Log.d("time", formattedDate);
            int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
            long timeToRefresh = SystemClock.elapsedRealtime() +
                                 updateFreq*60*1000;
            alarmManager.setInexactRepeating(alarmType, timeToRefresh, updateFreq*60*1000, alarmIntent);


        refreshEarthquakes(formattedDate);
        sendBroadcast(new Intent(QUAKES_REFRESHED));


    } 
     private void broadcastNotification(int no_of_review, String service_name ) {
            Intent startActivityIntent = new Intent(this, DashboardActivity.class);
            PendingIntent launchIntent =
              PendingIntent.getActivity(this, 0, startActivityIntent, 0);

            earthquakeNotificationBuilder
              .setContentIntent(launchIntent)
              .setContentTitle( no_of_review+" "+"new review is there" )
              .setContentText(service_name);

            if (no_of_review > 10) {
              Uri ringURI = 
                RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

              earthquakeNotificationBuilder.setSound(ringURI);
            }

            double vibrateLength = 100*Math.exp(0.53*no_of_review);
            long[] vibrate = new long[] {100, 100, (long)vibrateLength };
            earthquakeNotificationBuilder.setVibrate(vibrate);

            int color;
            if (no_of_review < 2)
              color = Color.GREEN;
            else if (no_of_review < 5)
              color = Color.YELLOW;
            else
              color = Color.RED;

            earthquakeNotificationBuilder.setLights(
              color, 
              (int)vibrateLength, 
              (int)vibrateLength);



            NotificationManager notificationManager 
              = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(NOTIFICATION_ID,
              earthquakeNotificationBuilder.getNotification());
          }

        }

在一个接收器方法中,我添加了一个这样的类:

  public class ReviewAlarmReceiver extends BroadcastReceiver{

public static final String ACTION_REFRESH_DASHBOARD_ALARM = "com.example.androidhive.ACTION_REFRESH_EARTHQUAKE_ALARM";

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Intent startIntent = new Intent(context, ReviewUpdateService.class);
    context.startService(startIntent);
}

}

在 Android.manifest 文件中,我进行了如下修改:

   .........
  <service android:enabled="true"
    android:name=".ReviewUpdateService"/>

  <receiver android:name=".ReviewAlarmReceiver">
       <intent-filter>
            <action android:name="com.example.androidhive.ACTION_REFRESH_EARTHQUAKE_ALARM" />
       </intent-filter>
   </receiver>
  ........

我不知道运行的问题是什么。谁能帮我?提前致谢。

4

2 回答 2

1

使用带有 Timer 方法的简单服务来执行您的操作,并且每当您的服务完成操作时,然后使用

    public static final String CUSTOM_INTENT = "packagename.activityname"
         Intent broadcastIntent=new Intent();
        broadcastIntent.setAction( CUSTOM_INTENT);
        broadcastIntent.putExtra(value,"name");// put data to send to your activity
        sendBroadcast( broadcastIntent );

在使用广播接收器的主要活动中接收来自服务的意图,例如

 @Override
  public void onReceive(Context context, Intent intent) {
   try {


    updateUI(intent);//write your ui update code in definition of this method
} catch (Exception e) {
// TODO Auto-generated catch block
        e.printStackTrace();
    }       
           }
             };


   public void UpdateUI(Intent intent){
       String value= intent.getExtras().getString("name");
//rest of operation perform for updation of notification here
            }
于 2013-04-24T07:10:25.847 回答
0

试试这个 - 在里面oncreate的新线程中启动服务mainactivity,如果设备关闭,你可以注册接收器以onbootup完成broadcastreceiver并在接收器的 onreceive mtd 内启动服务。

于 2013-04-24T07:53:49.450 回答