CONTENT PROVIDER

A content provider component supplies data from one application to others on request.Such requests are handled by the methods of the ContentResolver class.

cparch

Content Provider

  • Content Provider contains 6 methods : onCreate, insert, delete, update, query, getType.
  • SQLiteOpenHelper is a class that manages DB creation and version management.
  • SQLiteDatabase has methods to create, delete, execute SQL commands.
  • onCreate of Content Provider is called when App is first installed. In this method, SQLiteOpenHelper is created, which further creates  our database and SQLiteDatabase.
  • Data is stored in the form of key value pair in object known as ContentValues .
  • Requests for data retrieval are handled by ContentResolver.It contains 4 methods : insert, delete, update, query.
  • When data has to be inserted into table in DB, ContentValues are passed along with URI of Content Provider by ContentReolver to Content Provider. Content Provider further requests SQLiteDatabase to insert the data in particular table. Then, its work of SQLiteDatabase to insert the data in required table .

 

BROADCAST RECEIVER

Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself.  It receives Action. Action can be –

  • User defined /created by developer /Broadcasted by developer
  • System defined /pre-defined /Broadcasted by android system

Example :

In this example, there is a Receiver (Receiver.java) which receives broadcast actions which are defined in its Intent filter . Actions  defined in Intent filter on BroadcastReceiver can be any ; it may be user defined or system defined. In the given example, there is an action named “action1“. When this action is triggered, Receiver.class will receive the broadcast message and notification is displayed.

In AndroidManifest.xml , intent filter of Receiver.java is as under:


<receiver android:name=".Receiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="action1" />
</intent-filter>
</receiver>

MainActivity.java whose title is “Receiver”


//Here in this activity ,there's a button ,by clicking on that "action1" is triggered and Receiver will receive broadcast message.

public void onClick(View v){
Intent i=new Intent("action1");
sendBroadcast(i);
}

Receiver.java


public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

String action=intent.getAction();

if(action.equals("action1")){
Toast.makeText(context,"Action1 is triggered",Toast.LENGTH_SHORT).show();

NotificationCompat.Builder builder=new NotificationCompat.Builder(context);
//ActivityDemo starts when "ADD" option in notification is clicked
Intent i=new Intent(context,ActivityDemo.class);
PendingIntent pi=PendingIntent.getActivity(context,1001,i,0);

//Call Intent - By clicking on "CALL" icon , keypad will open and the specified mobile number will be automatically written
Intent call=new Intent(Intent.ACTION_DIAL);
call.setData(Uri.parse("tel:924xxxxxxx"));
PendingIntent piCall=PendingIntent.getActivity(context,101,call,0);

builder.setContentIntent(pi);
builder.setDefaults(Notification.DEFAULT_ALL);
builder.setSmallIcon(R.drawable.music);
builder.setContentTitle("Title");
builder.setContentText("This is a notification.");

builder.setStyle(new NotificationCompat.BigTextStyle().bigText("This is a big text .This text gives complete information in multiple lines."));
builder.addAction(android.R.drawable.ic_menu_add, "Add", pi);
builder.addAction(android.R.drawable.ic_menu_call, "Call", piCall);

Notification notification=builder.build();

NotificationManager manager=(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
manager.notify(100,notification);
}
}
}

mainactivity

MainActivity

notification

Notification

SERVICE

A service is a component that runs in the background without needing to interact with the user and it works even if application is destroyed.

Service can take  two states :

  • Start Service : Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.
  • Bind Service : A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC).

For starting a service:

startService(new Intent(getBaseContext(), MyService.class));

For stopping a service :

stopService(new Intent(getBaseContext(), MyService.class));

Example :

When service  is started, MediaPlayer is started and selected song is played. When service is destroyed, MediaPlayer is stopped and all the resources are released. 
MyService.java

public class MyService extends Service {

    MediaPlayer player;

    @Override
    public void onCreate() {
        super.onCreate();
    }

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

        player = new MediaPlayer();
        String songName = intent.getStringExtra("keySong");
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+songName;

        try{
            player.setDataSource(path);
            player.prepare();
            player.start();   //player started
        }catch (Exception e){

        }
	 return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
       
        player.stop();
        player.release();
    }

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

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
}

READING EXTERNAL STORAGE

For reading or writing external storage, add permissions in Manifest file

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This code firstly initialize the path . Then it displays al the image files(.jpg) in listView by storing the objects in an ArrayList(listOfContents). Object(SdObjects) contains the information about images present in external memory.


{//initialize path
String path= Environment.getExternalStorageDirectory().getAbsolutePath();
initList(path);
}

    void initList(String path){
        try {
            File file = new File(path);
            File[] filesArray=file.listFiles();
            String fileName;
            int icon=R.drawable.img;
            for(File file1:filesArray) {
                if (file1.isDirectory()) {
                    initList(file1.getAbsolutePath());
                } else {
                        fileName=file1.getName();
                        if ((fileName.endsWith(".jpg"))
                     		listOfContents.add(new SdObjects(icon,    file1.getName(), file1.getAbsolutePath()));
                        }

                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

filemanager