我在android中开发应用程序锁。我试图使用服务来保持我的应用程序在后台运行,但它似乎无法启动。我还想为用户想要锁定的所选应用程序实现密码屏幕。我编写了一些代码:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
private ListView list;
ArrayList<Model> data;
ApkAdapter adapter;
private PackageManager packageManager;
TextView tView;
ProtectAppProvider pap;
CheckBox chk;
ArrayList<String> protectedApps;
List<PackageInfo> appsList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
tView = (TextView) findViewById(R.id.appname);
list = (ListView) findViewById(R.id.applist);
appsList = getPackageManager().getInstalledPackages(0);
data = new ArrayList<Model>();
initialization();
getApps();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_bar, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public void onClick(View view) {
boolean isChecked;
boolean diditwork = true;
int getPosition = (Integer) view.getTag();
Model obj = data.get(getPosition);
String aName = obj.getAppName();
String pName = obj.getpName();
protectedApps = new ArrayList<String>();
pap = new ProtectAppProvider(getApplicationContext());
if (((CheckBox) view).isChecked()) {
try {
isChecked = true;
data.get(getPosition).setSelected(isChecked);
protectedApps.add(aName);
pap.open();
pap.createEntry(aName,pName);
pap.close();
} catch (Exception e) {
diditwork = false;
} finally {
if (diditwork)
Toast.makeText(this, "LOCKED", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Fail to lock!", Toast.LENGTH_SHORT).show();
}
} else {
isChecked = false;
data.get(getPosition).setSelected(isChecked);
diditwork = true;
try {
pap.open();
protectedApps.remove(aName);
pap.deleteEntry(aName);
pap.close();
} catch (Exception e) {
diditwork = false;
} finally {
if (diditwork)
Toast.makeText(this, "UNLOCKED", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Fail to unlock", Toast.LENGTH_SHORT)
.show();
}
}
}
public void getApps(){
for (int i = 0; i < appsList.size(); i++) {
PackageInfo p = appsList.get(i);
if (packageManager.getLaunchIntentForPackage(p.packageName) != null
&& ((!p.applicationInfo.loadLabel(getPackageManager())
.toString().equals("VoiceAppLock")))) {
Model model = new Model();
model.setAppName(p.applicationInfo.loadLabel(
getPackageManager()).toString());
model.setAppIcon(p.applicationInfo
.loadIcon((getPackageManager())));
model.setpName(p.packageName);
data.add(model);
Collections.sort(data, Model.AppComparator);
}
}
adapter = new ApkAdapter(MainActivity.this, data, packageManager,
protectedApps);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
}
public void initialization(){
Intent intent = new Intent(this, LockService.class);
this.startService(intent);
}
}
LockServices.java
public class LockService extends Service {
private ProtectAppProvider pap;
private ArrayList<String> protectApps;
private String appname;
private static LockService instance;
private String tag;
public LockService() {
this.pap = new ProtectAppProvider(this);
this.protectApps = new ArrayList<String>();
this.tag = "LS";
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
updateList();
Toast.makeText(getApplicationContext(), "Service Created",
Toast.LENGTH_LONG).show();
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Destroy",
Toast.LENGTH_LONG).show();
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.i(tag, "Service onStartCommand " + startId);
final int currentId = startId;
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 3; i++) {
long endTime = System.currentTimeMillis() + 10 * 1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
updateList();
checkRunningApps();
Log.i(tag, "Service running " + currentId);
}
}
};
Thread t = new Thread(r);
t.start();
return Service.START_STICKY;
}
public void updateList() {
appname = "";
pap.open();
Cursor c = pap.getPacName();
if (c.moveToFirst()) {
do {
appname = c.getString(0);
protectApps.add(appname);
} while (c.moveToNext());
}
pap.close();
}
public void checkRunningApps() {
ActivityManager mActivityManager = (ActivityManager) getSystemService("activity");
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop=ar.topActivity.getPackageName().toString();
Log.i("activity on TOp", "" + activityOnTop);
// Provide the packagename(s) of apps here, you want to show password
// activity
if(this.protectApps.contains(activityOnTop)){
Intent lockIntent = new Intent(LockService.this, Password.class);
lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
LockService.this.startActivity(lockIntent);
}
}
}
Password.java
public class Password extends Activity implements OnClickListener {
private EditText userpass;
private Button submit;
private Button cancel;
private String password;
private int counter;
public void findView() {
this.userpass = (EditText) findViewById(R.id.editText1);
this.submit = (Button) findViewById(R.id.button1);
this.cancel = (Button) findViewById(R.id.button2);
this.password = "12345";
this.cancel.setOnClickListener(this);
this.submit.setOnClickListener(this);
this.counter = 0;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.password);
findView();
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(getApplicationContext(), "Password", Toast.LENGTH_LONG)
.show();
findView();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.button1) {
String str2 = this.userpass.getText().toString();
if ((str2 != "") && (str2.equals(this.password))) {
this.finish();
} else {
userpass.setText("");
Toast.makeText(getApplicationContext(), "Wrong Password!", Toast.LENGTH_SHORT).show();
counter++;
if (counter == 3) {
Intent startHomescreen = new Intent(Intent.ACTION_MAIN);
startHomescreen.addCategory(Intent.CATEGORY_HOME);
startHomescreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(startHomescreen);
}
}
} else if (v.getId() == R.id.button2) {
Intent startHomescreen = new Intent(Intent.ACTION_MAIN);
startHomescreen.addCategory(Intent.CATEGORY_HOME);
startHomescreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(startHomescreen);
}
}
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.the.voiceapplock"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@drawable/applauncher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Password"
android:clearTaskOnLaunch="true"
android:excludeFromRecents="true"
android:label="@string/app_name"
android:launchMode="singleInstance"
android:screenOrientation="portrait"
android:stateNotNeeded="true"
android:theme="@*android:style/Theme.NoTitleBar.Fullscreen" />
<service
android:name="com.the.voiceapplock.services.LockService"
android:enabled="true"
android:exported="true" >
</service>
<receiver
android:name="com.the.voiceapplock.services.BootStartUpReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
</application>
</manifest>
请帮助..谢谢:)
答案 0 :(得分:0)
在BootStartReceiver
课程中,试试这个:
public class BootStartReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
// Start sensor service.
intent = new Intent(context, LockServices.class);
context.startService(intent);
}
}
}
您可能还需要在BootStartReceiver
文件中声明AndroidManifest.xml
,如下所示:
<receiver
android:name=".BootStartReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>