Как изменить имя пакета android приложения

How do you rename packages in the new IDE Android Studio, based on IntelliJ IDEA? Is there an automatic refactoring included? I want to make bulk refactoring, but I don't know how. I worked two ...

In Android Studio, you can do this:

For example, if you want to change com.example.app to my.awesome.game, then:

  1. In your Project panel, click on the little gear icon ( Gears icon )

  2. Uncheck the Compact Empty Middle Packages option

    Compact Empty Middle Packages

  3. Your package directory will now be broken down into individual directories

  4. Individually select each directory you want to rename, and:

  • Right-click on it

  • Select Refactor

  • Click on Rename

  • In the pop-up dialog, click on Rename Package instead of Rename Directory

  • Enter the new name and hit Refactor

  • Click Do Refactor in the bottom

  • Allow a minute to let Android Studio update all changes

  • Note: When renaming com in Android Studio, it might give a warning. In such case, select Rename All

    Enter image description here

  1. Now open your Gradle Build File (build.gradle — Usually app or mobile). Update the applicationId in the defaultConfig to your new Package Name and Sync Gradle, if it hasn’t already been updated automatically:

    Refactor Directories

  2. You may need to change the package= attribute in your manifest.

  3. Clean and Rebuild.

    Clean and Rebuild

  4. Done! Anyway, Android Studio needs to make this process a little simpler.

Chetan Goyal's user avatar

answered Mar 17, 2015 at 6:32

Sheharyar's user avatar

SheharyarSheharyar

72.3k20 gold badges168 silver badges213 bronze badges

69

Another good method is: First create a new package with the desired name by right clicking on the Java folder → NewPackage.

Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.

Finally, delete the old package.

Done.

Very important:

You have to manually change AndroidManifest.xml and build.gradle file to the new package if you use this method.

Peter Mortensen's user avatar

answered Sep 5, 2013 at 12:57

user10F64D4's user avatar

user10F64D4user10F64D4

6,4811 gold badge13 silver badges12 bronze badges

21

Changing the application ID (which is now independent of the package name) can be done very easily in one step.
You don’t have to touch AndroidManifest.
Instead do the following:

  1. right click on the root folder of your project.
  2. Click «Open Module Setting».
  3. Go to the Flavours tab.
  4. Change the applicationID to whatever package name you want. Press OK.

Note this will not change the package name. The decoupling of Package Name and Application ID is explained here:
http://tools.android.com/tech-docs/new-build-system/applicationid-vs-packagename

LarsH's user avatar

LarsH

27.1k8 gold badges92 silver badges151 bronze badges

answered Feb 5, 2015 at 4:42

Moj's user avatar

MojMoj

2,8421 gold badge13 silver badges9 bronze badges

22

The approach used by me for renaming the package name is as follows:-

Step 1
: Select the Project option from the left menu of Android Studio

enter image description here

Step 2
: Right-click on java and add a new package and set the desired package name

enter image description here

Step 3
: Enter your new package name

enter image description here

Step 4
:Copy all the files from your old package and paste into the new package

enter image description here

Step 5
:Rename the package name in the manifest file

enter image description here

Step 6
:Rename the package name in build.gradle file

enter image description here

Step 7
:Then right-click the old package and delete it with all its data, and delete that directory as well

enter image description here

Step 8
:Then Rebuild your project

enter image description here

Step 9
:Then you will find some errors of old import packagename in your project
Select the old package name in any file and press CTRL + Shift + R , and enter your new package name in replace box, then press find

enter image description here

Step 10
:Then a popup appears like below and select the All files option from it

enter image description here

Step 11
:Rebuild your project again, bingo your project packagename has been changed :)

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Sep 26, 2016 at 11:34

Mehroz Munir's user avatar

Mehroz MunirMehroz Munir

2,1681 gold badge17 silver badges16 bronze badges

8

  1. Go to your AndroidManifest.xml file.

  2. Place your cursor in the package name as shown below. Don’t select it, just place it.

    Enter image description here

  3. Then press Shift + F6 and you will get a popup window as shown below. Select
    Rename package.

    Enter image description here

  4. Enter your new name and select Refactor.
    (Note: since my cursor is on «something», only something is renamed.)

That’s it done.

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Jan 28, 2016 at 9:28

priwiljay's user avatar

priwiljaypriwiljay

2,5331 gold badge17 silver badges21 bronze badges

7

Right-click on the package at the Project Panel.

Choose Refactor -> Rename from the context menu.

Burak Tokak's user avatar

Burak Tokak

1,7651 gold badge21 silver badges27 bronze badges

answered May 29, 2013 at 2:03

GreyBeardedGeek's user avatar

GreyBeardedGeekGreyBeardedGeek

28.8k2 gold badges47 silver badges66 bronze badges

6

Change the Package Name


To rename your package name, all you have to do is go to your AndroidManifest.xml file and put your mouse cursor in front of the part of the package name you want to change.


enter image description here


Right-Click > Refactor > Rename


enter image description here


In the new window press Rename package


enter image description here


Change name and press Refactor


enter image description here


…and press Do Refactor at the bottom.


enter image description here


Your package name usually is in format com.domain.appname; in this example we changed the appname part, but you can do the same steps for the domain too.

Done! You have changed your package name!

answered Dec 2, 2019 at 4:53

VIISHRUT MAVANII's user avatar

VIISHRUT MAVANIIVIISHRUT MAVANII

10.9k6 gold badges33 silver badges48 bronze badges

3

  1. Open the file:

    app → manifests → AndroidManifest.xml

    Enter image description here

    Highlight each part in the package name that you want to modify (don’t highlight the entire package name) then:

    • Mouse right-click → Refactor → Rename → Rename package
    • type the new name and press (Refactor)

    Do these steps in each part of the package name.

    Enter image description here

  2. Open (Gradle Script) >> (build.gradle(Modul:app))

    and update the applicationId to your package name

    Enter image description here

  3. Open the menu (build) and choose (Rebuild Project).

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Jul 7, 2015 at 12:38

alhamdi's user avatar

alhamdialhamdi

4294 silver badges5 bronze badges

5

Android Studio 2022


Step by Step Implementation

Step 1: To rename package name in Android studio open your project in Android mode first as shown in the below image.

Step 2: Now click on the setting gear icon and deselect Compact Middle Packages.

Step 3: Now the packages folder is broken into parts as shown in the below image.

Step 4: Now right-click on the first package name (com) and Refactor > Rename. A warning message will be displayed but go ahead and click on the Rename current button.

Step 5: Rename the directory name as your requirement and click on the Refactor button.

Note: Go to Build > Rebuild Project to display the updated name.

Now you can see your directory name changes from com -> gfg as shown in the below image.

Step 6: Do the same for the domain extension and App folder name according to your requirement.

Now you can see the package name has been changed from com.example.pulltorefreshwithlistview to gfg.geeksforgeeks.listview as shown in the below image.

Step 7: Now go to the build.gradle (Module: app) in Gradle Scripts. Here change the applicationId and click on Sync Now. And you are successfully renamed your package name.


Source:
How to Rename Package Name in Android Studio?

answered Mar 12, 2022 at 17:57

Pedro Lobito's user avatar

Pedro LobitoPedro Lobito

91.2k30 gold badges244 silver badges263 bronze badges

I have seen the top voted answers but i found is a little bit different to do this, i try to do the most complete tutorial.

From the Android Studio click over the gear icon ( Gears icon ) and then select the option: "Compact Empty Middle Packages", to see the folders separated in a tree view.

introducir la descripción de la imagen aquí

Now select the folder, click right button to open the contextual menu, select Refactor and then Rename

introducir la descripción de la imagen aquí

You will be advised to refactor the package:

introducir la descripción de la imagen aquí

Then a window will show the coincidences inside the proyect, select "Do Refactor":

introducir la descripción de la imagen aquí

We don´t have to change manually the AndroidManifest.xml or build.gradle files, Refactoring the package will do the job!.

answered Sep 15, 2016 at 21:25

Jorgesys's user avatar

JorgesysJorgesys

123k23 gold badges328 silver badges264 bronze badges

Select the package that will be refactored. RefactorMove«Move xxx to new package».

Peter Mortensen's user avatar

answered Oct 6, 2014 at 10:50

hoot's user avatar

hoothoot

1,17513 silver badges15 bronze badges

2

If your package name is more than two dot separated, say com.hello.world and moreover, you did not put anything in com/ and com/hello/. All of your classes are putting into com/hello/world/, you might DO the following steps to refactoring your package name(s) in Android Studio or IntelliJ:

  • [FIRST] Add something under your directories(com/, com/hello/). You can
    achieve this by first add two files to package com.hello.world, say
   com.hello.world.PackageInfo1.java
   com.hello.world.PackageInfo2.java

then refactor them by moving them to com and com.hello respectively.
You will see com and com.hello sitting there at the Project(Alt+1
or Command+1 for shortcut) and rename directories refactoring is
waiting there as you expected.

  • Refactor to rename one or more of these directories to reach your aim. The only thing you should notice here is you must choose the directories rather than Packages when a dialog ask you.

  • If you’ve got lots of classes in your project, it will take you a while to wait for its auto-scan-and-rename.

  • Besides, you need to rename the package name inside the AndroidManifest.xml manually, I guess, such that other names in this file can benefit the prefix.

  • [ALSO], it might need you to replace all com.hello.world.R to the new XXX.XXX.XXX.R(Command+Shift+R for short)

  • Rebuild and run your project to see whether it work. And use «Find in Path» to find other non-touch names you’d like to rename.

  • Enjoy it.

answered Jun 7, 2013 at 16:20

dongxu's user avatar

dongxudongxu

1411 silver badge6 bronze badges

0

Quick and easy way in 3 steps:

1- open MainActivity or any other java or Kotlin file.

At the top there is the package declaration such as:

package com.example.myapp;

select the package portion that you want to change and press Shift+F6. I personally want to change the example.

In the warning dialog, select Rename package and then insert the desired package name.

2- Open AndroidManifest.xml and inside <manifest> tag change the package to the desired package name.

3- open build.gradle(Module: app) and change the applicationId to the desired package name.

answered Nov 16, 2016 at 17:15

Darush's user avatar

DarushDarush

11.1k9 gold badges61 silver badges60 bronze badges

1

Be sure to go to Sheharyar’s great Answer. There are so many answers and comments that follow it that it would be easy to get confused and give up, but don’t. That answer works.

In short, you do three things:

(1) Deselect Compact Empty Middle Packages.

(2) Refactor then Rename each old directory node by choosing Change Package (not Change Directory) to match the new package name. (Be sure to do a preview of changes.)

(3) Edit the build.gradle file and make APPLICATION_ID match the new package name.

answered Apr 30, 2015 at 5:42

DSlomer64's user avatar

DSlomer64DSlomer64

4,1744 gold badges49 silver badges86 bronze badges

2

I’ve found a way easier solution to this problem which also changed the generated imports like com.test.testpackagechange.R and only takes about a minute.

Your first step is to open Android Studio and open the replace all window (Mac: cmd + shift + R, Windows I assume: ctrl + shift + R). Type in your old package name and in the one below your new package name. Click Find. This may take a while because it is also looking through the generated items. If it has over 1000 hits, just click continue.

enter image description here

After you’ve done that push Replace All to replace your old package name with your new one.

enter image description here

Now close Android Studio and go to Finder on Mac or Windows Explorer on Windows. Change the name of the folders to your new package name, like this:

enter image description here

Now open Android Studio again. Gradle will sync and your package name should be changed to the new one.

I’ve found this to be the easiest one and the one that covers all areas like generated files.

answered Mar 20, 2017 at 19:59

Kevin van Mierlo's user avatar

Kevin van MierloKevin van Mierlo

9,4325 gold badges43 silver badges70 bronze badges

The common mistake that one can make is one cannot rename the package structure i.e. it is not possible to change com.name.android to com.Renamed.android when one tries to modify at the com.name.android level.

In order to have the same desired change go one level up i.e com.name and here when you refactor change it to Renamed. This will work always.

Peter Mortensen's user avatar

answered Apr 30, 2015 at 10:34

Shivanand T's user avatar

Shivanand TShivanand T

1,0131 gold badge9 silver badges17 bronze badges

  1. Select the package name in the Java folder.
  2. Shift+F6
  3. Change the package name and click OK.

Your package name will be changed from all the Java files and the manifest file. You have to manually change the package name from build.gradle.

Peter Mortensen's user avatar

answered Feb 4, 2016 at 6:13

himanshu.tiwari's user avatar

1

Updated answer: May 2015

OK I have been struggling with cloning & renaming projects in Android Studio, but finally I achieved it. Here are the steps to follow:

  1. Copy the project folder, rename it & open it with Android Studio
  2. Rename module directory from explorer
  3. Rename projectName.iml and content
  4. Rename idea/.name content
  5. In your Project pane, click on the little gear icon -> uncheck «Compact Empty Middle Package»
  6. Refactor src directories for new package name (rename package, «not rename directory»)
  7. In build.gradle rename application id
  8. settings.gradle rename module

That’s it…

answered May 15, 2015 at 19:18

Sebastian Breit's user avatar

Sebastian BreitSebastian Breit

6,1291 gold badge34 silver badges53 bronze badges

Packages serve two purposes. One is to uniquely identify your app in the Google Play Store. The other is to name the package for the R.java class which is generated when you build your project. You can think of the first purpose as the external package and the second as the internal package. Assuming you want to change the external package so you can identify in the Play store, there’s a convenient way to do this.

In Android Studio,

 choose File -> Project Structure -> Choose your app's module -> Click on the 
 Flavors tab -> change the Application id.

Now, when you build your project,
your APK and manifest will use this new package name.

Agilanbu's user avatar

Agilanbu

2,7312 gold badges28 silver badges33 bronze badges

answered Sep 18, 2014 at 2:40

zafirk's user avatar

zafirkzafirk

691 silver badge1 bronze badge

I found another way that works or an extra step to some of the answers here especially if you want to change the domain as well. It works in Android Studio 1.4. This is what I did:

  1. Open Manifest.xml and change the package name to what you want.
  2. Open your app build.gradle file and change the Application Id in defaultConfig to the same name as in manifest and rebuild the project.
  3. If still an issue, open a file under the package name, go to the package breadcrumbs (i.e. package declaration at head of file) and set your cursor to the domain you want to change and hit «Shift + F6», it would come out with a dialog with multiple use warnings, click on «Rename packages» and then click on «Do Refactor» it should rename everything including the R.Java files.

So for example if you want to rename «com.example.app» to «com.YourDomain.app», open a file under the package to be renamed, in the package breadcrumbs, set your cursor to «example» part of the domain and hit Shift + F6 and rename package to «YourDomain».

Peter Mortensen's user avatar

answered Oct 16, 2015 at 16:14

irobotxx's user avatar

irobotxxirobotxx

5,84311 gold badges61 silver badges91 bronze badges

I tried the two top-voted solutions but found some issues even though both work to some extent.

  • List item: The new package-drag-drop method leaves some unchanged and creates some undesired effects
  • List item: The rename package only changes the last part of the package name

After some experiments, I found the following method works well for me.

If you just need to change the last part of the package name, use the method outlined by GreyBeardedGeek, namely

Right-click on the package in the Project pane. Choose Refactor -> Rename from the context menu

If you need to change the whole package name, do the following.

Right-click on the package in the Project pane. Choose Refactor -> Move from the context menu

This will create a new package folder (when necessary) but will keep the last part of your package name as before. If you need to change the last part, do the rename accordingly.

Note also that you may need to modify package names in e.g. build.gradle, manifest, and/or any xml resource files, or even in your code if hardcoded. After all that, do Sync/Clean/Rebuild project as necessary.

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Oct 24, 2014 at 17:57

ssgg Google Developer Platform's user avatar

How to rename com.example.app to com.android.app:

  1. in package com.example.app select example

  2. Shift + F6

  3. choose rename package

  4. rename example to android

  5. confirm do refactor

Benjamin's user avatar

Benjamin

6,9045 gold badges39 silver badges60 bronze badges

answered Oct 10, 2018 at 12:19

Andrew Glukhoff's user avatar

The best way is to write the new package name and drag from the older package name.

The second way, if you click Refactor then move option then rename the package name, it will rename the package name and then rebuild.

In Build.gradle you have to do manually, if you Refactor then it will not rename in Build.gradle.

Peter Mortensen's user avatar

answered Mar 26, 2015 at 5:57

Ajay Keshri's user avatar

Right click on package -> refactor and change the name.

You can also change it in the manifest. Sometimes if you change the package name, but after creating the .apk file it shows a different package name. At that time check «applicationId» in the build.gradle file.

Peter Mortensen's user avatar

answered May 11, 2015 at 7:34

rajlaxmi_jagdale's user avatar

  • The first part consists of creating a new package under the java folder and selecting then dragging all your source files from the old package to this new package. After that, you need to rename the package name in android manifest` to the name of the new package.

  • In step 2, here is what you need to do. You need to change the old package name in applicationId under the module build.gradle in your android studio in addition to changing the package name in the manifest. So in summary, click on build.gradle which is below the «AndroidManifest.xml» and modify the value of applicationId to your new package name.

  • Then, at the very top, under build. clean your project, then rebuild. It should be fine from here.

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Aug 24, 2014 at 4:25

user3295929's user avatar

I recommend to use Sublime Text (or Notepad++). Replace com.one.lastname -> com.two.newname and com/one/lastname -> com/two/newname in …Projects[MyProject]. And don’t forget to rename …ProjectsMyProjectappsrcmainjavacomonelastname, …ProjectsMyProjectappsrctestjavacomonelastname and …ProjectsMyProjectappsrcandroidTestjavacomonelastname!

That’s all:)

Screenshot

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Apr 3, 2016 at 21:42

Ярослав Нестеров's user avatar

There are many answers given, but still, I am giving my attempt.

Step 1 :
As Show in the fig above select the Setting Option…
enter image description here

Step 2:
Select Compact Middle Packages option…
enter image description here

Step 3:
Now Expand the package as shown
enter image description here

Step 4:
After expanding it will look something like
enter image description here

Step 5:
Select any on the subpackage (in or example or googledevsmsverify) and click Shift+f6 button…
enter image description here

I selected middle package example so it will display as above fig
simple rename the package and click on the refactor button

enter image description here

Step 6:
you will see the following screen after clicking Refactor button, click on the DO Refactor, and wait until build the gradle…
enter image description here

Step 7:
Goto build.gradle(Mobile:app) and change the package name of applicationID as shown
enter image description here

Step 8:
Just check the package in the manifest.xml file…

enter image description here

All Done the package is change…@Ambilpura

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Aug 9, 2019 at 11:45

Ambilpura Sunil Kumar's user avatar

This I believe what you are looking for is Refactor > Move. You can also press F6.

You will get two popups. Make sure you select rename package on both. After that you will get a pop up to place the new package name.

Please note that if your package name is, for example, com.example.android.projectname then this will let you change com.example.android to something else.

One more thing, this will update the applicationId in your build.gradle as well. Just make sure that the checkboxes for «search in comments and strings» and «search for text occurrences» are both checked for it to work.

answered Mar 24, 2015 at 4:17

phxhawke's user avatar

phxhawkephxhawke

2,57122 silver badges17 bronze badges

  1. Select option enter image description here

  2. Uncheck the Compact Empty Middle Packages option.

  3. Select which directory you want to change(I have selected ‘crl’ shown in step 6).
  4. Shift+F6
  5. Rename Package
  6. Renaming directory crl to crl1
    enter image description here

  7. Finally click on Do Refactor button marked in image below
    enter image description here
    enter code here

  8. After Changes done
    enter image description here

Heinrich Cloete's user avatar

answered Aug 4, 2016 at 11:37

Shiv Buyya's user avatar

Shiv BuyyaShiv Buyya

3,53929 silver badges24 bronze badges

In Android Studio, you can do this:

For example, if you want to change com.example.app to my.awesome.game, then:

  1. In your Project panel, click on the little gear icon ( Gears icon )

  2. Uncheck the Compact Empty Middle Packages option

    Compact Empty Middle Packages

  3. Your package directory will now be broken down into individual directories

  4. Individually select each directory you want to rename, and:

  • Right-click on it

  • Select Refactor

  • Click on Rename

  • In the pop-up dialog, click on Rename Package instead of Rename Directory

  • Enter the new name and hit Refactor

  • Click Do Refactor in the bottom

  • Allow a minute to let Android Studio update all changes

  • Note: When renaming com in Android Studio, it might give a warning. In such case, select Rename All

    Enter image description here

  1. Now open your Gradle Build File (build.gradle — Usually app or mobile). Update the applicationId in the defaultConfig to your new Package Name and Sync Gradle, if it hasn’t already been updated automatically:

    Refactor Directories

  2. You may need to change the package= attribute in your manifest.

  3. Clean and Rebuild.

    Clean and Rebuild

  4. Done! Anyway, Android Studio needs to make this process a little simpler.

Chetan Goyal's user avatar

answered Mar 17, 2015 at 6:32

Sheharyar's user avatar

SheharyarSheharyar

72.3k20 gold badges168 silver badges213 bronze badges

69

Another good method is: First create a new package with the desired name by right clicking on the Java folder → NewPackage.

Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.

Finally, delete the old package.

Done.

Very important:

You have to manually change AndroidManifest.xml and build.gradle file to the new package if you use this method.

Peter Mortensen's user avatar

answered Sep 5, 2013 at 12:57

user10F64D4's user avatar

user10F64D4user10F64D4

6,4811 gold badge13 silver badges12 bronze badges

21

Changing the application ID (which is now independent of the package name) can be done very easily in one step.
You don’t have to touch AndroidManifest.
Instead do the following:

  1. right click on the root folder of your project.
  2. Click «Open Module Setting».
  3. Go to the Flavours tab.
  4. Change the applicationID to whatever package name you want. Press OK.

Note this will not change the package name. The decoupling of Package Name and Application ID is explained here:
http://tools.android.com/tech-docs/new-build-system/applicationid-vs-packagename

LarsH's user avatar

LarsH

27.1k8 gold badges92 silver badges151 bronze badges

answered Feb 5, 2015 at 4:42

Moj's user avatar

MojMoj

2,8421 gold badge13 silver badges9 bronze badges

22

The approach used by me for renaming the package name is as follows:-

Step 1
: Select the Project option from the left menu of Android Studio

enter image description here

Step 2
: Right-click on java and add a new package and set the desired package name

enter image description here

Step 3
: Enter your new package name

enter image description here

Step 4
:Copy all the files from your old package and paste into the new package

enter image description here

Step 5
:Rename the package name in the manifest file

enter image description here

Step 6
:Rename the package name in build.gradle file

enter image description here

Step 7
:Then right-click the old package and delete it with all its data, and delete that directory as well

enter image description here

Step 8
:Then Rebuild your project

enter image description here

Step 9
:Then you will find some errors of old import packagename in your project
Select the old package name in any file and press CTRL + Shift + R , and enter your new package name in replace box, then press find

enter image description here

Step 10
:Then a popup appears like below and select the All files option from it

enter image description here

Step 11
:Rebuild your project again, bingo your project packagename has been changed :)

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Sep 26, 2016 at 11:34

Mehroz Munir's user avatar

Mehroz MunirMehroz Munir

2,1681 gold badge17 silver badges16 bronze badges

8

  1. Go to your AndroidManifest.xml file.

  2. Place your cursor in the package name as shown below. Don’t select it, just place it.

    Enter image description here

  3. Then press Shift + F6 and you will get a popup window as shown below. Select
    Rename package.

    Enter image description here

  4. Enter your new name and select Refactor.
    (Note: since my cursor is on «something», only something is renamed.)

That’s it done.

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Jan 28, 2016 at 9:28

priwiljay's user avatar

priwiljaypriwiljay

2,5331 gold badge17 silver badges21 bronze badges

7

Right-click on the package at the Project Panel.

Choose Refactor -> Rename from the context menu.

Burak Tokak's user avatar

Burak Tokak

1,7651 gold badge21 silver badges27 bronze badges

answered May 29, 2013 at 2:03

GreyBeardedGeek's user avatar

GreyBeardedGeekGreyBeardedGeek

28.8k2 gold badges47 silver badges66 bronze badges

6

Change the Package Name


To rename your package name, all you have to do is go to your AndroidManifest.xml file and put your mouse cursor in front of the part of the package name you want to change.


enter image description here


Right-Click > Refactor > Rename


enter image description here


In the new window press Rename package


enter image description here


Change name and press Refactor


enter image description here


…and press Do Refactor at the bottom.


enter image description here


Your package name usually is in format com.domain.appname; in this example we changed the appname part, but you can do the same steps for the domain too.

Done! You have changed your package name!

answered Dec 2, 2019 at 4:53

VIISHRUT MAVANII's user avatar

VIISHRUT MAVANIIVIISHRUT MAVANII

10.9k6 gold badges33 silver badges48 bronze badges

3

  1. Open the file:

    app → manifests → AndroidManifest.xml

    Enter image description here

    Highlight each part in the package name that you want to modify (don’t highlight the entire package name) then:

    • Mouse right-click → Refactor → Rename → Rename package
    • type the new name and press (Refactor)

    Do these steps in each part of the package name.

    Enter image description here

  2. Open (Gradle Script) >> (build.gradle(Modul:app))

    and update the applicationId to your package name

    Enter image description here

  3. Open the menu (build) and choose (Rebuild Project).

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Jul 7, 2015 at 12:38

alhamdi's user avatar

alhamdialhamdi

4294 silver badges5 bronze badges

5

Android Studio 2022


Step by Step Implementation

Step 1: To rename package name in Android studio open your project in Android mode first as shown in the below image.

Step 2: Now click on the setting gear icon and deselect Compact Middle Packages.

Step 3: Now the packages folder is broken into parts as shown in the below image.

Step 4: Now right-click on the first package name (com) and Refactor > Rename. A warning message will be displayed but go ahead and click on the Rename current button.

Step 5: Rename the directory name as your requirement and click on the Refactor button.

Note: Go to Build > Rebuild Project to display the updated name.

Now you can see your directory name changes from com -> gfg as shown in the below image.

Step 6: Do the same for the domain extension and App folder name according to your requirement.

Now you can see the package name has been changed from com.example.pulltorefreshwithlistview to gfg.geeksforgeeks.listview as shown in the below image.

Step 7: Now go to the build.gradle (Module: app) in Gradle Scripts. Here change the applicationId and click on Sync Now. And you are successfully renamed your package name.


Source:
How to Rename Package Name in Android Studio?

answered Mar 12, 2022 at 17:57

Pedro Lobito's user avatar

Pedro LobitoPedro Lobito

91.2k30 gold badges244 silver badges263 bronze badges

I have seen the top voted answers but i found is a little bit different to do this, i try to do the most complete tutorial.

From the Android Studio click over the gear icon ( Gears icon ) and then select the option: "Compact Empty Middle Packages", to see the folders separated in a tree view.

introducir la descripción de la imagen aquí

Now select the folder, click right button to open the contextual menu, select Refactor and then Rename

introducir la descripción de la imagen aquí

You will be advised to refactor the package:

introducir la descripción de la imagen aquí

Then a window will show the coincidences inside the proyect, select "Do Refactor":

introducir la descripción de la imagen aquí

We don´t have to change manually the AndroidManifest.xml or build.gradle files, Refactoring the package will do the job!.

answered Sep 15, 2016 at 21:25

Jorgesys's user avatar

JorgesysJorgesys

123k23 gold badges328 silver badges264 bronze badges

Select the package that will be refactored. RefactorMove«Move xxx to new package».

Peter Mortensen's user avatar

answered Oct 6, 2014 at 10:50

hoot's user avatar

hoothoot

1,17513 silver badges15 bronze badges

2

If your package name is more than two dot separated, say com.hello.world and moreover, you did not put anything in com/ and com/hello/. All of your classes are putting into com/hello/world/, you might DO the following steps to refactoring your package name(s) in Android Studio or IntelliJ:

  • [FIRST] Add something under your directories(com/, com/hello/). You can
    achieve this by first add two files to package com.hello.world, say
   com.hello.world.PackageInfo1.java
   com.hello.world.PackageInfo2.java

then refactor them by moving them to com and com.hello respectively.
You will see com and com.hello sitting there at the Project(Alt+1
or Command+1 for shortcut) and rename directories refactoring is
waiting there as you expected.

  • Refactor to rename one or more of these directories to reach your aim. The only thing you should notice here is you must choose the directories rather than Packages when a dialog ask you.

  • If you’ve got lots of classes in your project, it will take you a while to wait for its auto-scan-and-rename.

  • Besides, you need to rename the package name inside the AndroidManifest.xml manually, I guess, such that other names in this file can benefit the prefix.

  • [ALSO], it might need you to replace all com.hello.world.R to the new XXX.XXX.XXX.R(Command+Shift+R for short)

  • Rebuild and run your project to see whether it work. And use «Find in Path» to find other non-touch names you’d like to rename.

  • Enjoy it.

answered Jun 7, 2013 at 16:20

dongxu's user avatar

dongxudongxu

1411 silver badge6 bronze badges

0

Quick and easy way in 3 steps:

1- open MainActivity or any other java or Kotlin file.

At the top there is the package declaration such as:

package com.example.myapp;

select the package portion that you want to change and press Shift+F6. I personally want to change the example.

In the warning dialog, select Rename package and then insert the desired package name.

2- Open AndroidManifest.xml and inside <manifest> tag change the package to the desired package name.

3- open build.gradle(Module: app) and change the applicationId to the desired package name.

answered Nov 16, 2016 at 17:15

Darush's user avatar

DarushDarush

11.1k9 gold badges61 silver badges60 bronze badges

1

Be sure to go to Sheharyar’s great Answer. There are so many answers and comments that follow it that it would be easy to get confused and give up, but don’t. That answer works.

In short, you do three things:

(1) Deselect Compact Empty Middle Packages.

(2) Refactor then Rename each old directory node by choosing Change Package (not Change Directory) to match the new package name. (Be sure to do a preview of changes.)

(3) Edit the build.gradle file and make APPLICATION_ID match the new package name.

answered Apr 30, 2015 at 5:42

DSlomer64's user avatar

DSlomer64DSlomer64

4,1744 gold badges49 silver badges86 bronze badges

2

I’ve found a way easier solution to this problem which also changed the generated imports like com.test.testpackagechange.R and only takes about a minute.

Your first step is to open Android Studio and open the replace all window (Mac: cmd + shift + R, Windows I assume: ctrl + shift + R). Type in your old package name and in the one below your new package name. Click Find. This may take a while because it is also looking through the generated items. If it has over 1000 hits, just click continue.

enter image description here

After you’ve done that push Replace All to replace your old package name with your new one.

enter image description here

Now close Android Studio and go to Finder on Mac or Windows Explorer on Windows. Change the name of the folders to your new package name, like this:

enter image description here

Now open Android Studio again. Gradle will sync and your package name should be changed to the new one.

I’ve found this to be the easiest one and the one that covers all areas like generated files.

answered Mar 20, 2017 at 19:59

Kevin van Mierlo's user avatar

Kevin van MierloKevin van Mierlo

9,4325 gold badges43 silver badges70 bronze badges

The common mistake that one can make is one cannot rename the package structure i.e. it is not possible to change com.name.android to com.Renamed.android when one tries to modify at the com.name.android level.

In order to have the same desired change go one level up i.e com.name and here when you refactor change it to Renamed. This will work always.

Peter Mortensen's user avatar

answered Apr 30, 2015 at 10:34

Shivanand T's user avatar

Shivanand TShivanand T

1,0131 gold badge9 silver badges17 bronze badges

  1. Select the package name in the Java folder.
  2. Shift+F6
  3. Change the package name and click OK.

Your package name will be changed from all the Java files and the manifest file. You have to manually change the package name from build.gradle.

Peter Mortensen's user avatar

answered Feb 4, 2016 at 6:13

himanshu.tiwari's user avatar

1

Updated answer: May 2015

OK I have been struggling with cloning & renaming projects in Android Studio, but finally I achieved it. Here are the steps to follow:

  1. Copy the project folder, rename it & open it with Android Studio
  2. Rename module directory from explorer
  3. Rename projectName.iml and content
  4. Rename idea/.name content
  5. In your Project pane, click on the little gear icon -> uncheck «Compact Empty Middle Package»
  6. Refactor src directories for new package name (rename package, «not rename directory»)
  7. In build.gradle rename application id
  8. settings.gradle rename module

That’s it…

answered May 15, 2015 at 19:18

Sebastian Breit's user avatar

Sebastian BreitSebastian Breit

6,1291 gold badge34 silver badges53 bronze badges

Packages serve two purposes. One is to uniquely identify your app in the Google Play Store. The other is to name the package for the R.java class which is generated when you build your project. You can think of the first purpose as the external package and the second as the internal package. Assuming you want to change the external package so you can identify in the Play store, there’s a convenient way to do this.

In Android Studio,

 choose File -> Project Structure -> Choose your app's module -> Click on the 
 Flavors tab -> change the Application id.

Now, when you build your project,
your APK and manifest will use this new package name.

Agilanbu's user avatar

Agilanbu

2,7312 gold badges28 silver badges33 bronze badges

answered Sep 18, 2014 at 2:40

zafirk's user avatar

zafirkzafirk

691 silver badge1 bronze badge

I found another way that works or an extra step to some of the answers here especially if you want to change the domain as well. It works in Android Studio 1.4. This is what I did:

  1. Open Manifest.xml and change the package name to what you want.
  2. Open your app build.gradle file and change the Application Id in defaultConfig to the same name as in manifest and rebuild the project.
  3. If still an issue, open a file under the package name, go to the package breadcrumbs (i.e. package declaration at head of file) and set your cursor to the domain you want to change and hit «Shift + F6», it would come out with a dialog with multiple use warnings, click on «Rename packages» and then click on «Do Refactor» it should rename everything including the R.Java files.

So for example if you want to rename «com.example.app» to «com.YourDomain.app», open a file under the package to be renamed, in the package breadcrumbs, set your cursor to «example» part of the domain and hit Shift + F6 and rename package to «YourDomain».

Peter Mortensen's user avatar

answered Oct 16, 2015 at 16:14

irobotxx's user avatar

irobotxxirobotxx

5,84311 gold badges61 silver badges91 bronze badges

I tried the two top-voted solutions but found some issues even though both work to some extent.

  • List item: The new package-drag-drop method leaves some unchanged and creates some undesired effects
  • List item: The rename package only changes the last part of the package name

After some experiments, I found the following method works well for me.

If you just need to change the last part of the package name, use the method outlined by GreyBeardedGeek, namely

Right-click on the package in the Project pane. Choose Refactor -> Rename from the context menu

If you need to change the whole package name, do the following.

Right-click on the package in the Project pane. Choose Refactor -> Move from the context menu

This will create a new package folder (when necessary) but will keep the last part of your package name as before. If you need to change the last part, do the rename accordingly.

Note also that you may need to modify package names in e.g. build.gradle, manifest, and/or any xml resource files, or even in your code if hardcoded. After all that, do Sync/Clean/Rebuild project as necessary.

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Oct 24, 2014 at 17:57

ssgg Google Developer Platform's user avatar

How to rename com.example.app to com.android.app:

  1. in package com.example.app select example

  2. Shift + F6

  3. choose rename package

  4. rename example to android

  5. confirm do refactor

Benjamin's user avatar

Benjamin

6,9045 gold badges39 silver badges60 bronze badges

answered Oct 10, 2018 at 12:19

Andrew Glukhoff's user avatar

The best way is to write the new package name and drag from the older package name.

The second way, if you click Refactor then move option then rename the package name, it will rename the package name and then rebuild.

In Build.gradle you have to do manually, if you Refactor then it will not rename in Build.gradle.

Peter Mortensen's user avatar

answered Mar 26, 2015 at 5:57

Ajay Keshri's user avatar

Right click on package -> refactor and change the name.

You can also change it in the manifest. Sometimes if you change the package name, but after creating the .apk file it shows a different package name. At that time check «applicationId» in the build.gradle file.

Peter Mortensen's user avatar

answered May 11, 2015 at 7:34

rajlaxmi_jagdale's user avatar

  • The first part consists of creating a new package under the java folder and selecting then dragging all your source files from the old package to this new package. After that, you need to rename the package name in android manifest` to the name of the new package.

  • In step 2, here is what you need to do. You need to change the old package name in applicationId under the module build.gradle in your android studio in addition to changing the package name in the manifest. So in summary, click on build.gradle which is below the «AndroidManifest.xml» and modify the value of applicationId to your new package name.

  • Then, at the very top, under build. clean your project, then rebuild. It should be fine from here.

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Aug 24, 2014 at 4:25

user3295929's user avatar

I recommend to use Sublime Text (or Notepad++). Replace com.one.lastname -> com.two.newname and com/one/lastname -> com/two/newname in …Projects[MyProject]. And don’t forget to rename …ProjectsMyProjectappsrcmainjavacomonelastname, …ProjectsMyProjectappsrctestjavacomonelastname and …ProjectsMyProjectappsrcandroidTestjavacomonelastname!

That’s all:)

Screenshot

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Apr 3, 2016 at 21:42

Ярослав Нестеров's user avatar

There are many answers given, but still, I am giving my attempt.

Step 1 :
As Show in the fig above select the Setting Option…
enter image description here

Step 2:
Select Compact Middle Packages option…
enter image description here

Step 3:
Now Expand the package as shown
enter image description here

Step 4:
After expanding it will look something like
enter image description here

Step 5:
Select any on the subpackage (in or example or googledevsmsverify) and click Shift+f6 button…
enter image description here

I selected middle package example so it will display as above fig
simple rename the package and click on the refactor button

enter image description here

Step 6:
you will see the following screen after clicking Refactor button, click on the DO Refactor, and wait until build the gradle…
enter image description here

Step 7:
Goto build.gradle(Mobile:app) and change the package name of applicationID as shown
enter image description here

Step 8:
Just check the package in the manifest.xml file…

enter image description here

All Done the package is change…@Ambilpura

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered Aug 9, 2019 at 11:45

Ambilpura Sunil Kumar's user avatar

This I believe what you are looking for is Refactor > Move. You can also press F6.

You will get two popups. Make sure you select rename package on both. After that you will get a pop up to place the new package name.

Please note that if your package name is, for example, com.example.android.projectname then this will let you change com.example.android to something else.

One more thing, this will update the applicationId in your build.gradle as well. Just make sure that the checkboxes for «search in comments and strings» and «search for text occurrences» are both checked for it to work.

answered Mar 24, 2015 at 4:17

phxhawke's user avatar

phxhawkephxhawke

2,57122 silver badges17 bronze badges

  1. Select option enter image description here

  2. Uncheck the Compact Empty Middle Packages option.

  3. Select which directory you want to change(I have selected ‘crl’ shown in step 6).
  4. Shift+F6
  5. Rename Package
  6. Renaming directory crl to crl1
    enter image description here

  7. Finally click on Do Refactor button marked in image below
    enter image description here
    enter code here

  8. After Changes done
    enter image description here

Heinrich Cloete's user avatar

answered Aug 4, 2016 at 11:37

Shiv Buyya's user avatar

Shiv BuyyaShiv Buyya

3,53929 silver badges24 bronze badges

18 ответов

Если вы используете Eclipse, вы можете попробовать эти инструкции с сайта разработчика Android. Они специально предназначены для примера GestureBuilder, но должны быть применимы к любому приложению, насколько я могу судить:

[H] как вы могли бы сделать это в Eclipse:

  • Щелкните правой кнопкой мыши имя пакета (src/com.android.gesture.builder).
  • Выберите «Рефакторинг» > «Переименовать» и изменить имя, например, com.android.gestureNEW.builder.
  • Откройте файл манифеста. Внутри <manifest>, измените имя пакета на com.android.gestureNEW.builder.
  • Откройте каждый из двух файлов Activity и сделайте Ctrl-Shift-O, чтобы добавить отсутствующие пакеты импорта, а затем сохраните каждый файл. Запустите приложение GestureBuilder на эмуляторе.

Кроме того, убедитесь, что вы запомнили переименование самого пакета вместе со ссылками на него в файлах. В Eclipse вы можете увидеть имя пакета в окне окна/дерева файла в левой части окна. По моему опыту, Eclipse иногда может быть немного фиктивным и ненадежным с этим (например, оставляя бездомные ссылки на старое имя пакета).

eldarerathis
26 окт. 2010, в 16:53

Поделиться

В Eclipse можно легко изменить имя пакета. Щелкните правой кнопкой мыши на своем проекте, прокрутите вниз до Android-инструментов и нажмите «Переименовать пакет приложений».

Marc Bernstein
26 окт. 2010, в 17:02

Поделиться

Здесь вы можете сделать это в Eclipse:

  • Щелкните правой кнопкой мыши имя пакета (src/com.android.gesture.builder).
  • Выберите Refactor > Rename и измените имя, например, на
    com.android.gestureNEW.builder.
  • Откройте файл манифеста. Внутри тега <manifest> измените имя пакета на com.android.gestureNEW.builder.
  • Откройте каждый из двух файлов Activity и сделайте Ctrl + Shift + O, чтобы добавить отсутствующие пакеты импорта, а затем сохраните каждый файл.
  • Запустите приложение GestureBuilder на эмуляторе.

Ссылка на сообщение

Обновление
супер легкий способ
щелкните правой кнопкой мыши по вашему проекту…
Изображение 108878

AZ_
07 фев. 2012, в 06:52

Поделиться

В Android Studio, который, честно говоря, вы должны использовать, измените имя пакета на right-clicking на имя пакета в project structure -> Refactor -> Rename...

Затем он дает возможность переименования каталога или пакета. Выберите пакет. Справочник должен следовать примеру. Введите новое имя пакета и нажмите «Refactor». Он изменит весь импорт и удалит избыточный импорт для вас. Вы даже можете исправить это для вас в комментариях и строках и т.д.

Наконец,, измените имя пакета в AndroidManifest.xml по направлению вверх. В противном случае вы получите ошибки повсюду, жалуясь на R.whatever.

Другое очень полезное решение

Сначала создайте новый пакет с нужным именем by right clicking on the java folder → new → package.`

Затем выберите и перетащите все ваши классы в новый пакет. AndroidStudio будет переопределять имя пакета везде.

После этого: в приложении build.gradle добавьте/отредактируйте applicationId с новым. т.е. (com.a.bc в моем случае):

defaultConfig {
    applicationId "com.a.bc"
    minSdkVersion 13
    targetSdkVersion 19
}

Оригинальная публикация и комментарии здесь

craned
11 окт. 2013, в 15:43

Поделиться

Без Eclipse:

  • Измените имя пакета и названия активности в AndroidManifext.xml и в любом другом месте в XML файлах (пользовательские имена и т.д.)

  • Обновить оператор импорта пакета во всех исходных файлах

  • Переименуйте все папки в соответствии с именем пакета. Расположение папок:
    а. bin/классы
    б. ген
    с. ЦСИ

  • Обновите имя проекта в файле build.xml(или ваше имя apk не изменится)

  • Удалите все файлы .class в bin/classes/com/example/myapp/(если вы пропустите этот шаг, файлы не будут перезаписаны во время сборки, а dex даст кучу проблем с обработкой «имя класса» не соответствуют пути «

  • Удалить gen/com/example/myapp/BuildConfig.java(я не знаю, почему удаление BuildConfig.class на шаге 3a не вызывало dex для обновления пути к этому, но до тех пор, пока я не удалю BuildConfig. java он продолжал воссоздавать gen/com/oldapp_example/oldapp и помещать там BuildConfig.class. Я не знаю, почему у R.java из того же места нет этой проблемы. Я подозреваю, что BuildConfig.java автоматически сгенерирован в pre -compile, но R.java нет)

Вышеуказанные 6 шагов — это то, что я сделал, чтобы изменить имя моего пакета и получить успешную * сборку. Может быть лучший способ обработать шаги 5 и 6 через команды dex для обновления путей или, возможно, путем редактирования classes.dex.d в корневой директории проекта. Я не знаком с dex или если это нормально для удаления/редактирования classes.dex.d, поэтому я пошел с методом удаления файлов .class, которые, как я знаю, будут восстановлены в сборке. Затем я проверил classes.dex.d, чтобы узнать, что еще нужно обновить.

* В моей сборке нет ошибок или предупреждений. EXCEPT dex и apkbuilder устанавливают состояние «Найденный удаленный целевой файл» без каких-либо особенностей того, что этот файл. Не уверен, что это отображается в каждой сборке, если она была там до того, как я испортился с моим именем пакета, или если это результат моих удалений, и мне не хватает шага.

clusterflux
04 янв. 2013, в 15:59

Поделиться

Самый быстрый способ сделать это в Android Studio 1.3:

  • Измените имя пакета в manifest
  • Перейдите в Module Settings[F4]-> Flavors, в Application Id введите одно и то же имя.
  • Создайте новый пакет с таким именем: [right-click-> new-> package]
  • Выберите все java файлы вашего проекта, а затем продолжите [Right-click-> Refactor-> Move-> {Select package}-> Refactor]

P.S. Если вы не будете следовать этому заказу, вы можете в конечном итоге изменить все java файлы один за другим с новыми импортерами и кучей ошибок времени компиляции, поэтому порядок очень важен.

Movsar Bekaev
02 сен. 2015, в 17:21

Поделиться

Выполните следующие действия: —

  • Щелкните правой кнопкой мыши проект.
  • Перейдите в Android-инструменты.
  • Нажмите «Переименовать пакет приложений».
  • Измените имя пакета приложения.

DONE

Deepak Sharma
25 сен. 2013, в 06:58

Поделиться

Изменение названия пакета — боль в заднице. Похоже, что разные методы работают для разных людей. Мое решение быстро и безошибочно. Похоже, что не требуется очистка или сброс затмения.

  • Щелкните правой кнопкой мыши имя пакета, затем Refractor > Rename.
  • Щелкните правой кнопкой мыши название проекта Android. > Переименуйте пакет приложений.
  • Вручную установите имена пакетов в манифесте, которые не были изменены предыдущими шагами.

erdomester
11 фев. 2012, в 22:31

Поделиться

  • Fist изменить имя пакета в файле манифеста
  • Re-factor > Переименуйте имя пакета в папку src и поставьте галочку для rename subpackages
  • Это все, что вы сделали.

Sathirar
29 дек. 2012, в 04:54

Поделиться

Я нашел самое легкое решение: Regexxer заменить «com.package.name» на «com.newpackage.name», а затем правильно переименуйте каталоги. Супер легкий, супер быстрый.

robisaks
12 авг. 2011, в 15:05

Поделиться

У Бернштейна есть метод, используйте инструмент Eclipse, «Переименуйте пакет приложений», вам, возможно, придется выполнить некоторую очистку даже после факта.
Кроме того, Eclipse иногда теряет смысл, когда вы вносите изменения в проект. Возможно, вам придется использовать инструмент «Чистый проект» (в меню «Проект».) Если это не сработает, возможно, вам придется закрыть и перезапустить Eclipse. Voo-doo, но Eclipse может быть таким.

m0j0
01 авг. 2011, в 15:51

Поделиться

Существует также другое решение для пользователей без Eclipse, просто измените атрибут package в <manifest> в AndroidManifest.xml, заменив прежнее имя пакета, используемое новым. Примечание.. Вы также должны вручную настроить все связанные операторы импорта и связанные с ними папки в своем проекте.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="new.package.name"
    .....
</manifest>

LikeYou
17 июль 2012, в 07:05

Поделиться

В Android Studio 1.2.2
Скажем, если вы хотите изменить com.example.myapp на org.mydomain.mynewapp
Вы можете выполнить шаги в каждом из каталогов, как показано на следующем снимке экрана. Он предоставит вам возможность предварительного просмотра, чтобы вы могли предварительно просмотреть все изменения.

Перейдите к Refactor -> Rename и укажите свое новое имя. Вы должны сделать это для каждой из папок, например, для com, example и myapp. Он автоматически обновит импорт, чтобы вам не пришлось беспокоиться об этом.
Изображение 108879

Также обновите файл build.gradle, который не обновляется автоматически.

defaultConfig {
        applicationId "org.mydomain.mynewapp" //update the new package name here
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }

После этого он попросит sync сделать это. Тогда все будет хорошо. После этого я могу загрузить APK в Google Store. Убедитесь, что вы подписали приложение, чтобы загрузить его в магазин.

Krishnadas PC
14 окт. 2015, в 15:06

Поделиться

Я просто потерял несколько часов, пытаясь найти все решения. Я был уверен, проблема в моем коде — запуск apk, но некоторые ошибки при работе с разными классами и действиями.

Только способ работы с моим проектом:

  • переименуйте его — файл/переименовать и отметьте все флажки
  • проверьте, не переименованные места, у меня было в одном из старых старое имя все еще в инструментах: context = «..
  • создать новое рабочее пространство
  • импортировать проект в новое рабочее пространство

Для меня это работает, только решение.

Dudeist
03 нояб. 2014, в 02:56

Поделиться

  • Щелкните правой кнопкой мыши по проекту > Инструменты Android > Переименуйте пакет приложений

  • Перейдите в src и щелкните правой кнопкой мыши на основном пакете > Рефакторинг > Переименовать

  • Перейдите в файл манифеста и измените имя своего пакета.

ritesh4326
26 фев. 2014, в 05:28

Поделиться

Альтернатива:

  • Открыть AndroidManifest.xml
  • Изменить пакет = «NEW NAME» в теге манифеста.

MapleLover
18 апр. 2013, в 16:27

Поделиться

Итак, использование IntelliJ с плагином Android (Studio) было следующим: я пошел в AndroidManifest.xml сверху и изменил имя пакета, щелкнув правой кнопкой мыши → Refactor → rename.
У нашего имени пакета было четыре части a.b.c.d, а новая — только a.b.c.
Поэтому я переименовал первые три. Затем я отправился в каталог сгенерированных источников (appbuildgeneratedsourcerdevelopmentdebugabcd), щелкнул правой кнопкой мыши R класс и Refactor- > Move [d] до одного пакета выше. То же самое с BuildConfig в appbuildgeneratedsourcebuildConfigdevelopmentdebugabcd.

Используя Refactor- > Move, IntelliJ обновляет все ссылки на BuildConfig и R.

Наконец, я обновил все applicationId [s], которые я нашел в gradle.build. Я ударил проект Clean Project, Make and Rebuild. Удалите приложение с моего телефона и нажмите «Играть». Все это сработало, поэтому рефакторинг был простым и довольно быстрым.

Raul Pinto
18 дек. 2015, в 15:54

Поделиться

Ещё вопросы

  • 1Проблема с vue.js для получения данных из REST API
  • 0объединить с двумя столбцами и получить значения полей из их внешнего ключа с помощью одного запроса SQL
  • 0AngularJS — Запуск функции один раз при загрузке
  • 1Пользовательская легенда из нескольких строк с двумя маркерами для одного и того же текста
  • 1Внедрение модели Keras на веб-сайт с помощью Keras.js
  • 0Найти сообщение с несколькими тегами [дубликаты]
  • 1объединять строки в кадре данных один за другим
  • 0если щелкнуть 3 из 5 изображений, перейдите по ссылке
  • 1Как преобразовать коллекцию элементов в «Текущий выбор» в Revit?
  • 0Обработка формы с использованием jQuery
  • 0Тайм-аут file_get_contents для конкретного сайта?
  • 0Присоедините параметр (ы) с помощью $ http Angularjs
  • 0Использование переменных в JavaScript для динамической ссылки на элементы HTML
  • 0Изображения не отображаются в строке
  • 1Создание столбца в Dataframe с использованием нескольких условий
  • 0Проблема угловой панели инструментов Js
  • 1проверить, если 2d массив действителен
  • 1Как мне использовать значение локальной переменной в angular2?
  • 1Результаты обратной матрицы разные в MATLAB и Python
  • 0При нажатии на прослушиватель событий в jquery
  • 1Создание Android-игры, странная регистрация клавиш на X10 Mini Pro
  • 0как использовать угловой гобой без «гобой не определено»
  • 1Нулевая ссылка ошибка C # несколько объектов
  • 1Холст анимация с JavaScript. Случайные координаты и скорость при каждом запуске
  • 0Как получить идентификатор запроса MySQL, который не совпадает с моим?
  • 0удалить дубликаты Camma из запроса MySQL
  • 1Как расположить кнопки в JFrame в Java?
  • 1Как проверить, подключен ли компьютер к интернету?
  • 0Firefox семейства шрифтов дочерние элементы не наследуют, в то время как Chrome работает правильно
  • 0Могу ли я иметь HA MySQL / MariaDB Slave?
  • 1startActivity на Android
  • 1Как применить ffill к 1?
  • 0Когда элемент находится в окне браузера, постепенно исчезают по порядку
  • 1Рабочая роль Azure Что пошло не так до метода OnRun ()?
  • 1Google Chart с динамическим массивом
  • 0Как прокрутить страницу вверх, если после 10 минут ни один пользователь не активен на веб-странице?
  • 1Как нарисовать горизонтальную линию в ListView?
  • 1JSONP с Джерси
  • 0SoapUI — Сервис не возвращает операций
  • 0Возврат невременного объекта из функции C ++ с ограниченным сроком службы
  • 0почему выполнение запросов быстрее с pdo_oci, чем с oci8?
  • 1Блокировка запуска потока Python ()
  • 0Синтаксическая ошибка в полном внешнем соединении?
  • 0сортировка и добавление li в ul asc
  • 0Неразрешенные внешние проблемы, Неразрешенные внешние символы LNK 1120
  • 0Что именно мы хотим, когда мы копируем указатель из одного объекта в другой того же класса? [Дубликат]
  • 1Custom Keras Loss (который НЕ имеет форму f (y_true, y_pred))
  • 1Мой общий класс безопасен для потоков?
  • 1Конвертировать GIF в PNG программно
  • 0Как я могу положить два значения из таблицы MySQL в одну переменную?

Название пакета приложения для Android. однозначно идентифицирует ваше приложение на устройстве, в магазине Google Play и в поддерживаемых сторонних магазинах Android.

Как изменить название пакета в Play Store?

Руководство Android также подтверждает это здесь: Внимание: один раз вы публикуете свое приложение, вы не можете изменить имя пакета. Имя пакета определяет идентификатор вашего приложения, поэтому, если вы его измените, оно будет считаться другим приложением, и пользователи предыдущей версии не смогут выполнить обновление до новой версии.

Как мне переименовать пакет?

** Способ 01 **

  1. Щелкните его правой кнопкой мыши.
  2. Выберите Refactor.
  3. Щелкните Переименовать.
  4. Во всплывающем диалоговом окне нажмите «Переименовать пакет» вместо «Переименовать каталог».
  5. Введите новое имя и нажмите Refactor.
  6. Нажмите «Выполнить рефакторинг» внизу.
  7. Подождите минуту, чтобы Android Studio обновила все изменения.

Могу ли я изменить название пакета Android?

Выделите каждую часть имени пакета, которую вы хотите изменить (не выделяйте все имя пакета), затем: Щелкните правой кнопкой мыши → Рефакторинг → Переименовать → Переименовать пакет. введите новое имя и нажмите (Рефакторинг)

Что должно быть уникальным для каждого APK?

У каждого APK должен быть другой код версии, указанный в атрибуте android: versionCode. Каждый APK не должно точно соответствовать поддержке конфигурации другого APK. То есть в каждом APK должна быть заявлена ​​немного отличающаяся поддержка хотя бы одного из поддерживаемых фильтров Google Play (перечисленных выше).

Какое у вас название пакета?

У всех приложений Android есть имя пакета. Название пакета однозначно идентифицирует приложение на устройстве; он также уникален в магазине Google Play.

Что такое пакеты в Android?

Пакет по сути каталог (папка), которому принадлежит исходный код. Обычно это структура каталогов, которая однозначно идентифицирует ваше приложение; например com. пример. приложение . Затем вы можете создавать пакеты в своем пакете приложения, которые разделяют ваш код; например com.

Как мне узнать название моего пакета?

Метод 1 — из Play Store

  1. Откройте play.google.com в своем браузере.
  2. Используйте панель поиска, чтобы найти приложение, для которого вам нужно название пакета.
  3. Откройте страницу приложения и посмотрите URL-адрес. Имя пакета образует конечную часть URL-адреса, то есть после id = ?. Скопируйте его и используйте по мере необходимости.

Можем ли мы изменить идентификатор приложения для Android?

Каждый Android приложений имеет уникальный ID приложения который выглядит как имя пакета Java, например com. пример. … Ты можешь измениться имя пакета вашего кода (пространство имен кода) и будем не влиять идентификатор приложения, и наоборот. Вы можете или изменить идентификатор приложения посредством рефакторинга переименования или во время сборки.

Какое имя пакета у JSON?

JSON 4) орг. json.

Могу ли я изменить имя пакета в firebase?

Чтобы отредактировать любое из названий вашего проекта: Щелкните рядом с названием либо для имени проекта, либо для общедоступного имени. Введите новое имя. Щелкните Сохранить.

Предположим, это имя пакета: package com.company.name. Как мне изменить company?

P.S. Я видел, как изменить name, но не company. Я использую Android Studio.

18 ответов

Лучший ответ

Ты можешь это сделать:

Измените имя пакета вручную в файле манифеста. Щелкните свой класс R.java и нажмите F6 (Refactor-> Move …). Это позволит вам переместить класс в другой пакет, и все ссылки на этот класс будут обновлены.

Ссылка: Как переименовать имя пакета Android?


51

Community
23 Май 2017 в 14:55

текущий пакет: com.company.name

Новый пакет: com.mycomapny.name

Шаги: 1) Предположим, вы находитесь на этом экране, показанном ниже.

enter image description here

2) Откройте панель проекта и щелкните значок настроек.

3) Снимите флажок Компактные пустые средние пакеты.

4) Теперь ваша посылка разбита на отдельные части, как показано ниже.

5) щелкните правой кнопкой мыши по «компании», выберите «Рефакторинг» -> выберите переименовать -> переименовать каталог.

enter image description here

6) Теперь ваша «компания» была изменена на новую «mycomapny», и изменения были отражены, как показано на рисунке ниже.

enter image description here

7) Теперь измените имя пакета в файле AndroidManifest.xml.

enter image description here

8) Откройте build.gradle уровня приложения и измените имя пакета.

enter image description here

9) вы получите сообщение об ошибке «Невозможно разрешить символ« R »».

10) Удалите строку, которая дает эту ошибку, и студия автоматически импортирует новый файл R.

11) Если у вас несколько файлов, воспользуйтесь функцией поиска и замены, нажав «Cntrl + Shift + R».

Или «Выберите Правка-> Найти-> Заменить в пути ..»

enter image description here

12) выберите «Заменить все».


58

Janardhan R
18 Мар 2017 в 11:11

Это сработало для меня из https://stackoverflow.com/a/18637004/127434

Еще один хороший метод: сначала создайте новый пакет с желаемым именем, щелкнув правой кнопкой мыши папку java -> новый -> пакет.

Затем выберите и перетащите все свои классы в новый пакет. AndroidStudio повсюду выполняет рефакторинг имени пакета.

Наконец, удалите старый пакет.


33

Community
23 Май 2017 в 15:34

В Android Studio это можно сделать следующим образом:

Например, если вы хотите изменить com.example.app на iu.awesome.game, тогда:

  1. На панели проекта щелкните маленький значок шестеренки (введите здесь описание изображения)
  2. Снимите флажок / снимите флажок Компактные пустые средние пакеты введите здесь описание изображения
  3. Ваш каталог пакетов теперь будет разбит на отдельные каталоги
  4. Индивидуально выберите каждый каталог, который вы хотите переименовать, и:

    • Нажмите правой кнопкой мыши
    • Выбрать рефакторинг

    • Нажмите «Переименовать».

    • Во всплывающем диалоговом окне нажмите «Переименовать пакет» вместо «Переименовать». Каталог

    • Введите новое имя и нажмите «Рефакторинг».

    • Нажмите «Выполнить рефакторинг» внизу

    • Подождите минуту, пока Android Studio обновит все изменения

    • Примечание. При переименовании com в Android Studio может появиться предупреждение. В таком случае выберите «Переименовать все»введите здесь описание изображения

      <старт = «5»>

    • Теперь откройте файл сборки Gradle (build.gradle — обычно приложение или мобильное устройство). Обновите applicationId в defaultConfig на новое имя пакета и синхронизируйте Gradle, если он еще не был обновлен автоматически: введите здесь описание изображения

    • Возможно, вам потребуется изменить атрибут package= в манифесте.

    • Очистить и восстановить.

    • Готово! В любом случае, Android Studio должна немного упростить этот процесс.


15

ibad ur rahman
11 Фев 2019 в 08:19

Решение @Luch Filip хорошо работает, если вы просто хотите переименовать пакет приложения. В моем случае я тоже хочу переименовать исходный пакет, чтобы не путать вещи.

Требуется всего 2 шага:

  1. Нажмите на исходную папку, например. com.company.example> Shift + F6 (Рефакторинг-> Переименовать …)> Переименовать пакет > введите желаемое имя.

  2. Перейдите в свой AndroidManifest.xml, щелкните имя своего пакета> Shift + F6 (Refactor-> Rename …)> введите то же имя, что и выше.

На шаге 1 ваша папка R.java будет автоматически переименована, и вы сразу сможете приступить к сборке.


8

Xakep
23 Апр 2015 в 16:45

Ниже приведены четыре шага:

  1. Щелкните папку приложения ниже:

enter image description here

com.new25.impro. нажмите Shift + F6 {Refactor-> Rename …} , чтобы переименовать пакет, и нажмите refactor.

  1. После этого посмотрите на андроид-монитор. Это шоу меняется везде, где указано название пакета. Щелкните refactor.

  2. Зайдите в модуль app:change идентификатор приложения для вас, как это имя поместили. и нажмите sync now.

  3. Теперь вы можете изменить имя пакета на то, что вам нравится.


5

tiny sunlight
11 Янв 2016 в 17:57

Я прочитал почти все ответы. Но я думаю, что одного не хватает. Иногда я могу ошибаться. Я использовал метод ниже, и он работает.

3 Методы изменения имени пакета в Android Studio

  1. Выберите свой пакет и щелкните правой кнопкой мыши , Рефакторинг -> Переместить .
  2. Выберите Переместить пакет из «вашего пакета» в другой пакет и нажмите ОК.
  3. Появится новое диалоговое окно, в котором говорится, что несколько каталогов соответствуют пакету «ваш пакет», и нажмите Да .
  4. Введите новое имя пакета, за исключением последнего уровня или фамилии. Означает, что вы хотите переименовать пакет в «info.xyz.yourapplication». Затем введите «info.xyz» и оставьте только «ваше приложение».
  5. Нажмите Рефакторинг .
  6. Новое диалоговое окно Информация о пакете.xyz не существует. Вы хотите его создать ?. Нажмите Да .
  7. Нажмите Выполнить рефакторинг .
  8. Щелкните правой кнопкой мыши новый пакет, чтобы изменить фамилию. Рефакторинг-> Переименовать .
  9. Переименовать пакет
  10. введите новое имя и нажмите Выполнить рефакторинг .
  11. Удалите все старые каталоги пакетов.
  12. Измените ApplicationId в файле build.gradle и нажмите синхронизировать сейчас .


4

Jacob George
21 Июл 2019 в 07:49

Если имя домена / пакета вашей компании очень длинное, это сложнее.

Для меня это было недостающее звено. Вам нужно выбрать файлы проекта -> настройки -> затем снять флажок «компактные пустые средние классы».


2

DivineChaos
23 Дек 2015 в 20:13

1) Откройте папку проекта в Android Studio.
2) Выберите папку приложения -> щелкните правой кнопкой мыши и выберите рефакторинг .
3) Нажмите на движение. Он спросит, для какого типа имени пакета у вас есть полное имя пакета, и он попросит создать новый пакет да создать новый автоматически, он попросит gradle на sync.


2

Asim K T
23 Июл 2016 в 12:24

Чтобы переименовать имя пакета в Android Studio, щелкните значок настройки в разделе проекта и снимите флажок Компактные пустые средние пакеты, после чего пакет разделится на несколько имен папок, затем щелкните правой кнопкой мыши папку, в которой нужно изменить имя, нажмите на рефакторинг-> Переименовать-> Введите имя, которое вы хотите изменить -> Рефакторинг -> Каталог рефакторинга, затем импортируйте файл R.java во весь проект. Работает на меня.


2

Deepika kapila
23 Сен 2016 в 18:17

Самый простой способ сделать это — переименовать корневую папку приложения с com.example.MyApp на com.newcompanyname.MyNewAppName, а затем заменить все вхождения старого пути на новый путь в любой IDE, которую вы используете.


0

Prof
17 Апр 2016 в 03:56

Я нашел другое решение для переименования пакета во всем проекте:

Откройте файл в пакете. IntelliJ отображает хлебные крошки файла над открытым файлом. На пакете, который вы хотите переименовать: щелкните правой кнопкой мыши> Рефакторинг> Переименовать. Это переименовывает каталог package / во всем проекте.


0

Thasneem
14 Июн 2016 в 10:09

Я также столкнулся с той же проблемой, и вот как я решил: —

Я хочу изменить имя пакета np.com.shivakrstha.userlog на np.edu.khec.userlog

Я выбрал shivakrstha и нажал Shift + F6 для Rename Refract и переименовал его в khec .

Наконец, используйте то же имя пакета в AndroidManifest.xml , applicationId в build.gradle и не забудьте перестроить свой проект .

Примечание. — Я попытался изменить np на jp , поэтому выбрал np и нажал Shift + F6 для Переименовать Refract и переименован в jp , можно изменить и другие.


0

ersks
19 Июл 2016 в 06:27

Это может вам помочь: 1) Откройте файл вашего пакета. 2) Android Studio отображает хлебные крошки файла над открытым файлом. На пакете, который вы хотите переименовать: щелкните правой кнопкой мыши> Рефакторинг> Переименовать.

enter image description here


0

Bagesh Sharma
14 Дек 2016 в 07:48

Привет, я нашел самый простой способ сделать это.

  1. Создайте новый проект с желаемым именем пакета
  2. скопируйте все файлы из старого проекта в новый (все файлы в old.bad.oldpackage => new.fine.newpackage, res => res)
  3. скопируйте старый build.graddle в новый build.graddle
  4. копировать старый манифест внутри нового манифеста
  5. Сделайте резервную копию или просто удалите старый проект

Выполнено!


0

Martin Jovial
2 Сен 2017 в 02:07

Я не менял ни одного названия пакета. Следующие два шага сработали для меня. После выполнения следующих действий приложение было установлено как НОВОЕ, несмотря на то, что было два приложения с одинаковым именем пакета.

1) В build.gradle

ApplicationId «mynew.mynewpackage.com»

2) В AndroidManifest.xml android: rules = «mynew.mynewpackage.com.fileprovider»


0

VARUN ISAC
5 Дек 2019 в 15:54

В моем случае, когда я переместил свой файл MainActivity в новую структуру папок пакета, как предписано … он изменил мой AndroidManifest.xml. Наконец, после проверки Logcat я понял, что это проблема, и переименовал ее обратно в «.MainActivity» из «.MainActivity»

    <activity
        android:name=".MainActivity"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">


0

batthis
14 Мар 2021 в 21:38

Рефакторинг-метод студии Android сильно испортился. Так что я сделал это вручную, и он отлично сработал. Также очень просто:

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

-В Android Studio: откройте «Заменить в файлах» и введите старое имя пакета, которое нужно заменить новым, и git замените все.

-Закройте Android Studio.

-Вручную переименуйте каталоги в app / src / main / java / … и app / src / test / java / … и app / src / androidTest / java / …

-Откройте Android Studio и очистите проект, перестройте проект -> и готово!


0

Martin
18 Сен 2021 в 21:11

Иногда возникают ситуации, когда по окончанию работы над проектом обнаруживается, что имя пакета, заданного при создании проекта, следует изменить. Подобная ситуация может возникнуть, если в магазине приложений Google Play данное имя уже используется или же, к примеру, вы допустили ошибку при создании проекта и теперь не можете обновить свое приложение. Такая неприятность легко решается если вы использовали в качестве IDE старенький Eclipse,но вот с Android Studio дела обстоят немного хуже.

Попытка сделать рефакторинг имени пакета в студии приводит к тому, что корректно изменится лишь название проекта – com.name.appname. Это происходит потому, что Anndroid Studio объединяет средние имена пакета (по сути папки) в одно название и считает остальную часть принадлежащей конкретному разработчику или компании, а значит является их идентификатором. Но все же изменить средние имена пакета можно и без особых проблем. Первым способом является изменение название папок внутри проекта, но за этим последует рутинное изменение всех связей в проекте, к тому же и так тормозной Gradle начнёт капризничать пуще прежнего и привести его работу в порядок будет крайне сложно. Потому я рекомендую воспользоваться вторым, более простым и быстрым способом полного изменения имени пакета.
Для начала необходимо открепить объединение средних имен в пакете, для этого нужно выбрать параметры отображения структуры проекта, которая находится над самой текстурой и убрать галочку “Compact Empty Middle Packages”.

Когда имена будут откреплены, каждое из имён можно изменить отдельно. Меняем необходимые имена выбрав из контекстного меню Refactor – > Rename или нажав сочетание клавиш Shift+F6. При появлении предупреждения нажимаем кнопку Rename Package.

При изменении первого имени пакета – com/ru/ua необходимо нажать “Rename all”, так как внутри этой папки расположены паки библиотек, в которых так же необходимо заменить имена.
Теперь имя пакета изменено, связи в классах переписаны, но настройки проекта еще не знают что мы что-то сделали. Для оповещения открываем файл с настройками Gradle который называется build.gradle (Module:app), находим в нём следующий участок кода и изменяем имя пакета на новое.

defaultConfig {

applicationId "com.name.test"

minSdkVersion 14

targetSdkVersion 21

versionCode 1

versionName "1.0"

 }

В большинстве случаев Gradle сам определит, что были внесены изменения и предложит синхронизироваться с проектом, показав соответствующее уведомление в правом верхнем углу. Но если этого не произошло —  необходимо выполнить синхронизацию вручную. Для этого отправляемся в меню студии Tools –> Android –> Sync Project With Gradle Files .
Последнее что осталось сделать, это изменить имя пакета в манифесте, хотя для активностей имена уже будут изменены. Открываем файл манифеста AndroidManifest.xml и в самом верху изменяем имя

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

     package="com.awesomedevelop.test" > 

Если после выполнения всех шагов Android Studio не сможет инициализировать R.java , и будут выводиться соответствующие уведомления «Cannot resolve symbol R» — необходимо очистить проект перейдя в соответствующее меню студии Build -> Clean Project.

Автор
Unknown

Android разработчик и Google-фил. В рабочее время пишу код, в свободное — его читаю. Google+

Понравилась статья? Поделить с друзьями:
  • Как изменить имя на фураффинити
  • Как изменить имя пабг мобайл на телефоне айфон
  • Как изменить имя на форуме самп рп
  • Как изменить имя операционной системы
  • Как изменить имя на форуме радмир рп