0

I'm making a bus notification application now and having a hard time because of parsing XML data in BroadcastReceiver. (I'm very first user of Android studio)

It's my first time to use broadcastreceiver to make a notification when bus arrives at specific bus station. I'm using bus api, and it gives me a XML data. Everything was fine when I parse xml data in Activity using asyncTask but this kind of thing not working in Broadcastreceiver. Some post even said broadcastreceiver is bad for asynctask.

Can I ask how I can parse XML data in broadcastreceiver or service?

package com.example.absin.firebasebus;

import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import java.util.Calendar;

/**
 * Created by absin on 2019-05-22.
 */

public class alarm_proto extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.temp_alarm);

        Button btn = (Button) findViewById(R.id.alarm_btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Calendar calendar = Calendar.getInstance();

                calendar.set(Calendar.HOUR_OF_DAY, 16);
                calendar.set(Calendar.MINUTE, 26);
                calendar.set(Calendar.SECOND, 30);
                Intent intent = new Intent(getApplicationContext(), Notification_reciver.class);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);



            }

        });
    }
}

This is alarm_proto.java file that calls broadcastreceiver.

package com.example.absin.firebasebus;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;


/**
 * Created by absin on 2019-05-22.
 */

public class Notification_reciver extends BroadcastReceiver {

    final String TAG ="MainActivity";
    public String dataKey = "vgOxwLDnBL1K%2B0EV%2FG7Yi%2Bge%2BwfXMB66UwEnnmJEUuoej7Zg75Z85lE7wOcYZcysMUq5Sa2VGKzNsczJqzgg9A%3D%3D";
    private String requestUrl;
    ArrayList<station_arrive> list = null;
    station_arrive arrival = null;
    String keyword1="206000472", keyword2="204000021", keyword3="35";
//keyword1= 정류소 아이디, keyword2 = 노선아이디(버스번호), keyword3 =노선의 정류소순번 (노선에서 그 정류소 몇번째에 지나가는지)

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

        final PendingResult pendingResult = goAsync();

        AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
            @Override
            protected String doInBackground(String... strings) {

                requestUrl = "http://openapi.gbis.go.kr/ws/rest/busarrivalservice?serviceKey=" +dataKey+ "&stationId=" + keyword1 + "&routeId=" + keyword2 + "&staOrder=" + keyword3;

                try {
            boolean b_predictTime1 = false;
            boolean b_predictTime2 =false;
            boolean b_routeId = false;
            boolean b_stationId = false;


            URL url = new URL(requestUrl);
            InputStream is = url.openStream();
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(new InputStreamReader(is, "UTF-8"));


            int eventType = parser.getEventType();

            while(eventType != XmlPullParser.END_DOCUMENT){
                switch (eventType){
                    case XmlPullParser.START_DOCUMENT:
                        list = new ArrayList<station_arrive>();
                        break;
                    case XmlPullParser.END_DOCUMENT:
                        break;
                    case XmlPullParser.END_TAG:
                        if(parser.getName().equals("busArrivalItem") && arrival != null) {
                            list.add(arrival);
                        }
                        break;
                    case XmlPullParser.START_TAG:
                        if(parser.getName().equals("busArrivalItem")){
                            arrival = new station_arrive();
                        }
                        if (parser.getName().equals("predictTime1")) b_predictTime1 = true;
                        if(parser.getName().equals("predictTime2")) b_predictTime2 = true;
                        if(parser.getName().equals("routeId")) b_routeId = true;
                        if (parser.getName().equals("stationId")) b_stationId = true;

                        break;
                    case XmlPullParser.TEXT:
                        if(b_predictTime1){
                            arrival.setPredictTime1(parser.getText());
                            b_predictTime1 = false;
                        }else if(b_predictTime2) {
                            arrival.setPredictTime2(parser.getText());
                            b_predictTime2 = false;
                        }else if(b_routeId) {
                            arrival.setRouteId(parser.getText());
                            b_routeId = false;
                        } else if(b_stationId) {
                            arrival.setStationId(parser.getText());
                            b_stationId = false;
                        }
                        break;
                }
                eventType = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


                pendingResult.finish();
                return null;
            }
        };

        asyncTask.execute();


        station_arrive sub = list.get(0);

        if(sub.getPredictTime1().equals("7")) { //it means firing a notification when the bus will be at the station in 7 minutes.

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "default");
            builder.setSmallIcon(R.drawable.ic_buspointer);
            builder.setContentTitle("버스 알람");
            builder.setContentText("제발 되어라 좀 살려줘");
            builder.setAutoCancel(true); //사용자가 눌렀을 때 그냥 노티 날아간다

            Intent intent1 = new Intent(context, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

            builder.setContentIntent(pendingIntent);

            Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION);
            builder.setSound(ringtoneUri);

            long[] vibrate = {0, 100, 200, 300};
            builder.setVibrate(vibrate);


            NotificationManager notificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(new NotificationChannel("default", "기본채널", NotificationManager.IMPORTANCE_HIGH));
            notificationManager.notify(1, builder.build());

        }



    }

}

class station_arrive{
    String predictTime1;
    String predictTime2;
    String routeId; // 노선아이디 aka 버스 번호
    String stationId;

    public String getPredictTime1() { return predictTime1; }
    public String getPredictTime2() { return predictTime2; }
    public String getRouteId() { return routeId; }
    public String getStationId() { return stationId;}

    public void setPredictTime1(String predictTime1) { this.predictTime1 = predictTime1; }
    public void setPredictTime2(String predictTime2) { this.predictTime2 = predictTime2; }
    public void setRouteId(String routeId) { this.routeId = routeId; }
    public void setStationId(String stationId) { this.stationId = stationId; }

}

This is broadcastreceiver java file. I used goAyscn() after searching in StackOverflow and it didn't work...

<response>
<comMsgHeader>
<errMsg>NORMAL SERVICE.</errMsg>
<returnCode>00</returnCode>
</comMsgHeader>
<msgHeader>
<queryTime>2019-05-22 15:50:31.873</queryTime>
<resultCode>0</resultCode>
<resultMessage>정상적으로 처리되었습니다.</resultMessage>
</msgHeader>
<msgBody>
<busArrivalItem>
<flag>PASS</flag>
<locationNo1>4</locationNo1>
<locationNo2>6</locationNo2>
<lowPlate1>0</lowPlate1>
<lowPlate2>0</lowPlate2>
<plateNo1>경기70아1784</plateNo1>
<plateNo2>경기70아1926</plateNo2>
<predictTime1>4</predictTime1>
<predictTime2>6</predictTime2>
<remainSeatCnt1>-1</remainSeatCnt1>
<remainSeatCnt2>-1</remainSeatCnt2>
<routeId>204000021</routeId>
<staOrder>35</staOrder>
<stationId>206000472</stationId>
</busArrivalItem>
</msgBody>
</response>

And this one is the answer from api! Thank you in advanc

jamie 8910
  • 247
  • 1
  • 3
  • 10
  • `it didn't work` how exactly? what is the problem? – Vladyslav Matviienko May 22 '19 at 10:47
  • I wrote a code about that I get value from list (station_arrival sub= list.get(0) *I did that cuz XML has only one value) and call getPredictTime1 to take predicTime1 value to use for if sentence. When I activate app, and wait for notification, the app stop and I got a "00 has stopped" pop-up. I'm not sure what is the main problem.. sorry about abstraction. – jamie 8910 May 22 '19 at 10:57
  • Possible duplicate of [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – Vladyslav Matviienko May 22 '19 at 10:59
  • oh I though there are some problem on my broadcastreceiver code. Can I ask a question? what I wrote is the right way to parse XML data in broadcastreceiver? – jamie 8910 May 22 '19 at 11:06
  • there is too much code. Fix your crash first – Vladyslav Matviienko May 22 '19 at 11:08

0 Answers0