Search code examples
javaandroidnotificationsandroid-serviceandroid-service-binding

Does Service needs another parser?


I have already been fetched data from instagram api. But i cannot reach that data to use it on my service. I have tried all methods that i know.

**Here is my main object: ** If my followers count is increases or decreases, notify, And check that for every 5 min.(I am still working on it. There are lots of misses yet.)

**Here is my main question: ** Do i really have to create a new parser to fetch data that i already have or what should i build?

If you have any sample or Articles for this case, that would be useful.
I heard about Csv file. Is that can be useful to import ?

PS: I learned java and android studio yet. I am pretty newbie.

public class MyService extends Service {
private InstagramApp mApp;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
@Nullable
@Override

public IBinder onBind(Intent intent) { return null; }

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
            ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);

    Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();

    Timer myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {

            String xx=userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);

            getnotification(xx);
        }
    }, 0, 5000);

    return START_STICKY; 
}

@Override
public void onDestroy() {
    Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}

public void getnotification(String xx){

            //String foo=(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
       // int fo= Integer.parseInt(foo);

       // Toast.makeText(this, xx, Toast.LENGTH_LONG).show();

        NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
         Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
        //PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
        Notification notif = new Notification.Builder(this)
                .setSmallIcon(R.drawable.common_full_open_on_phone)
                .setContentTitle("Notifications "+xx)
                .setContentText("Followed by="+ userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY))
                .setContentIntent(pintent)
                .build();
        notificationmgr.notify(0,notif);
    }
   /* Uri uri = Uri.parse("http://instagram.com/");
    Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
    likeIng.setPackage("com.instagram.android");
    try {
        startActivity(likeIng);
    } catch (ActivityNotFoundException e) {
        startActivity(new Intent(Intent.ACTION_VIEW,
                Uri.parse("http://instagram.com/xxx")));
    }*/
}

Here is my MainActivity

public class MainActivity extends AppCompatActivity implements OnClickListener {

private InstagramApp mApp;

private Button btnConnect;
private Button btnMe, btnOS,btnCS;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
ViewGroup myLayout;
private FirebaseAnalytics mFirebaseAnalytics;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(activity_main);
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
        myLayout = (ViewGroup)findViewById(R.id.myLayout);

        mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
                ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
        mApp.setListener(new OAuthAuthenticationListener() {

            @Override
            public void onSuccess() {
                mApp.fetchUserName(handler);
            }

            @Override
            public void onFail(String error) {
                Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT)
                        .show();
            }
        }
        );
        setWidgetReference();
        bindEventHandlers();

        if (mApp.hasAccessToken()) {
            btnConnect.setText("Disconnect");
            mApp.fetchUserName(handler);

        }
    }

private void setWidgetReference() {

    btnConnect = (Button) findViewById(R.id.btnConnect);
    btnMe = (Button) findViewById(R.id.btnMy);
    btnOS = (Button) findViewById(R.id.btnOS);
    btnCS = (Button) findViewById(R.id.btnCS);
}

private void bindEventHandlers() {
    btnConnect.setOnClickListener(this);
    btnMe.setOnClickListener(this);
    btnOS.setOnClickListener(this);
    btnCS.setOnClickListener(this);
}

String log="log";

    @Override
    public void onClick(View v) {
        if (v == btnConnect) {
            connectOrDisconnectUser();
        } else {
            String url = "";
            if (v == btnMe) {
                Log.v(log,"info show");
                displayInfoDialogView();
                                                                                                        //TODO Usersa string koy. Yeni hesap için.
                                                                                                       //  url = "https://api.instagram.com/v1/users/self"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/?access_token=" + mApp.getTOken(); imageView.setTag(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE));String imageName = (String) imageView.getTag();String axe=(String) userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE);image.setImageResource(axe);
            }
            else if (v == btnOS) {
                Log.v(log,"Service started");
                startService(new Intent(getBaseContext(),MyService.class));

                                                                                                       // url = "https://api.instagram.com/v1/users/self/media/recent"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/followed-by?access_token="+ mApp.getTOken();
            }
                                                                                                        //startActivity(new Intent(MainActivity.this, Relationship.class).putExtra("userInfo", url));
            else if(v==btnCS){
                Log.v(log,"Service closed");
                stopService(new Intent(getBaseContext(),MyService.class));

            }
        }

    }
    public void goBack(View v){
        setContentView(R.layout.activity_main);
    }


        private void connectOrDisconnectUser() {
            if (mApp.hasAccessToken()) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(
                        MainActivity.this);
                builder.setMessage("Disconnect from Instagram?")
                        .setCancelable(false)
                        .setPositiveButton("Yes",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
                                        mApp.resetAccessToken();
                                        btnConnect.setText("Connect");
                                    }
                                })
                        .setNegativeButton("No",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
                                        dialog.cancel();
                                    }
                                });
                final AlertDialog alert = builder.create();
                alert.show();
            } else {

                mApp.authorize();
            }
        }
        private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == InstagramApp.WHAT_FINALIZE) {
                userInfoHashmap = mApp.getUserInfo();
                btnConnect.setText("Disconnect");
            } else if (msg.what == InstagramApp.WHAT_ERROR) {
                Toast.makeText(MainActivity.this, "Check your network.",
                        Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });

    @Override
    protected void onStart() {
        super.onStart();

        Toast.makeText(this, "Welcome to onStart", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this, "Welcome to onResume", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(this, "It is onPause", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStop() {
        super.onStop();

        Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Toast.makeText(this, "Bye Bye :((", Toast.LENGTH_SHORT).show();
    }

    private void displayInfoDialogView() {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        alertDialog.setTitle(userInfoHashmap.get(InstagramApp.TAG_USERNAME));

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.activity_follower_list, null);
        alertDialog.setView(view);

        TextView tvName = (TextView) view.findViewById(R.id.textView3);
        TextView tvNoOfFollwers = (TextView) view.findViewById(R.id.textView2);
        TextView tvNoOfFollowing = (TextView) view.findViewById(R.id.textView4);
        //new ImageLoader(MainActivity.this).DisplayImage(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE), ivProfile);
        tvName.setText(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
        tvNoOfFollowing.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWS));
        tvNoOfFollwers.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
        alertDialog.create().show();
    }

    public void getnotification(){

       String xx = userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
      /*  Toast.makeText(this, xx, Toast.LENGTH_LONG)
                .show();
*/
        if (xx!=xx ) {

            NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            // Intent intent = new Intent(this, resultpage.class);
            // PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);

            //   PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);


            Notification notif = new Notification.Builder(this)
                    .setSmallIcon(R.drawable.common_google_signin_btn_text_dark_pressed)
                    .setContentTitle("Bu bir Bildirimdir!")
                    .setContentText("Bu bildirimin içeriğidir.")
                    //.setContentIntent(pintent)
                    .build();


            notificationmgr.notify(0,notif);

        }
        }
}

Solution

  • The only solution that i found is the adding parser to your service to reach data from api. None of the the method can access to reach data from service to activity.

    I added this class to reach api data on service.

    public void lilParser()  throws IOException, JSONException{
    
           URL url = new URL(API_URL + "/users/" + mSession.getId()
                   + "/?access_token=" + mAccessToken);
           HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
           urlConnection.setRequestMethod("GET");
           urlConnection.setDoInput(true);
           urlConnection.connect();
           String response = Utils.streamToString(urlConnection
                   .getInputStream());
           System.out.println(response);
    
           JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
           JSONObject data_obj = jsonObj.getJSONObject("data");
           JSONObject counts_obj = data_obj.getJSONObject("counts");
    
           String name = jsonObj.getJSONObject("data").getString("full_name");
           String bio =jsonObj.getJSONObject("data").getString("bio");
           String counts=jsonObj.getJSONObject("data").getString("counts");
    
           userInfoHashmap.put(TAG_FOLLOWED_BY,counts_obj.getString(TAG_FOLLOWED_BY));
           Log.i(TAG,"followedby=>[" + counts + "]");
       }
    

    And, Here is my onCreate. You can check The data if it is changed or not.

           @Override
    public void onCreate() {
        Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
    
        myTimer = new Timer();
        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
    
                String fo = userInfoHashmap.get(TAG_FOLLOWED_BY);
                try {
                    lilParser();
                }
                    catch (IOException e) {e.printStackTrace();}
                    catch (JSONException e) {e.printStackTrace();}
    
          if(new String(userInfoHashmap.get(TAG_FOLLOWED_BY)).equals(fo)==true){}
          else {
              getnotification();
    
          }
            }
        }, 0, 30000);
    }
    

    PS: I published my code, that may help someone else. I am still newbie.