从Android服务调用函数

时间:2016-05-04 10:43:53

标签: android

您好大家好我正在开发一个应用程序,我正在使用服务上传多个图像到服务器上传多个图像,即使应用程序从后台关闭。           但我想调用一个函数,但我无法调用该函数,请帮助我。

UploadPhotos.java

public class UploadPhotos extends AppCompatActivity {
UploadService mBoundService;
boolean mServiceBound = false;
Context context;
SelectPaper paperSession;
private CoordinatorLayout coordinatorLayout;
SelectLab labSession;
SessionManager session;
String strSize,strType,str_username,strMRP,strPrice,strlab,strcity,strdel_type,album_type;
MaterialEditText ppr_size,ppr_type,mrp,disPrice;
SelectedAdapter_Test selectedAdapter;
long totalprice=0;
int i=0;
ProgressBar pb;
String imageName,user_mail,total;
GridView UploadGallery;
Handler handler;
ArrayList<CustomGallery> listOfPhotos;
ImageLoader imageLoader;
String Send[];
Snackbar snackbar;
OrderId orderidsession;
AlertDialog dialog;
Button btnGalleryPickup, btnUpload;
TextView noImage;
String abc;
NotificationManager manager;
Notification.Builder builder;
ArrayList<CustomGallery> dataT;
  Notification myNotication;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_photos);
    context = this;
         manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

    final ActionBar ab = getSupportActionBar();
    assert ab != null;
    ab.setDisplayHomeAsUpEnabled(true);

    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_content);
    labSession = new SelectLab(getApplicationContext());
    paperSession = new SelectPaper(getApplicationContext());
    orderidsession=new OrderId(getApplicationContext());
    session = new SessionManager(getApplicationContext());
    HashMap<String, String> user = session.getUserDetails();
    user_mail = user.get(SessionManager.KEY_EMAIL);

    noImage = (TextView)findViewById(R.id.noImage);

    final String symbol = getResources().getString(R.string.rupee_symbol);


    HashMap<String, String> paper = paperSession.getPaperDetails();
    strSize = paper.get(SelectPaper.KEY_SIZE);
    strType = paper.get(SelectPaper.KEY_TYPE);
    strdel_type=paper.get(SelectPaper.DEL_TYPE);

    HashMap<String, String> lab = labSession.getLabDetails();
    strMRP = lab.get(SelectLab.KEY_MRP);
    strPrice = lab.get(SelectLab.KEY_PRICE);
    strlab = lab.get(SelectLab.KEY_LAB);
    strcity = lab.get(SelectLab.KEY_CITY);
    str_username=lab.get(SelectLab.KEY_USERNAME);

    ppr_size = (MaterialEditText) findViewById(R.id.paper_size);
    ppr_type = (MaterialEditText) findViewById(R.id.paper_type);
    mrp = (MaterialEditText) findViewById(R.id.MRP);

    disPrice = (MaterialEditText) findViewById(R.id.discount_price);
    ppr_size.setText(strSize);
    ppr_type.setText(strType);
    mrp.setText(symbol + " " + strMRP);
    disPrice.setText(symbol + " " + strPrice);
    initImageLoader();
    init();
}

private void initImageLoader() {
    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
            .bitmapConfig(Bitmap.Config.RGB_565).build();
    ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
            this).defaultDisplayImageOptions(defaultOptions).memoryCache(
            new WeakMemoryCache());

    ImageLoaderConfiguration config = builder.build();
    imageLoader = ImageLoader.getInstance();
    imageLoader.init(config);
}

private void init() {

    handler = new Handler();
    UploadGallery = (GridView) findViewById(R.id.uploadGallery);
    UploadGallery.setFastScrollEnabled(true);
    selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
    UploadGallery.setAdapter(selectedAdapter);
    btnGalleryPickup = (Button) findViewById(R.id.btnSelectPhoto);
    btnGalleryPickup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
            startActivityForResult(i, 200);
        }
    });

    btnUpload = (Button) findViewById(R.id.btn_upload);
    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            listOfPhotos = selectedAdapter.getAll();
            if (listOfPhotos != null && listOfPhotos.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                abc = sdf.format(new Date());
                Log.d("Orderid Session", ""+abc);
                abc="EPP"+abc;
                orderidsession.CreateOrderId(abc);
                Toast.makeText(getApplicationContext(),""+abc,Toast.LENGTH_LONG).show();

                //progressDialog = ProgressDialog.show(UploadPhotos.this, "", "Uploading files to server.....", false);
                //AlertDialog dialog;;

                dialog = new SpotsDialog(UploadPhotos.this);
                dialog.show();
                Thread thread = new Thread(new Runnable() {
                    public void run() {
                        Intent in = new Intent(UploadPhotos.this, UploadService.class);
                        in.putExtra("listof",dataT);
                        in.putExtra("strsize",strSize);
                        in.putExtra("strtype",strType);
                        in.putExtra("user_mail",user_mail);
                        in.putExtra("strmrp",strMRP);
                        in.putExtra("strprice",strPrice);
                        in.putExtra("strlab",strlab);
                        in.putExtra("strcity",strcity);
                        in.putExtra("strdel_type",strdel_type);
                        in.putExtra("strusername",str_username);
                        in.putExtra("foldername",abc);
                        startService(in);

                        bindService(in, mServiceConnection, Context.BIND_AUTO_CREATE);
                           // doFileUpload();
                        runOnUiThread(new Runnable() {
                            public void run() {
                                if (dialog.isShowing()) {
                                    dialog.dismiss();
                                    totalprice=0;


                                }


                            }
                        });
                    }
                });
                thread.start();

            }else{
                Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
            }
        }



});



    UploadGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(position);
            selectedAdapter.getItem(position);
           // selectedAdapter.Pbbar(view );
            Toast.makeText(getApplicationContext(), "Position : " + position + " Path : " + objDetails.sdcardPath, Toast.LENGTH_SHORT).show();
             //selectedAdapter.changeSelection(view, position);
        }
    });
}



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 200 && resultCode == Activity.RESULT_OK) {

        String[] all_path = data.getStringArrayExtra("all_path");
        noImage.setVisibility(View.GONE);
        UploadGallery.setVisibility(View.VISIBLE);
         dataT = new ArrayList<CustomGallery>();

        for (String string : all_path) {
            CustomGallery item = new CustomGallery();
            item.sdcardPath = string;
            dataT.add(item);
        }

        Log.d("DATAt",dataT.toString());
        selectedAdapter.addAll(dataT);
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_upload_photos, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

private ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mServiceBound = false;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        UploadService.MyBinder myBinder = (UploadService.MyBinder) service;
        mBoundService = myBinder.getService();
        mServiceBound = true;
    }
};


   }

SelectedAdapter_Test.java

public class SelectedAdapter_Test extends BaseAdapter{

private Context mContext;
private LayoutInflater inflater;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;

private boolean isActionMultiplePick;


public SelectedAdapter_Test(Context c, ImageLoader imageLoader) {
    mContext = c;
    inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.imageLoader = imageLoader;
    // clearCache();
}

public class ViewHolder {
    ImageView imgQueue;
    ImageView imgEdit;
    EditText qty;
    Button ok;
    ProgressBar pb;


}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int i) {
    return data.get(i);
}

@Override
public long getItemId(int i) {
    return i;
}

public void changeSelection(View v, int position) {

    if (data.get(position).isSeleted) {
        data.get(position).isSeleted = false;
        ((ViewHolder) v.getTag()).imgEdit.setVisibility(View.GONE);
        ((ViewHolder) v.getTag()).qty.setVisibility(View.GONE);
        ((ViewHolder) v.getTag()).ok.setVisibility(View.GONE);
    } else {
        data.get(position).isSeleted = true;
        ((ViewHolder) v.getTag()).qty.setVisibility(View.VISIBLE);
        ((ViewHolder) v.getTag()).ok.setVisibility(View.VISIBLE);
        ((ViewHolder) v.getTag()).imgEdit.setVisibility(View.VISIBLE);
    }


}
public void Pbbar(View v) {

        ((ViewHolder)v.getTag()).pb.setVisibility(View.VISIBLE);




}

@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {


    final ViewHolder holder;
    if (convertView == null) {

        convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
        holder = new ViewHolder();
        holder.pb=(ProgressBar)convertView.findViewById(R.id.pb_image_upload);
        holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
        holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
        holder.qty = (EditText)convertView.findViewById(R.id.quantity);
        holder.ok = (Button)convertView.findViewById(R.id.btn_ok);

        holder.imgEdit.setVisibility(View.GONE);
        holder.qty.setVisibility(View.GONE);
        holder.ok.setVisibility(View.GONE);

        holder.ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                data.get(i).qty = 1;
            }
        });

        convertView.setTag(holder);

    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    //holder.imgQueue.setTag(position);


    imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {
            holder.imgQueue.setImageResource(R.drawable.no_media);
            super.onLoadingStarted(imageUri, view);
        }
    });

    if (isActionMultiplePick) {
        holder.imgEdit.setSelected(data.get(i).isSeleted);
        holder.qty.setSelected(data.get(i).isSeleted);
        holder.ok.setSelected(data.get(i).isSeleted);
        Log.d("Position Data", data.get(i).toString());
        Log.d("Position", String.valueOf(i));
    }

    return convertView;
}


public void addAll(ArrayList<CustomGallery> files) {

    try {
        this.data.clear();
        this.data.addAll(files);

    } catch (Exception e) {
        e.printStackTrace();
    }

    notifyDataSetChanged();
}
public ArrayList getAll(){

    return data;
}

 }

这是服务

public class UploadService extends Service {
private static String LOG_TAG = "BoundService";
private IBinder mBinder = new MyBinder();
ArrayList<CustomGallery> listOfPhotos;
int i=0;
ImageLoader imageLoader;

NotificationManager manager;
Notification myNotication;
String response_str=null;
long totalprice=0;
Notification.Builder builder;
SelectedAdapter_Test selectedAdapter;

String strsize,strtype,usermail,total,strmrp,strprice,strlab,strcity,abc,strdel_type,struname,imageName;
@Nullable
@Override
public IBinder onBind(Intent intent) {
    Log.v(LOG_TAG, "in onBind");
    return mBinder;
}

@Override
public void onRebind(Intent intent) {
    Log.v(LOG_TAG, "in onRebind");
    super.onRebind(intent);
}

@Override
public boolean onUnbind(Intent intent) {
    Log.v(LOG_TAG, "in onUnbind");
    return true;
}


@Override
public void onCreate() {
    super.onCreate();
}

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
    Toast.makeText(UploadService.this, "Service Started ", Toast.LENGTH_SHORT).show();
    manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    listOfPhotos = (ArrayList<CustomGallery>) intent.getSerializableExtra("listof");
    strsize = intent.getStringExtra("strsize");
    strtype = intent.getStringExtra("strtype");
    usermail = intent.getStringExtra("user_mail");
    strmrp = intent.getStringExtra("strmrp");
    strprice = intent.getStringExtra("strprice");
    strlab = intent.getStringExtra("strlab");
    strcity = intent.getStringExtra("strcity");
    struname = intent.getStringExtra("strusername");
    strdel_type = intent.getStringExtra("strdel_type");
    abc = intent.getStringExtra("foldername");
   // selectedAdapter.Pbbar(view);
    Intent intn = new Intent("com.dhruva.eprintpost.digitalPrinting");

    PendingIntent pendingIntent = PendingIntent.getActivity(UploadService.this, 1, intn, 0);

    builder = new Notification.Builder(UploadService.this);

    builder.setAutoCancel(true);
    builder.setOngoing(true);
    builder.setContentTitle("Uploading Photos");
    builder.setContentText("Uploading PhotoPrinting Images");
    builder.setSmallIcon(R.drawable.ic_launcher);
    builder.setContentIntent(pendingIntent);
    builder.setOngoing(true);
    for( i = 0 ; i<listOfPhotos.size();i++) {
                try {
                    File f = new File(listOfPhotos.get(i).sdcardPath.toString());
                    //Toast.makeText(UploadService.this, "aa "+listOfPhotos.get(i).sdcardPath, Toast.LENGTH_SHORT).show();
                    int j=i+1;
                    builder.setSubText("Uploading " + j + " of " + listOfPhotos.size() + " image");   //API level 16
                    j++;
                    Toast.makeText(UploadService.this, "i is =  "+i, Toast.LENGTH_SHORT).show();
                    builder.build();
                    myNotication = builder.getNotification();
                    manager.notify(11, myNotication);
                    imageName = f.getName();
                    totalprice = totalprice + Long.parseLong(strprice);
                    total = String.valueOf(totalprice);
                    Log.v("Abhijit", "" + totalprice);
                    String responseString = null;
                    final HttpClient httpclient = new DefaultHttpClient();

                    final HttpPost httppost = new HttpPost("http://abcdefg.com/abcd/UploadFile?foldername=" + abc);     //TODO - to hit URL);
                    try {
                        AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                                new AndroidMultiPartEntity.ProgressListener() {

                                    @Override
                                    public void transferred(long num) {

                                    }
                                });

                        File sourceFile = new File(listOfPhotos.get(i).sdcardPath);
                        Toast.makeText(UploadService.this, "aa "+sourceFile.getName(), Toast.LENGTH_SHORT).show();
                        // Adding file data to http body
                        entity.addPart("image", new FileBody(sourceFile));
                        entity.addPart("foldername", new StringBody(abc));
                        entity.addPart("size",
                                new StringBody(strsize));
                        entity.addPart("type",
                                new StringBody(strtype));
                        entity.addPart("username",
                                new StringBody(usermail));
                        entity.addPart("total",
                                new StringBody(total));
                        entity.addPart("mrp",
                                new StringBody(strmrp));
                        entity.addPart("price",
                                new StringBody(strprice));
                        entity.addPart("lab",
                                new StringBody(strlab));
                        Toast.makeText(UploadService.this, "aa Ky Ho raha hai bhai", Toast.LENGTH_SHORT).show();

                        entity.addPart("city",
                                new StringBody(strcity));
                        entity.addPart("imagename",
                                new StringBody(imageName));
                        entity.addPart("deltype",
                                new StringBody(strdel_type));
                        String initflag = String.valueOf(i + 1);
                        entity.addPart("initflag",
                                new StringBody(initflag));
                        entity.addPart("lab_username",
                                new StringBody(struname));
                        //  totalSize = entity.getContentLength();
                        httppost.setEntity(entity);

                        Thread thread = new Thread(new Runnable() {
                            public void run() {
                                try {

                                    HttpResponse response = httpclient.execute(httppost);
                                    HttpEntity r_entity = response.getEntity();
                                     response_str = EntityUtils.toString(r_entity);

                                    if (r_entity != null) {
                                       Toast.makeText(UploadService.this, "SSS"+response_str, Toast.LENGTH_SHORT).show();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();

                                }catch(Exception e)
                                {
                                    e.printStackTrace();
                                }

                            }
                        });
                        thread.start();


                        Toast.makeText(UploadService.this, "SSS"+response_str, Toast.LENGTH_SHORT).show();

                    } catch (IOException e) {
                        responseString = e.toString();
                        Toast.makeText(UploadService.this, "Exception Occured2 ", Toast.LENGTH_SHORT).show();

                    }catch(Exception e)
                    {
                        Toast.makeText(UploadService.this, "Exception Occured 3", Toast.LENGTH_SHORT).show();

                        e.printStackTrace();
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }


    }
    return Service.START_NOT_STICKY;
}


public class MyBinder extends Binder {
    UploadService getService() {
        return UploadService.this;
    }
}
   }

这里我想从适配器类调用pbbar函数,但我无法从服务器发送视图参数到函数。

请帮帮我,我是android新手

另一个问题是通知中的值没有改变它在整个执行期间占用i的最后一个值。 我想根据成功的上传图片更新i的值

0 个答案:

没有答案