代码之家  ›  专栏  ›  技术社区  ›  d-man

android从服务启动活动

  •  129
  • d-man  · 技术社区  · 14 年前

    安卓:

    public class LocationService extends Service {
    
    @Override
        public void onStart(Intent intent, int startId) {
            super.onStart(intent, startId);
            startActivity(new Intent(this, activity.class));
        }
    }
    

    我是从 Activity

    活动 如果条件满足启动

    startService(new Intent(WozzonActivity.this, LocationService.class));
    

    从我的 LocationService 活动 在服务舱?

    6 回复  |  直到 7 年前
        1
  •  352
  •   Tim Abhishek Kumar    9 年前

    从服务类内部:

    Intent dialogIntent = new Intent(this, MyActivity.class);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(dialogIntent);
    
        2
  •  18
  •   Nikhil Agrawal    11 年前

    对我有效的是:

     Intent dialogIntent = new Intent(this, myActivity.class);
     dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     this.startActivity(dialogIntent);
    

    在我的一个子类中,存储在一个单独的文件中,我必须:

    public static Service myService;
    
    myService = this;
    
    new SubService(myService);
    
    Intent dialogIntent = new Intent(myService, myActivity.class);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    myService.startActivity(dialogIntent);
    

    所有其他的答案都给了我一个答案 nullpointerexception .

        3
  •  10
  •   José Braz    4 年前

    不再允许从服务(前台或后台)启动活动。

    文档中仍然有一些限制

    https://developer.android.com/guide/components/activities/background-starts

        4
  •  8
  •   kellogs    13 年前

    另一件值得一提的事情是:当我们的任务在后台时,上面的答案可以很好地工作,但是如果我们的任务(由服务+一些活动组成)在前台(即用户可以看到我们的一个活动),我能使它工作的唯一方法是这样的:

        Intent intent = new Intent(storedActivity, MyActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        storedActivity.startActivity(intent);
    

    我不知道ACTION\u VIEW或FLAG\u ACTIVITY\u NEW\u TASK在这里是否有实际用途。成功的关键是

    storedActivity.startActivity(intent);
    

    当然,如果没有再次实例化活动,请将活动重新排序到前面。祝你好运!

        5
  •  1
  •   Martin Zeitler    8 年前

    Context Service ;能够获得(包) 相似:

    Intent intent = new Intent(getApplicationContext(), SomeActivity.class);
    
        6
  •  0
  •   james    10 年前

    或者,

    您可以使用自己的应用程序类并从任何需要的地方调用(尤其是非活动)。

    public class App extends Application {
    
        protected static Context context = null;
    
        @Override
        public void onCreate() {
            super.onCreate();
            context = getApplicationContext();
        }
    
        public static Context getContext() {
            return context;
        }
    
    }
    

    <application android:name="yourpackage.App" ...
    

    然后打电话:

    App.getContext();