Как получить контекст в сервисе вне метода onStartCommand ()? - PullRequest
0 голосов
/ 15 мая 2018

Когда я использую Intent вне onStartCommand () службы, чтобы показать уведомление о конкретном событии, он показывает getApplicationContext на нулевой ссылке на объект.Сервис позволяет только использовать getApplcationContext / this / context внутри метода onStartCommand ().Как я могу использовать его вне метода 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 голосов
/ 16 мая 2018

В updateList() вы делаете это:

context.getApplicationContext().startActivity(intent);

context является переменной-членом вашего Service.Однако вы никогда не инициализируете эту переменную ни для чего.Поэтому это null, что приведет к описанной вами ошибке.

0 голосов
/ 15 мая 2018

Сервисы имеют свой собственный контекст. Есть простой способ иметь глобальный контекст.

private Context context;

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

Вот и все. Должно работать, если не позволяют искать проблему в другом месте.

@ Редактировать
Для ясности, ваша проблема вызывает эту строку, потому что ваш контекст не назначен, и он нулевой.

context.getApplicationContext().startActivity(intent);
0 голосов
/ 15 мая 2018

Служба является дочерней по классу Context, который предоставит вам контекст, когда вам нужно. Он ведет себя как действие (тоже дочерний контекст.)

Так же, как и Деятельность , вы можете позвонить this или yourService.this (в классе анонимуса)Ключевое слово как контекст.

0 голосов
/ 15 мая 2018

Сервис разрешает использовать только getApplcationContext / this / context внутри метода onStartCommand ()

Нет такого ограничения. Вы можете использовать его из других методов вашего Service, если onCreate() уже был вызван для этого Service.

Итак, чтобы показать Notification из некоторого фонового потока, который ваши Service разветвляют из onStartCommand(), например, используйте this.

...