如何在onStartCommand()方法之外获取服务中的上下文?

时间:2018-05-15 10:12:17

标签: android service android-service

当我在服务的onStartCommand()之外使用Intent时,为了显示特定事件的通知,它会在null对象引用上显示getApplicationContext。 Service仅允许在onStartCommand()方法中使用getApplcationContext / this / context。 如何在onStartCommand()方法之外使用它? 以下是我的服务。有人可以帮我解决这个问题吗?

public class ForegroundService extends Service {
    @Nullable

    private static TransferUtility transferUtility;
    private static ArrayList<HashMap<String, Object>> transferRecordMaps;
    private static ArrayList<HashMap<String, Object>> transferRecordMaps1;
    private Utils utils = new Utils();
    private static final int INDEX_NOT_CHECKED = -1;
    public static int totalcount, totalAssetCount;
    private int checkedIndex;
    private static List<TransferObserver> observers;
    private static int REQUEST_CAMERA = 0, navigate = 0,counter=0,failedcounter=0;
    private static final String LOG_TAG = "ForegroundService";
    UploadMediaToAssetFragment uploadMediaToAssetFragment;
    private int progress;
    Context context;
    private long currentbyte, totalbyte;
    private Notification notification;


    @Override
    public void onCreate() {
        super.onCreate();
        transferUtility = Util.getTransferUtility(getApplicationContext());
        checkedIndex = INDEX_NOT_CHECKED;
        transferRecordMaps = new ArrayList<HashMap<String, Object>>();
        transferRecordMaps1 = new ArrayList<HashMap<String, Object>>();

        uploadMediaToAssetFragment = new UploadMediaToAssetFragment();


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
            Log.i(LOG_TAG, "Received Start Foreground Intent ");
            Intent notificationIntent = new Intent(this, UploadMediaToAssetFragment.class);
            notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TASK);

            Log.d(LOG_TAG,"bytes"+UploadMediaToAssetFragment.totalAssetCount+ " total"+UploadMediaToAssetFragment.totalcount);

            uploadAsset();
            initData();
            updateList();
//            AlertDialog.Builder builder = new AlertDialog.Builder(this);
//                    builder.setTitle("Test dialog");
//                    builder.setIcon(R.drawable.icon);
//                    builder.setMessage("Content");
//
//                        AlertDialog alert = builder.create();
//            alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                alert.show();

            // startActivity(notificationIntent);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                    notificationIntent, 0);

            Intent previousIntent = new Intent(this, ForegroundService.class);
            previousIntent.setAction(Constants.ACTION.PREV_ACTION);
            PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
                    previousIntent, 0);

            Intent playIntent = new Intent(this, ForegroundService.class);
            playIntent.setAction(Constants.ACTION.PLAY_ACTION);
            PendingIntent pplayIntent = PendingIntent.getService(this, 0,
                    playIntent, 0);

            Intent nextIntent = new Intent(this, ForegroundService.class);
            nextIntent.setAction(Constants.ACTION.NEXT_ACTION);
            PendingIntent pnextIntent = PendingIntent.getService(this, 0,
                    nextIntent, 0);

            Bitmap icon = BitmapFactory.decodeResource(getResources(),
                    R.drawable.logo);
             notification = new NotificationCompat.Builder(this)
                    .setContentTitle("Visibly")
                    .setTicker("asset uplaoding")
                    .setContentText("uploading")
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setLargeIcon(
                            Bitmap.createScaledBitmap(icon, 128, 128, false))
                    .setContentIntent(pendingIntent)
                    .setOngoing(true)
                     .setProgress(100,progress,false)
                    .addAction(android.R.drawable.ic_menu_close_clear_cancel,
                            "cancel", ppreviousIntent).build();
            startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
                    notification);

//            if(UploadMediaToAssetFragment.totalAssetCount>=UploadMediaToAssetFragment.totalcount)
//            {
//                onDestroy();
//                stopForeground(true);
//                stopSelf();
//            }
        } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
            Log.i(LOG_TAG, "Clicked Previous");
        } else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
            Log.i(LOG_TAG, "Clicked Play");
        } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
            Log.i(LOG_TAG, "Clicked Next");
        } else if (intent.getAction().equals(
                Constants.ACTION.STOPFOREGROUND_ACTION)) {
            Log.i(LOG_TAG, "Received Stop Foreground Intent");
            stopForeground(true);
            stopSelf();
        }

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(LOG_TAG, "In onDestroy");
    }
    public IBinder onBind(Intent intent) {
        return null;
    }

    public class ForegroundServiceBInder extends Binder {
        ForegroundService getService() {
            // Return this instance of LocalService so clients can call public methods
            return ForegroundService.this;
        }
    }


    public void uploadAsset()
    {
        Log.d("upload asset service","method called");
        for(int i=0;i<AddMediaAssetActivity.galleryDTOArrayList1.size();i++)
        {
            Handler handler1 = new Handler();
            try {
                if(AddMediaAssetActivity.galleryDTOArrayList1.get(i)!=null)
                {
                    String path;
                    Uri uri = Uri.fromFile(new File(AddMediaAssetActivity.galleryDTOArrayList1.get(i).getMediaName()));
                    path = Utility.getPath(uri, getApplicationContext());
                    Uri uriThumb = Uri.fromFile(new File(AddMediaAssetActivity.galleryDTOArrayList1.get(i).getThumbnail()));
                    String pathThum = null;
                    if (uriThumb != null)
                        pathThum = Utility.getPath(uriThumb, getApplicationContext());
                    path = Utility.getPath(uri, getApplicationContext());
                    if(GlobalVariables.isNetworkAvailable(getApplicationContext())) {
                        beginUpload1(pathThum, pathThum);

                        beginUpload(path, AddMediaAssetActivity.galleryDTOArrayList1.get(i).getDescription(), pathThum,AddMediaAssetActivity.galleryDTOArrayList1.get(i).getCreateTagPostDTOList());
                    }else
                    {
                        AlertDialog.Builder builder;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            builder = new AlertDialog.Builder(getApplicationContext(),android.R.style.Theme_Material_Light_Dialog_Alert);
                        } else {
                            builder = new AlertDialog.Builder(getApplicationContext());
                        }
                        builder.setMessage(getResources().getString(R.string.network_connectivity))
                                .setTitle("");
                        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                //getApplicationContext().finish();
                                dialog.dismiss();
                            }
                        });
                        AlertDialog dialog = builder.create();
                        dialog.setCanceledOnTouchOutside(true);
                        dialog.show();
                        dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.clear_blue));

                    }
                }
            }catch (Exception e)
            {

            }
        }
    }

    /*
     * Begins to upload the file specified by the file path.
     */
    private void beginUpload(String filePath, String title, String pathThum, List<TagDTO> createTagPostDTOList)
    {
        Log.d("beginUpload","method called "+filePath+" title "+title+" pathnum "+pathThum+" list tagdto"+createTagPostDTOList);
        if (filePath == null) {
            Toast.makeText(getApplicationContext(), "Could not find the filepath of the selected file",
                    Toast.LENGTH_LONG).show();
            return;
        }
        File file = new File(filePath);
        TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, Constants.FOLDERNAME_NAME+"/"+ file.getName(),
                file, CannedAccessControlList.PublicRead);
        File file1 = new File(pathThum);
        AssetMediaDTO assetMediaDTO=new AssetMediaDTO();
        if(GlobalVariables.isCampaignAsset)
        {
            if (GlobalVariables.campaignFeedDTO.getCampaign_category() != null && GlobalVariables.campaignFeedDTO.getCampaign_category().length() > 0 && !(GlobalVariables.campaignFeedDTO.getCampaign_category().equalsIgnoreCase("null"))) {
                assetMediaDTO.setCategory_id(GlobalVariables.campaignFeedDTO.getCampaign_category());
            } else {
                assetMediaDTO.setCategory_id("rpPDp");
            }
            if (GlobalVariables.campaignFeedDTO.getCampaign_folder() != null && GlobalVariables.campaignFeedDTO.getCampaign_folder().length() > 0 && !(GlobalVariables.campaignFeedDTO.getCampaign_folder().equalsIgnoreCase("null"))) {
                if(GlobalVariables.campaignFeedDTO.getCampaign_folder().equalsIgnoreCase("General"))
                {
                    assetMediaDTO.setFolder_id("");
                }else
                {
                    assetMediaDTO.setFolder_id(GlobalVariables.campaignFeedDTO.getCampaign_folder());
                }


            } else
            {
                assetMediaDTO.setFolder_id("");

            }
        }else
        {
            if (AssetFolderActivity.folderDTO.getCategoryID() != null && AssetFolderActivity.folderDTO.getCategoryID().length() > 0 && !(AssetFolderActivity.folderDTO.getCategoryID().equalsIgnoreCase("null"))) {
                assetMediaDTO.setCategory_id(AssetFolderActivity.folderDTO.getCategoryID());
            } else {
                assetMediaDTO.setCategory_id("rpPDp");
            }
            if (AssetFolderActivity.folderDTO.getFolderIdentity() != null && AssetFolderActivity.folderDTO.getFolderIdentity().length() > 0 && !(AssetFolderActivity.folderDTO.getFolderIdentity().equalsIgnoreCase("null"))) {

                if(AssetFolderActivity.folderDTO.getFoldername()!=null&&AssetFolderActivity.folderDTO.getFoldername().equalsIgnoreCase("general"))
                {
                    assetMediaDTO.setFolder_id("");
                }else {
                    assetMediaDTO.setFolder_id(AssetFolderActivity.folderDTO.getFolderIdentity());
                }

            } else {
                assetMediaDTO.setFolder_id("");

            }
        }
        assetMediaDTO.setMedia_url(GlobalVariables.s3Path+Constants.FOLDERNAME_NAME+"/"+file.getName());
        assetMediaDTO.setThumbnail_url(GlobalVariables.s3Path+Constants.FOLDERNAME_NAME+"/"+file1.getName());
        try {
            assetMediaDTO.setMediaSize(""+file.length());
        }catch (Exception e)
        {

        }
        assetMediaDTO.setDetail(title);
        String result = file.getName().substring(0, file.getName().lastIndexOf("."));
        assetMediaDTO.setTitle(result);
        assetMediaDTO.setTagDTOList(createTagPostDTOList);
        GlobalVariables.assetMediaDTOList.add(assetMediaDTO);

    }


    /*
     * Begins to upload the file specified by the file path.
     */
    private void beginUpload1(String filePath, String pathThum) {
        Log.d("beginUpload1","method called");
        if (filePath == null) {
            Toast.makeText(getApplicationContext(), "Could not find the filepath of the selected file",
                    Toast.LENGTH_LONG).show();
            return;
        }
        File file = new File(filePath);
        TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, Constants.FOLDERNAME_NAME+"/"+ file.getName(),
                file,CannedAccessControlList.PublicRead);
      //  temp1=file.getName();

    }


    //To delete assets from list
    public void deleteMediaUpload(final int position)
    {
        final int position1=position+1;
        AlertDialog.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder = new AlertDialog.Builder(GlobalVariables.mActivity, android.R.style.Theme_Material_Light_Dialog_Alert);
        } else {
            builder = new AlertDialog.Builder(GlobalVariables.mActivity);
        }
        builder.setMessage("Do you want to delete this media?")
                .setTitle("");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id)
            {
                dialog.dismiss();
                if (position >= 0 && position1 < observers.size())
                {
                    try {
                        transferUtility.deleteTransferRecord(observers.get(position).getId());
                        transferUtility.deleteTransferRecord(observers.get(position1).getId());
                        observers.remove(position1);
                        transferRecordMaps.remove(position1);
                        observers.remove(position);
                        transferRecordMaps.remove(position);
                        AddMediaAssetActivity.galleryDTOArrayList1.remove(position);
                    }catch (Exception e)
                    {

                    }
                    updateList();
                    try {
                        GlobalVariables.assetMediaDTOList.remove(position);
                    }catch (Exception e)
                    {

                    }
                }
            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id)
            {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(GlobalVariables.mActivity.getResources().getColor(R.color.clear_blue));
        dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(GlobalVariables.mActivity.getResources().getColor(R.color.clear_blue));

    }

//    /**
//     * Gets all relevant transfers from the Transfer Service for populating the
//     * UI
//     */
//    private void initData() {
//        counter=0;
//        failedcounter=0;
//        navigate=0;
//        transferRecordMaps.clear();
//        transferRecordMaps1.clear();
//        // Use TransferUtility to get all upload transfers.
//        observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
//        TransferListener listener = new UploadMediaToAssetFragment.UploadListener();
//        for (TransferObserver observer : observers) {
//
//            // For each transfer we will will create an entry in
//            // transferRecordMaps which will display
//            // as a single row in the UI
//            HashMap<String, Object> map = new HashMap<String, Object>();
//            Util.fillMap(map, observer, false);
//
//            transferRecordMaps.add(map);
//
//            // Sets listeners to in progress transfers
//            if (TransferState.WAITING.equals(observer.getState())
//                    || TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
//                    || TransferState.IN_PROGRESS.equals(observer.getState())) {
//                observer.setTransferListener(listener);
//            }
//        }
//        transferRecordMaps1.clear();
//        for(int i=0;i<transferRecordMaps.size();i++)
//        {
//            File file = new File((String) transferRecordMaps.get(i).get("fileName"));
//            if(file.getName().substring(0,2).equalsIgnoreCase("0!"))
//            {
//            }
//            else
//            {
//                transferRecordMaps1.add(transferRecordMaps.get(i));
//
//            }
//
//        }
//        assetListAdapter.notifyDataSetChanged();
//    }

    /*
     * A TransferListener class that can listen to a upload task and be notified
     * when the status changes.
     */
    public class UploadListener implements TransferListener {

        // Simply updates the UI list when notified.
        @Override
        public void onError(int id, Exception e)
        {
            failedcounter++;
            updateList();

        }

        @Override
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

            updateList();

            currentbyte =bytesCurrent;
            totalbyte =bytesTotal;
            Log.d("onprogresschnaged","method bytes"+bytesCurrent+" bytestotoal"+bytesTotal);
        }

        @Override
        public void onStateChanged(int id, TransferState newState)
        {
            if (newState.equals(TransferState.COMPLETED))
            {
                counter++;
                updateList();
            } else if (newState.equals(TransferState.FAILED))
            {
                failedcounter++;
               updateList();
            }




        }

    }
    /*
     * Updates the ListView according to the observers.
     */
    /*
     * Updates the ListView according to the observers.
     */
    public void updateList()
    {
        if(transferRecordMaps!=null&&transferRecordMaps.size()>0)
        {
            TransferObserver observer = null;
            HashMap<String, Object> map = null;
            for (int i = 0; i < observers.size(); i++) {
                observer = observers.get(i);
                map = transferRecordMaps.get(i);
                 progress = (int) ((double) observer.getBytesTransferred() * 100 / observer
                        .getBytesTotal());

                Log.d("progressuploadingData"," map"+progress);

                Util.fillMap(map, observer, i == checkedIndex);
                Log.d("uploadingData"," map"+map+" observer"+observer);

            }
            transferRecordMaps1.clear();
            for (int i = 0; i < transferRecordMaps.size(); i++)
            {
                File file = new File((String) transferRecordMaps.get(i).get("fileName"));
                if (file.getName().substring(0, 2).equalsIgnoreCase("0!")) {
                } else
                {
                    transferRecordMaps1.add(transferRecordMaps.get(i));

                }
                totalcount=transferRecordMaps.size();
                totalAssetCount=counter+failedcounter;
                Log.d("totalcount","count"+totalcount+"toatlassetcount"+totalAssetCount);
                if(counter>1&&totalAssetCount>=totalcount&&GlobalVariables.assetMediaDTOList.size()>0)
                {
                    Log.d("myservice asset","complete");
                    navigate=1;

                    Intent intent = new Intent(this, DialogeActivity.class);
                    context.getApplicationContext().startActivity(intent);

                   // Toast.makeText(this,"Your asset uploaded successfully",Toast.LENGTH_LONG).show();
//                    Intent notificationIntent = new Intent(this, DialogeActivity.class);
//                    notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
//                    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//                            | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                    startActivity(notificationIntent);


//                    Notification notification = new NotificationCompat.Builder(this)
//                            .setContentTitle("Visibly")
//                            .setTicker("asset uploaded")
//                            .setContentText("asset uploaded successfully")
//                            .setSmallIcon(R.drawable.ic_launcher)
//                            .build();





//                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
//                    builder.setTitle("Test dialog");
//                    builder.setIcon(R.drawable.icon);
//                    builder.setMessage("Content");
//                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//                        public void onClick(DialogInterface dialog, int whichButton) {
//                            //Do something
//                            dialog.dismiss();
//                        });
//
//                        AlertDialog alert = builder.create();
//            alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                alert.show();

//                    AlertDialog alertDialog = new AlertDialog.Builder(this)
//                            .setTitle("Title")
//                            .setMessage("Are you sure?")
//                            .create();
//
//                    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                    alertDialog.show();
//                    button_Done.setVisibility(View.VISIBLE);
//                    button_Done.setText("Done");
//                    button_Done.setEnabled(true);
//                    button_Done.setClickable(true);

                }else if(failedcounter>=totalcount)
                {
                    navigate=0;
//                    button_Done.setVisibility(View.VISIBLE);
//                    button_Done.setText("Back");
//                    button_Done.setEnabled(true);
//                    button_Done.setClickable(true);
                }else
                {
//                    button_Done.setVisibility(View.VISIBLE);
//                    button_Done.setText("Please wait.");
//                    button_Done.setEnabled(false);
//                    button_Done.setClickable(false);
                }
            }


           // assetListAdapter.notifyDataSetChanged();
        }else
        {
//            Intent intent=null;
//            if( AssetFolderActivity.folderDTO!=null&&AssetFolderActivity.folderDTO.getFolderIdentity()!=null&& AssetFolderActivity.folderDTO.getFolderIdentity().length()>0&&!AssetFolderActivity.folderDTO.getFolderIdentity().equalsIgnoreCase("")) {
//                intent = new Intent(activity, AssetFolderActivity.class);
//            }else
//            {
//                intent = new Intent(activity, DashboardActivity.class);
//            }
//            intent.putExtra("folderDTO", AssetFolderActivity.folderDTO);
//            activity.startActivity(intent);
//            activity.finish();
        }

    }

    private void initData() {
        counter=0;
        failedcounter=0;
        navigate=0;
        transferRecordMaps.clear();
        transferRecordMaps1.clear();
        // Use TransferUtility to get all upload transfers.
        observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
        TransferListener listener =  new ForegroundService().new UploadListener();
        for (TransferObserver observer : observers) {

            // For each transfer we will will create an entry in
            // transferRecordMaps which will display
            // as a single row in the UI
            HashMap<String, Object> map = new HashMap<String, Object>();
            Util.fillMap(map, observer, false);

            transferRecordMaps.add(map);

            // Sets listeners to in progress transfers
            if (TransferState.WAITING.equals(observer.getState())
                    || TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
                    || TransferState.IN_PROGRESS.equals(observer.getState())) {
                observer.setTransferListener(listener);
            }
        }
        transferRecordMaps1.clear();
        for(int i=0;i<transferRecordMaps.size();i++)
        {
            File file = new File((String) transferRecordMaps.get(i).get("fileName"));
            if(file.getName().substring(0,2).equalsIgnoreCase("0!"))
            {
            }
            else
            {
                transferRecordMaps1.add(transferRecordMaps.get(i));
            }

        }
       // assetListAdapter.notifyDataSetChanged();
    }

}

4 个答案:

答案 0 :(得分:0)

  

服务只允许在onStartCommand()方法中使用getApplcationContext / this / context

没有这样的限制。您可以在Service上的其他方法中使用该方法,只要onCreate()已调用Service

因此,要显示来自某个后台帖子的NotificationService onStartCommand()来自this,请使用if (instance1 == instance2) //...

答案 1 :(得分:0)

服务是Context类的子级,可在您需要时为您提供上下文。 它的行为就像一个活动(也是上下文的孩子。)

活动相同,您可以将thisyourService.this(在匿名类中)关键字作为上下文调用。

答案 2 :(得分:0)

updateList()中执行此操作:

context.getApplicationContext().startActivity(intent);

contextService的成员变量。但是,您永远不会将此变量初始化为任何内容。因此它是null,这将导致您描述的错误。

答案 3 :(得分:-1)

服务有自己的背景。有一个简单的方法来拥有一个globl上下文。

private Context context;

@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
    context = this;
}

这就是全部。应该工作,如果不是在其他地方搜索问题。

@Edit
为清楚起见,您的问题导致此行,因为您的上下文未分配,并且它为空。

context.getApplicationContext().startActivity(intent);