如何始终处于后台运行的应用程序,以显示Android的通知 [英] How to run a application always in background to show a notification in android

查看:313
本文介绍了如何始终处于后台运行的应用程序,以显示Android的通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想展现一个通知,每当有新的数据进入服务器。但我面临的一个问题。这是只显示通知,当我打开活动。但它没有运行在后台。我使用的服务运行在后台的功能。任何一个可以告诉我怎么总是在后台运行该应用程序,如果应用程序关闭,则还?

I am trying to show a notification whenever any new data come into server. But I am facing a problem. It is only showing notification when i am opening the activity. But it is not running in background. I am using service to run the functionality in background. Can any one tell me how to run this application always in background, if the app closed then also?

我打电话在这样的主要活动的onCreate方法的服务:

I am calling the service in onCreate method of the main activity like this:

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

和在ReviewUpdateService.class我写了这个code:

and in ReviewUpdateService.class i have written this code:

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

        }

和在reciver方法,我添加了一个类是这样的:

And In a reciver method i have added a class like this:

  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文件我已经修改是这样的:

And in Android.manifest file i have modified like this:

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

我不知道是怎么运行的问题。谁能帮助我?先谢谢了。

I don't know what is the problem running on. Can anyone help me? Thanks in advance.

推荐答案

使用简单,定时服务的方法来执行你的操作,并随时为您服务完成操作,然后使用

use simple service with Timer method to execute your operation and whenever your service complete operation then use

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

在主要活动使用广播接收器接收来自服务的意图像

in main activity using broadcast receiver receive intent from service like

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

这篇关于如何始终处于后台运行的应用程序,以显示Android的通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆