2015-04-24 4 views
-2

Я использую IntentService для получения данных из базы данных. Это мой код:Как отправить уведомление в фоновом режиме?

GetDataService.java

public class GetDataService extends IntentService { 

    public GetDataService() { 
     super("GetDataService"); 

    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     Parameter parameter = new Parameter(); 
     String data = (new LandSlideHttpClient()).getDeviceData(); 

     try { 
      parameter = JSONLandslideParser.getParameter(data); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     Intent in = new Intent(); 
     in.setAction(DataReceiver.ACTION_RESP); 
     in.addCategory(Intent.CATEGORY_DEFAULT); 
     in.putExtra("123", (Parcelable) parameter); 
     sendBroadcast(in); 

     long ct = System.currentTimeMillis(); 
     AlarmManager mgr = (AlarmManager) getApplicationContext() 
       .getSystemService(Context.ALARM_SERVICE); 
     Intent i = new Intent(getApplicationContext(), GetDataService.class); 
     PendingIntent pendingIntent = PendingIntent.getService(
       getApplicationContext(), 0, i, 0); 

     mgr.set(AlarmManager.RTC_WAKEUP, ct + 10000, pendingIntent); 
     stopSelf(); 
    } 
} 

CurrentData.java

public class CurrentDataService extends Fragment { 

public CurrentDataService() { 
    super(); 
} 

private DataReceiver dataReceiver; 

TextView id; 
TextView temp; 
TextView acc; 
TextView moisture; 
TextView battery; 
TextView date; 
TextView time; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.currentdata_layout, 
      container, false); 
    id = (TextView) rootView.findViewById(R.id.showID); 
    temp = (TextView) rootView.findViewById(R.id.showTEMP); 
    acc = (TextView) rootView.findViewById(R.id.showACC); 
    moisture = (TextView) rootView.findViewById(R.id.showMoisture); 
    battery = (TextView) rootView.findViewById(R.id.showBat); 
    date = (TextView) rootView.findViewById(R.id.showDATE); 
    time = (TextView) rootView.findViewById(R.id.showTIME); 

    return rootView; 
} 

@Override 
public void onResume() { 
    IntentFilter filter = new IntentFilter(DataReceiver.ACTION_RESP); 
    filter.addCategory(Intent.CATEGORY_DEFAULT); 

    dataReceiver = new DataReceiver(); 
    getActivity().registerReceiver(dataReceiver, filter); 

    Intent intent = new Intent(getActivity(), GetDataService.class); 
    getActivity().startService(intent); 
    super.onResume(); 
} 

@Override 
public void onDestroy() { 
    getActivity().unregisterReceiver(dataReceiver); 
    super.onDestroy(); 
} 

public class DataReceiver extends BroadcastReceiver { 

    public static final String ACTION_RESP = "getdatafromBroadcast"; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Parameter result = (Parameter) intent.getParcelableExtra("123"); 

     id.setText(result.getId()); 
     temp.setText(" " + result.getTemp());// + " °C"); 
     acc.setText(" " + result.getAcc());// + " m/s2"); 
     moisture.setText(" " + result.getMoisture());// +// " mps"); 
     battery.setText(" " + result.getBattery());// + " %"); 
     date.setText(result.getDate()); 
     time.setText(result.getTime()); 
     if (Float.parseFloat(temp.getText().toString()) > 25) { 
      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
        getActivity()).setContentTitle("My notification") 
        .setContentText("Danger") 
        .setWhen(System.currentTimeMillis()); 

      NotificationManager mNotificationManager = (NotificationManager) getActivity() 
        .getSystemService(Context.NOTIFICATION_SERVICE); 
      mNotificationManager.notify(1, mBuilder.build()); 
     } 
    } 

} 
} 

У меня есть две проблемы:

  1. Я хочу, когда значение temp превышает 25, а затем создайте одно уведомление, которое уведомит пользователя, если приложение закрыто. Но мой код не создает уведомления.

  2. Я использую навигационную панель и имею вторую вкладку с именем Current data, которая показывает текущую информацию. Я использую intenservice и диспетчер аварийных сообщений, но мой CurrentTab просто работает, когда мое приложение показывает эту вкладку, но если я перехожу на другую вкладку, CurrentTab не показывать тост (я устанавливаю тост, когда temp>25). Итак, является ли мой intenservice неправильным?

    Если вы знаете мои проблемы, помогите мне, пожалуйста.

+0

вы должны отправить его. google - ваш лучший друг ..... –

+0

'if (Float.compare (result.getTemp(), 25f)> = 0)' – Blackbelt

+0

Я очень много googled, но мне еще нужно найти ответ, поэтому я отправляю его , Вы знаете мою проблему? –

ответ

0

Прежде всего проверьте, будут ли ваши, если условие работает или нет .. Положить тост или распечатать что-то .. Если это работает, поместите в него следующий код:

NotificationManager mManager;  
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE); 

//Put the name of the class where you want to go on clicking the notification.. I used MainActivity 

     Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class); 

     Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis()); 

     intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(),0, intent1,PendingIntent.FLAG_ONE_SHOT); 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 
     notification.setLatestEventInfo(this.getApplicationContext(), "Notification", "This is a test message!", pendingNotificationIntent); 

     mManager.notify(0, notification); 

Этот код для уведомление будет работать, просто убедитесь, что ваше условие работает

+0

Спасибо @Prakhar, Ваш код работает, но он не удаляется автоматически. –

Смежные вопросы