Reputation: 44315
My main activity starts with the following:
package com.example.alexander.bootintervals;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.example.alexander.libraryproject.MyLogger;
public class MainActivity extends AppCompatActivity {
...
Now I am using some code from in other package, for example in package com.example.alexander.libraryproject
. How can I get the name of the main app/package of where the main activity is defined? Is there a way to extract the string com.example.alexander.bootintervals
from a code called which resides in com.example.alexander.libraryproject
?
Upvotes: 2
Views: 2134
Reputation:
so simple:
String full_package_name = MainActivity.class.getCanonicalName();
if you dont have any context in you module do as below: 1- define an interface like below in your module (lets say X module):
public interface Provider{
public String getPackageName();
}
2- in your App modules (lets say A and B) you need to send an implementation of this interface to the module X like below:
public class ProviderImpl implements Provider{
@Override
public String getPackageName()
{
return BuildConfig.APPLICATION_ID;
}
}
then send the implementation to the module X some how:
ModuleX obj=new ModuleX(new ProviderImpl());
you can add whatever you want to this interface and make your Modules implement it.
then in your module X just call getPackageName() method of the implementation and get your packageName ;)
Upvotes: 0
Reputation: 603
you can add static function getInstance()
in MainActivity
that return the context of it and you can use it to get it's context and calling function that gives you package name as following:
public class MainActivity extends AppCompatActivity {
private static MainActivity instance;
public MainActivity () {
instance = this;
}
public static MyApplication getInstance() {
return instance;
}
and use it as following:
MainActivity.getInstance.getPackageName();
Upvotes: 0
Reputation: 3852
Try MainActivity.class.getCanonicalName()
and ignore the last period and the class name that follows it.
Upvotes: 0
Reputation: 376
You could use this to get the full package name
String packageName = BuildConfig.APPLICATION_ID
Upvotes: 1