从ServiceAdapter中获取数据

时间:2014-08-28 15:59:35

标签: java android android-service baseadapter

我有一个使用ViewHolders的BaseAdapter类来显示已检查的应用列表。我使用SharedPreferences存储选中的应用程序,以便检查已检查的应用程序。我想要实现的是将我的服务类中的已检查应用程序理想地存储在arraylist或类似的东西中。

问题是密钥是我以前用来获取值在BaseAdapter类中的,我无法从服务类中获取它所以我不得不重新创建获取包列表和迭代的方法通过for循环。

我也无法检查我的Service类中是否已选中holder复选框,因为这是在我的BaseAdapter类中完成的。

尽管在BaseAdapter中传递了上下文并将getApplicationContext与SharedPreferences一起使用,但我无法获得服务类中已检查应用的列表。我不知道现在在哪里转。我已经尝试过使用静态变量,尝试从BaseAdapter类获取上下文等所有内容。

这是我的适配器类(我已经评论了我在哪里获得了被检查的应用程序):

package com.ibc.android.demo.appslist.app;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.spicycurryman.getdisciplined10.app.R;

import java.util.ArrayList;
import java.util.List;

//

public class ApkAdapter extends BaseAdapter {

    //Pastebin link:  http://pastebin.com/LGRicg4U , http://pastebin.com/c4WfmhMK , http://pastebin.com/gFuuM4dY, http://pastebin.com/4Q7EP9G4
    // http://pastebin.com/Te2g072w,  http://pastebin.com/NLT5iUiA ,

    SharedPreferences sharedPrefs;
    List<PackageInfo> packageList;
    ArrayList <String> appchecklist;
    static ArrayList <String> newappchecklist;
    Context mContext;

    Activity context;
    PackageManager packageManager;
    boolean[] itemChecked;


    String PACKAGE_NAME;
    static TinyDB appcheckdb;

    public ApkAdapter(Activity context, List<PackageInfo> packageList,
                      PackageManager packageManager) {
        super();
        this.context = context;
        this.mContext = mContext;

        this.packageList = packageList;
        this.packageManager = packageManager;
        itemChecked = new boolean[packageList.size()];
        appchecklist =  new ArrayList<String>();
        newappchecklist =  new ArrayList<String>();

        appcheckdb = new TinyDB(context);


    }

    public ApkAdapter(Context heartBeat) {

    }


    private class ViewHolder {
        TextView apkName;
        CheckBox ck1;
        TextView packageName;
    }

    public int getCount() {
        return packageList.size();
    }

    public Object getItem(int position) {
        return packageList.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        LayoutInflater inflater = context.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.installed_apps, null);
            holder = new ViewHolder();

            holder.apkName = (TextView) convertView
                    .findViewById(R.id.appname);
            holder.ck1= (CheckBox)convertView
                    .findViewById(R.id.checkBox1);
            holder.packageName = (TextView) convertView.findViewById(R.id.app_package);



            convertView.setTag(holder);
            //holder.ck1.setTag(packageList.get(position));

        } else {

            holder = (ViewHolder) convertView.getTag();
        }



        // ViewHolder holder = (ViewHolder) convertView.getTag();
        final PackageInfo packageInfo = (PackageInfo) getItem(position);



        Drawable appIcon = packageManager
                .getApplicationIcon(packageInfo.applicationInfo);



        // Make sure to define it again!
        PACKAGE_NAME = packageInfo.packageName;


        final String appName = packageManager.getApplicationLabel(
                packageInfo.applicationInfo).toString();
        appIcon.setBounds(0, 0, 80, 80);
        holder.apkName.setCompoundDrawables(appIcon, null, null, null);
        holder.apkName.setCompoundDrawablePadding(15);
        holder.apkName.setText(appName);
        //holder.packageName.setText(PACKAGE_NAME);


        holder.ck1.setChecked(false);


        if (itemChecked[position])
            holder.ck1.setChecked(true);
        else
            holder.ck1.setChecked(false);








        for(int i= 0; i<packageList.size(); i++){



            PACKAGE_NAME = packageInfo.packageName;
            //Log.d("lol", PACKAGE_NAME);

            sharedPrefs = context.getSharedPreferences(PACKAGE_NAME, Context.MODE_PRIVATE);

            newappchecklist = appcheckdb.getList("appcheck");

            holder.ck1.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME,false));


        }



        // appchecklist has all the checked apps!!!!!

        // it is right here!!!!!!

        if(holder.ck1.isChecked()){
            appchecklist.add(packageInfo.packageName);
            appcheckdb.putList("appcheck", appchecklist);
            for (Object data : appchecklist) {
                Log.e("HUH!?: ",(String) data);
            }


        }


        holder.ck1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {



                SharedPreferences.Editor editor = context.getSharedPreferences(packageInfo.packageName, Context.MODE_PRIVATE).edit();

                if (holder.ck1.isChecked()) {
                    itemChecked[position] = true;
                    holder.ck1.setChecked(true);
                    editor.putBoolean(packageInfo.packageName, true);


                    editor.apply();

                } else {
                    itemChecked[position] = false;
                    holder.ck1.setChecked(false);
/*                    editor.putBoolean(packageInfo.packageName, false);


                    editor.apply();*/

                }

            }


        });


        return convertView;

    }


    public void check( View convertView, int position){
        final ViewHolder holder;
        holder = new ViewHolder();
        holder.ck1= (CheckBox)convertView
                .findViewById(R.id.checkBox1);
        convertView.setTag(holder);
        final PackageInfo packageInfo = (PackageInfo) getItem(position);


        PACKAGE_NAME = packageInfo.packageName;



        if(holder.ck1.isChecked()){
            appchecklist.add(packageInfo.packageName);
            appcheckdb.putList("appcheck", appchecklist);
            for (Object data : appchecklist) {
                Log.e("HUH!?: ",(String) data);
            }


        }
    }



    public static ArrayList getArrayList()
    {
        newappchecklist = appcheckdb.getList("appcheck");

        return newappchecklist;
    }






}

这是我的服务类!我评论了我想要获取列表的位置:

package com.ibc.android.demo.appslist.app;

import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

public class HeartBeat extends Service {



    private static final String TAG = HeartBeat.class.getSimpleName();
    public Timer TIMER;

    String CURRENT_PACKAGE_NAME;


    private static Set<AccessGranted> mAccessGrantedList = new HashSet<AccessGranted>();
    private Set<String> mLockedApps = new HashSet<String>();
    private long lastModified = 0;
    private BroadcastReceiver mScreenStateReceiver;
    private BroadcastReceiver mAccessGrantedReceiver;
    private File mLockedAppsFile;
    private ArrayList newArrayList = null;
    SharedPreferences sharedPrefs;
    PackageManager pm = null;
    List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();





    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        startService(new Intent(this, HeartBeat.class));






        pm = getPackageManager();

        List<PackageInfo> packageList = pm
                .getInstalledPackages(PackageManager.GET_PERMISSIONS);



        for(PackageInfo pi : packageList) {
            boolean b = isSystemPackage(pi);
            boolean c = isSystemPackage1(pi);

            if(!b || !c ) {
                packageList1.add(pi);
            }

        }

        //TRYING TO GET IT OVER HERE!
        for(int i = 0; i < packageList1.size(); i++) {
            Log.e("hannnnnnn values       ", packageList1.get(i)+ "");
            sharedPrefs = getApplicationContext().getSharedPreferences(String.valueOf(packageList1.get(i)), Context.MODE_PRIVATE);


        }



        //TRYING TO CHECK IT OVER HERE!

        Map<String, ?> allEntries = sharedPrefs.getAll();
        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            Log.e("map values", entry.getKey() + ": " + entry.getValue().toString());
       }


        // Log.i("LocalService", "Received start id " + startId + ": " +
        // intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        if (TIMER == null) {

            TIMER = new Timer(true);
            TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);

            mScreenStateReceiver = new BroadcastReceiver() {

                private boolean screenOff;

                @Override
                public void onReceive(Context context, Intent intent) {



                    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                        screenOff = true;
                    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                        screenOff = false;
                    }

                    if (screenOff) {
                        Log.i(TAG, "Cancel Timer");
                        TIMER.cancel();
                    } else {
                        Log.i(TAG, "Restart Timer");
                        TIMER = new Timer(true);
                        TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
                    }
                }
            };

            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            registerReceiver(mScreenStateReceiver, filter);

            mAccessGrantedReceiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    String packageName = intent.getStringExtra("packageName");
                    if (action.equals(Constants.ACTION_GRANT_ACCESS) && packageName != null) {
                        AccessGranted ag = new AccessGranted(packageName);
                        mAccessGrantedList.remove(ag);
                        mAccessGrantedList.add(ag);
                    }
                }
            };

            IntentFilter filter2 = new IntentFilter(Constants.ACTION_GRANT_ACCESS);
            registerReceiver(mAccessGrantedReceiver, filter2);
        }
        // this.stopSelf();



        //startforeground goes here



        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        startService(new Intent(this, HeartBeat.class));
    }
    private boolean isSystemPackage(PackageInfo pkgInfo) {
        return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
                : false;
    }

    private boolean isSystemPackage1(PackageInfo pkgInfo) {
        return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) ? false
                : true;
    }



    private class LockAppsTimerTask extends TimerTask {




        @Override
        public void run() {
            ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

            try {
                //List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
                ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
                        .getRunningTasks(1);
                ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
                String activityOnTop = ar.topActivity.getPackageName();

                // Log.e("activity on Top", "" + activityOnTop);
                //   Log.e(" My package name", "" + getApplicationContext().getPackageName());








//                newArrayList = ApkAdapter.getArrayList();
//                for (Object data : newArrayList) {


// Provide the packagename(s) of apps here, you want to show password activity
                    if ((activityOnTop.contains("com.android.camera")) &&
                            (!activityOnTop.contains(getApplicationContext().getPackageName()
                            ))) {  // you have to make this check even better


                        Intent i = new Intent(getApplicationContext(), LockScreenActivity.class);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        i.putExtra( "", "");
                        startActivity(i);
                    }
                //}


            } catch (Exception e) {
                Log.e("Foreground App", e.getMessage(), e);
            }
        }



    }

}

最终,我可以尝试完成工作,以便在我的服务类中获取已检查应用的列表。所以,无论什么时候我运行服务,我都有已检查的应用程序列表。每当应用程序打开时,重新打开,重新启动或执行任何操作等等。

帮助表示赞赏。如果还有什么我可以补充的,请告诉我。

1 个答案:

答案 0 :(得分:0)

我最终在SharedPreferences中创建了一个新数据库,仅存储已检查的应用程序。

这是我的BaseAdapter类:

package com.ibc.android.demo.appslist.app;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.spicycurryman.getdisciplined10.app.R;

import java.util.HashSet;
import java.util.List;

//

public class ApkAdapter extends BaseAdapter {

    //Pastebin link:  http://pastebin.com/LGRicg4U , http://pastebin.com/c4WfmhMK , http://pastebin.com/gFuuM4dY, http://pastebin.com/4Q7EP9G4
    // http://pastebin.com/Te2g072w,  http://pastebin.com/NLT5iUiA ,

    SharedPreferences sharedPrefs;
    SharedPreferences sharedPrefsapp;

    List<PackageInfo> packageList;

    Activity context;
    PackageManager packageManager;
    boolean[] itemChecked;
    HashSet checked;


    String PACKAGE_NAME;

    public ApkAdapter(Activity context, List<PackageInfo> packageList,
                      PackageManager packageManager) {
        super();
        this.context = context;

        this.packageList = packageList;
        this.packageManager = packageManager;
        itemChecked = new boolean[packageList.size()];


    }
    private class ViewHolder {
        TextView apkName;
        CheckBox ck1;
        TextView packageName;
    }

    public int getCount() {
        return packageList.size();
    }

    public Object getItem(int position) {
        return packageList.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        LayoutInflater inflater = context.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.installed_apps, null);
            holder = new ViewHolder();

            holder.apkName = (TextView) convertView
                    .findViewById(R.id.appname);
            holder.ck1= (CheckBox)convertView
                    .findViewById(R.id.checkBox1);
            holder.packageName = (TextView) convertView.findViewById(R.id.app_package);



            convertView.setTag(holder);
            //holder.ck1.setTag(packageList.get(position));

        } else {

            holder = (ViewHolder) convertView.getTag();
        }



        // ViewHolder holder = (ViewHolder) convertView.getTag();
        final PackageInfo packageInfo = (PackageInfo) getItem(position);



        Drawable appIcon = packageManager
                .getApplicationIcon(packageInfo.applicationInfo);



        // Make sure to define it again!
        PACKAGE_NAME = packageInfo.packageName;


        final String appName = packageManager.getApplicationLabel(
                packageInfo.applicationInfo).toString();
        appIcon.setBounds(0, 0, 80, 80);
        holder.apkName.setCompoundDrawables(appIcon, null, null, null);
        holder.apkName.setCompoundDrawablePadding(15);
        holder.apkName.setText(appName);
        //holder.packageName.setText(PACKAGE_NAME);


        holder.ck1.setChecked(false);


        if (itemChecked[position])
            holder.ck1.setChecked(true);
        else
            holder.ck1.setChecked(false);




        // CHANGE UP EVERYTHING! MAKE THIS SHIT WORK, TIGGA!





        checked = new HashSet();

            PACKAGE_NAME = packageInfo.packageName;
            //Log.d("just here: ", PACKAGE_NAME);

            sharedPrefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
            sharedPrefsapp = context.getSharedPreferences("appdb", Context.MODE_PRIVATE);





        holder.ck1.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME,false));







        holder.ck1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {



                SharedPreferences.Editor editor = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE).edit();
                SharedPreferences.Editor editorapp = context.getSharedPreferences("appdb", Context.MODE_PRIVATE).edit();

                if (holder.ck1.isChecked()) {

                    itemChecked[position] = true;
                    holder.ck1.setChecked(true);
                    editor.putBoolean(packageInfo.packageName, true);
                    editorapp.putString(packageInfo.packageName, packageInfo.packageName);



                    editor.apply();
                    editorapp.apply();

                   // sharedPrefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);


                } else {
                    itemChecked[position] = false;
                    holder.ck1.setChecked(false);
                    editor.putBoolean(packageInfo.packageName, false);
                    editorapp.remove(packageInfo.packageName);


                    editor.apply();
                    editorapp.apply();
                    //sharedPrefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);




                }

            }



        });





        return convertView;

    }
}

我使用键“appdb”检索服务类中的值

package com.ibc.android.demo.appslist.app;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class HeartBeat extends Service {

    ArrayList<String> packagezList;
    SharedPreferences sharedPrefs;
    Map<String, ?> allEntries;
    SharedPreferences sharedPrefsapp;



    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //startService(new Intent(this, HeartBeat.class));





        sharedPrefs = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
        sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
        allEntries= null;
        allEntries = sharedPrefsapp.getAll();
        //prefix = "m";
        packagezList= null;


        packagezList = new ArrayList<String>();




        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            //Log.e("right key: ", entry.getKey() + "right value: " + entry.getValue().toString()  );
            packagezList.add(entry.getKey());





        }



        for(Object object: packagezList){
            Log.e("YO!", (String) object);
        }

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

        try {
            //List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
            ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
                    .getRunningTasks(1);
            ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
            String activityOnTop = ar.topActivity.getPackageName();

            // Log.e("activity on Top", "" + activityOnTop);
            //   Log.e(" My package name", "" + getApplicationContext().getPackageName());








            //for (Object data : newArrayList) {

            for(Object object: packagezList){

// Provide the packagename(s) of apps here, you want to show password activity
                if ((activityOnTop.contains((CharSequence) object)) &&
                        (!activityOnTop.contains(getApplicationContext().getPackageName()
                        ))) {  // you have to make this check even better


                    Intent i = new Intent(getApplicationContext(), LockScreenActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    i.putExtra( "", "");
                    startActivity(i);
                }

            }


        } catch (Exception e) {
            // Log.e("Foreground App", e.getMessage(), e);
        }

        Intent ishintent = new Intent(this, HeartBeat.class);
        PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pintent);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),150000, pintent);



        return START_STICKY;

}

        // Log.i("LocalService", "Received start id " + startId + ": " +
        // intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.

    @Override
    public void onDestroy() {

        Intent ishintent = new Intent(this, HeartBeat.class);
        PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pintent);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),150000, pintent);
        //startService(new Intent(this, HeartBeat.class));

    }


        // this.stopSelf();
        //startforeground goes here



    }