在android中需要关于LinkedIn集成的帮助

时间:2012-02-02 10:25:45

标签: android linkedin

在我的Android应用程序中,我正在尝试集成LinkedIn。我已经在LinkedIn上注册了我的应用程序,并且还下载了LinkedIn-j文件。我有应用程序的API密钥和密钥。现在我想获取auth密钥user.I我无法理解如何获得Auth密钥...请帮助我..

1 个答案:

答案 0 :(得分:1)

public class LinkCon_Main extends BaseActivityListView {

final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
        .getInstance().createLinkedInOAuthService(Config.CONSUMER_KEY,
                Config.CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
        .newInstance(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);

/*LinkCon  Widgets*/


ProgressDialog mPrograss;

String name;

View experiencePage;

TextView prof_Name, prof_Headline, prof_Location, prof_Industry;

String prof_name, prof_headline, prof_location, prof_industry, prof_summary, prof_experience,prof_education,prof_languages,prof_skills, prof_interests,prof_birthdate,prof_contatct,prof_email;
String con_name, con_headline, con_location,con_industry, con_summary,con_experience,con_education,con_languages,con_skills,con_interets,con_birthdate,con_phone;
Connections con_email;
String pic_url,con_pic_url;
String startDate, endDate;
String item;
String dty;
String dtm;
String dtd;


ImageView person_Pic, con_pic;

ListView connections_list;
ArrayList<Person> itemslist;

@SuppressWarnings({ "rawtypes" })
Iterator localIterator;

Person mylist;
RelativeLayout  layout_persondetils,layout_con_profile;
LinkedInApiClient client;
Person person;
Connections connections;
ImageLoader imageLoader;
DisplayImageOptions options;
LinkConApp myLinkCon;
LayoutInflater inflater;
String[] months= {"Jan", "Feb", "March", "April", "May","June", "July", "August","Sep", "Oct", "Nov", "Dec"};
StringBuilder localStringBuilder;

@Override
@SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myLinkCon=new LinkConApp();
    prof_Name=(TextView)findViewById(R.id.user_name);
    prof_Headline=(TextView)findViewById(R.id.user_headline);
    prof_Location=(TextView)findViewById(R.id.user_Location);
    prof_Industry=(TextView)findViewById(R.id.user_industry);
    person_Pic=(ImageView)findViewById(R.id.profile_pic);
    layout_persondetils=(RelativeLayout)findViewById(R.id.layout_profiledetils);
    layout_con_profile=(RelativeLayout)findViewById(R.id.layout_con_profile);

    layout_persondetils.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            userpersons();
        }
    });

    mPrograss=new ProgressDialog(LinkCon_Main.this);
    inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // ImageLoader options
    options = new DisplayImageOptions.Builder()
    .showImageOnLoading(R.drawable.ic_launcher)
    .showImageForEmptyUri(R.drawable.photo)
    .showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
    .cacheOnDisc(true).considerExifParams(true).build();

    imageLoader = ImageLoader.getInstance();
    imageLoader.init(ImageLoaderConfiguration.createDefault(this));

    connections_list=(ListView)findViewById(R.id.connectionslist);

    itemslist = new ArrayList<Person>();

    if( Build.VERSION.SDK_INT >= 9){
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 
    }


    final SharedPreferences pref = getSharedPreferences(Config.OAUTH_PREF,
            MODE_PRIVATE);
    final String token = pref.getString(Config.PREF_TOKEN, null);
    final String tokenSecret = pref.getString(Config.PREF_TOKENSECRET, null);

    if (token == null || tokenSecret == null) {
        startAutheniticate();
    } else {
        showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
    }


}

void startAutheniticate() {
    mPrograss.setMessage("Loading...");
    mPrograss.setCancelable(true);
    mPrograss.show();
    new AsyncTask<Void, Void, LinkedInRequestToken>() {

        @Override
        protected LinkedInRequestToken doInBackground(Void... params) {
            return oAuthService.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);
        }

        @Override
        protected void onPostExecute(LinkedInRequestToken liToken) {
            final String uri = liToken.getAuthorizationUrl();
            getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE)
            .edit()
            .putString(Config.PREF_REQTOKENSECRET,
                    liToken.getTokenSecret()).commit();
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
            startActivity(i);
        }

    }.execute();
    mPrograss.dismiss();
}


void finishAuthenticate(final Uri uri) {
    if (uri != null && uri.getScheme().equals(Config.OAUTH_CALLBACK_SCHEME)) {
        final String problem = uri.getQueryParameter(Config.OAUTH_QUERY_PROBLEM);
        if (problem == null) {

            new AsyncTask<Void, Void, LinkedInAccessToken>() {

                @Override
                protected LinkedInAccessToken doInBackground(Void... params) {
                    final SharedPreferences pref = getSharedPreferences(
                            Config.OAUTH_PREF, MODE_PRIVATE);
                    final LinkedInAccessToken accessToken = oAuthService
                            .getOAuthAccessToken(
                                    new LinkedInRequestToken(
                                            uri.getQueryParameter(Config.OAUTH_QUERY_TOKEN),
                                            pref.getString(
                                                    Config.PREF_REQTOKENSECRET,
                                                    null)),
                                                    uri.getQueryParameter(Config.OAUTH_QUERY_VERIFIER));
                    pref.edit()
                    .putString(Config.PREF_TOKEN, accessToken.getToken())
                    .putString(Config.PREF_TOKENSECRET,
                            accessToken.getTokenSecret())
                            .remove(Config.PREF_REQTOKENSECRET).commit();
                    return accessToken;
                }

                @Override
                protected void onPostExecute(LinkedInAccessToken accessToken) {
                    mPrograss.dismiss();
                    showCurrentUser(accessToken);
                }
            }.execute();

        } else {
            Toast.makeText(this,
                    "Appliaction down due OAuth problem: " + problem,
                    Toast.LENGTH_LONG).show();
            finish();
        }

    }
}

void clearTokens() {
    getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE).edit()
    .remove(Config.PREF_TOKEN).remove(Config.PREF_TOKENSECRET)
    .remove(Config.PREF_REQTOKENSECRET).commit();
}


void showCurrentUser(final LinkedInAccessToken accessToken) {

    client = factory.createLinkedInApiClient(accessToken);
    mPrograss.setMessage("Loading..");
    mPrograss.show();
    new AsyncTask<Void, Void, Object>() {


        @Override
        protected Object doInBackground(Void... params) {
            try {

                final Person user_Profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID)); 
                person = client.getProfileById(user_Profile.getId(), EnumSet.of(
                        ProfileField.FIRST_NAME,
                        ProfileField.LAST_NAME,
                        ProfileField.PICTURE_URL,
                        ProfileField.INDUSTRY,
                        ProfileField.MAIN_ADDRESS,
                        ProfileField.HEADLINE,
                        ProfileField.SUMMARY,
                        ProfileField.POSITIONS,
                        ProfileField.EDUCATIONS,
                        ProfileField.LANGUAGES,
                        ProfileField.SKILLS,
                        ProfileField.INTERESTS,
                        ProfileField.PHONE_NUMBERS,
                        ProfileField.EMAIL_ADDRESS,
                        ProfileField.DATE_OF_BIRTH,
                        ProfileField.PUBLIC_PROFILE_URL));


                prof_name       = person.getFirstName() + " "   + person.getLastName();
                prof_headline   = person.getHeadline();
                prof_location   = person.getMainAddress();
                prof_industry   = person.getIndustry();


                return person;

            } catch (LinkedInApiClientException ex) {
                return ex;
            }
        }

        @Override
        protected void onPostExecute(Object result) {
            if (result instanceof Exception) {
                //result is an Exception :) 
                final Exception ex = (Exception) result;
                clearTokens();
                Toast.makeText(
                        LinkCon_Main.this,
                        "Appliaction down due LinkedInApiClientException: "
                                + ex.getMessage()
                                + " Authokens cleared - try run application again.",
                                Toast.LENGTH_LONG).show();
                finish();
            } else if (result instanceof Person) {

                final Person person = (Person) result;

                prof_Name.setText( person.getFirstName() + " "  + person.getLastName());
                prof_Headline.setText(person.getHeadline());
                prof_Location.setText(person.getMainAddress());
                prof_Industry.setText(person.getIndustry());

                prof_Name.setVisibility(0);
                prof_Headline.setVisibility(0);
                prof_Location.setVisibility(0);
                prof_Industry.setVisibility(0);
                person_Pic.setVisibility(0);

                userConnections();
                userDetails();



            }


        }
    }.execute();
    mPrograss.dismiss();

}

@Override
protected void onNewIntent(Intent intent) {
    finishAuthenticate(intent.getData());
}



public void userDetails(){


    if(person.getPictureUrl()!=null){
        pic_url = person.getPictureUrl().toString();
        imageLoader.displayImage(pic_url, person_Pic);                  
    }else{
        person_Pic.setImageResource(R.drawable.ic_launcher);    
    }

    /*************** person Details Summary/experience/education/languages/skills/contacts/interests **********************/

    if (person.getSummary()!=null) {
        prof_summary    = person.getSummary();
    }

    prof_experience="";
    for (Position position:person.getPositions().getPositionList())
    {
        if(position.isIsCurrent()){
            startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
            endDate="Currently Working";
        }else{
            startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
            endDate=months[(int) (position.getEndDate().getMonth()-1)]+"-"+position.getEndDate().getYear();
        }
        prof_experience=prof_experience+"<b>" +"Position :"+"</b>"+position.getTitle()+"<br><b>" +"Company :"+ "</b>"+ position.getCompany().getName()+"<br><b>" +"Start Date:"+ "</b>"+ startDate +"<br><b>" +"End Date:"+ "</b>"+ endDate +"<br>"+"<br>";
    }

    prof_education="";
    for (Education education:person.getEducations().getEducationList()) 
    {
        prof_education=prof_education +"<b>" +"Gaduation :"+ "</b>" +education.getDegree()+"<br><b>" +"Institute :"+ "</b>" +education.getSchoolName()+ "<br><b>" +"Graduation Year :"+ "</b>" +education.getEndDate().getYear()+"<br>"+"<br>";
    }
    prof_languages="";
    for(Language language:person.getLanguages().getLanguageList())
    {
        prof_languages=prof_languages+language.getLanguage().getName()+"\n";
    }

    prof_skills="";
    for(Skill skill:person.getSkills().getSkillList())
    {
        prof_skills=prof_skills+skill.getSkill().getName()+"\n";
    }


    prof_contatct="";
    PhoneNumbers contactinfo=person.getPhoneNumbers();
    if(contactinfo!=null ){
        for(PhoneNumber phoneno:person.getPhoneNumbers().getPhoneNumberList())
        {
            prof_contatct=prof_contatct+ phoneno.getPhoneNumber().toString();
        }
    }

    if(person.getEmailAddress()!=null){
        prof_email=person.getEmailAddress();
    }
    prof_interests = person.getInterests();
    prof_birthdate= person.getDateOfBirth().getDay()+"-"+ months[(int) (person.getDateOfBirth().getMonth()-1)]+"-"+person.getDateOfBirth().getYear();



}


public void userConnections(){




    final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID, 
            ProfileField.FIRST_NAME, 
            ProfileField.LAST_NAME, 
            ProfileField.HEADLINE,
            ProfileField.INDUSTRY,
            ProfileField.PICTURE_URL,

            );

    connections = client.getConnectionsForCurrentUser(connectionFields);

    for (Person person : connections.getPersonList()) {
        itemslist.add(person);
    }

    connection_Adapter myadpter=new connection_Adapter();
    connections_list.setAdapter(myadpter);
    connections_list.setVisibility(0);
    connections_list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            /*Connections List item position selection*/
            person = itemslist.get(position);

        con_name=person.getFirstName()+" "+person.getLastName();
            System.out.println("Name:"+con_name);

            con_headline=person.getHeadline();
            System.out.println("Designation:"+con_headline);

            con_industry=person.getIndustry();
            System.out.println("Industry:"+con_industry);

            Location localLocation = person.getLocation();
            if (localLocation != null){
                con_location=String.format("%s", new Object[] { localLocation.getName() });
                System.out.println("Con_Loaction:"+con_location);
            }

            /*****PICTURE/NAME/INDUSTRY/LOCATION Tested OK******/

            /********need to get SUMMARY/EXPERIENCE/EDUCATION/SKILLS/LANGUAGES/DATEOFBIRTH/PHONENUMBER/EMAIL**********/

            Toast.makeText(LinkCon_Main.this, "Name:"+" "+con_name +"\n"+"Position:"+" "+con_headline+"\n"+"Industry:"+" "+con_industry+"\n"+"Locations:"+" "+con_location, Toast.LENGTH_LONG).show();

        }//onItemClick
    });
}

public class connection_Adapter extends BaseAdapter{

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return itemslist.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder = null;
        if(convertView==null){
            convertView = inflater.inflate(R.layout.list_row,
                    null);
            holder = new ViewHolder();
            holder.con_Itenames = (TextView) convertView
                    .findViewById(R.id.connection_name);
            holder.con_designations = (TextView) convertView
                    .findViewById(R.id.connection_headline);
            holder.con_ItemImage = (ImageView) convertView
                    .findViewById(R.id.connection_image);
            holder.con_locationad = (TextView) convertView
                    .findViewById(R.id.connection_location);


            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        SetData(holder,position);
        return convertView;
    }

    protected Context getBaseContext() {
        // TODO Auto-generated method stub
        return null;
    }

    public void SetData(final ViewHolder holder, int position) {
        final Person con_details = itemslist.get(position);
        holder.con_Itenames.setText(con_details.getFirstName()+" "+con_details.getLastName());
        holder.con_designations.setText(con_details.getIndustry());

        Location localLocation = con_details.getLocation();
        if (localLocation != null){
            con_location=String.format("%s", new Object[] { localLocation.getName() });
        }
        holder.con_locationad.setText(con_location);
        holder.con_Itenames.setTag(con_details);
        if (con_details.getPictureUrl()!=null) {
            imageLoader.displayImage(con_details.getPictureUrl(), holder.con_ItemImage, options);
        }else {
            holder.con_ItemImage.setImageResource(R.drawable.ic_launcher);}
    }

    public void setListItems(ArrayList<Person> newList) {
        itemslist = newList;
        notifyDataSetChanged();
    }
}    
public class ViewHolder{
    TextView con_Itenames,con_designations, con_locationad;
    ImageView con_ItemImage;
}

private void userpersons() {
    // TODO Auto-generated method stub

    Intent user_prof = new Intent(LinkCon_Main.this, User_Profile.class);

    user_prof.putExtra("pic", pic_url);
    user_prof.putExtra("name", prof_name);
    user_prof.putExtra("headline", prof_headline);
    user_prof.putExtra("locations", prof_location);
    user_prof.putExtra("industry", prof_industry);
    user_prof.putExtra("summary", prof_summary);
    user_prof.putExtra("languages", prof_languages);
    user_prof.putExtra("experience", prof_experience);
    user_prof.putExtra("education", prof_education);
    user_prof.putExtra("skills", prof_skills);
    user_prof.putExtra("interests", prof_interests);
    user_prof.putExtra("dateofbirth", prof_birthdate);
    user_prof.putExtra("phoneno", prof_contatct);
    user_prof.putExtra("email", prof_email);

    startActivity(user_prof);       

}


}