我希望这是这个问题的合适标题。现在我有两节课。主类和ApplicationOperations类。最初我有一个方法卸载应用程序和listall安装的应用程序,它在我的主类中运行良好。现在,当我将它们移动到另一个类(为了扩展)时,它们不起作用。我对意图一无所知,因为我还是一个新手,所以任何帮助都会很棒!
我在
上收到错误PackageManager pm = getPackageManager(); <--method undefined???
and
StartActivity <---method undefined.
这是守则。如果您还有其他需要,请告诉我们:
主要文件:
package com.IPR2.viewlog;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Main extends Activity {
private TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
FileOperations fileOperations = new FileOperations();
ApplicationOperations applicationOperations = new ApplicationOperations();
Testing testing = new Testing();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
}
}
ApplicationOperations.java
package com.IPR2.viewlog;
import java.util.List;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;
public class ApplicationOperations {
FileOperations fileOperations = new FileOperations();
public void UninstallApplication(String packageName)
{
Uri packageURI = Uri.parse("package:"+packageName);
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
startActivity(uninstallIntent);
}
public void ListAllInstalledApplications()
{
PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm
.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages)
{
fileOperations.AppendFile("Installed package :" +
packageInfo.packageName + "\n", "Installed_packages.txt");
// tv.append("Installed package :" + packageInfo.packageName + "\n");
}
}
}
答案 0 :(得分:3)
当你的代码
PackageManager pm = getPackageManager();
在继承自Activity类(类Main)的类中,它起作用,因为实际上getPackageManager()是Context.getPackageManager。 Activity扩展了Context类,因此一切都很好。 但是您将此代码移动到新类中,该类不会扩展与Context相关的任何内容。因此,您有编译错误。 你应该以某种方式将一个上下文传递给你的新类(ApplicationOperations)并使用它
PackageManager pm = mContext.getPackageManager()
答案 1 :(得分:2)
getPackageManager()需要Context。
您可以在ApplicationOperations类中添加Context或Main成员,并添加一个init方法以将Main传递给它。
private Main context;
public ApplicationOperations(Main activity) {
this.context = activity;
}
然后在需要时使用它
PackageManager pm = context.getPackageManager();